I'm new to Yii framework. I 'm using Yii framework for my application. Now , the data is extracted from XML file and not from database.The data entered into textfield is also converted to XML file. The model class extends CFormModel . I have a textfield that should allow only integers. I did a front end validation using Javascript that works fine for some browsers but not most. So, I want to do a backend validation using rules(). How can I write the validation rule for this to allow integers.
EDIT
if (isset($_GET['TestForm']['min']) && isset($_GET['TestForm']['max'])) {
$test = $xml->addChild('test');
$test->addChild('min', $_GET['TestForm']['min']?$_GET['TestForm']['min']:"0");
$test->addChild('max', $_GET['TestForm']['max']?$_GET['TestForm']['max']:"500000000");
} else {
$test = $xml->addChild('area');
$test->addChild('min', 0);
$test->addChild('max', 5000000);
}
EDIT 2 simplexml_load_string parser error is the warning shown
in your model suppose the modelname is file.php *create a variable*
public $name;
public function rules()
{
return array(
array('name','numerical', 'integerOnly' => true)
);
}
in view where form is created
here $model is the object
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
</div>
This should do the job
models/yourformmodel.php:
public function rules() {
return array(
array('field', 'required'),
array('field', 'numerical', 'integerOnly' => true),
);
}
Here is good documentation. Just read...
First the setup:
You have a classic problem, you want to verify that a user accepted the contract terms but the value of the acceptance is not stored (bound) in the database... So you extend CFormModle, define the rules and got to validate. With bound variables you validated as part of save. Now you validate() by itself but Validate requires a list of attributes which is not defined in CFormModel. So, what do you do? You do this:
$contract->validate($contract->attributeNames())
Here's the full example:
class Contract extends CFormModel
{
...
public $agree = false;
...
public function rules()
{
return array(
array('agree', 'required', 'requiredValue' => 1, 'message' => 'You must accept term to use our service'),
);
}
public function attributeLabels()
{
return array(
'agree'=>' I accept the contract terms'
);
}
}
Then in the controller you do this:
public function actionAgree(){
$contract = new Contract;
if(isset($_POST['Contract'])){
//$contract->attributes=$_POST['Contract']; //contract attributes not defined in CFormModel
...
$contract->agree = $_POST['Contract']['agree'];
...
}
if(!$contract->validate($contract->attributeNames())){
//re-render the form here and it will show up with validation errors marked!
}