I wrote a custom validation rule to which I am trying to pass some parameters.
One of the parameters should be a return value from a function. However the value does not get passed along.
If I call the same function within the custom rule then I can get the return value. It just doesn’t work for me to set a parameter using this technique…
Here is the code I am using:
// Within the rules:
array('someAttribute', 'customValidation', 'parameter'=>$this->someFunction(), 'anotherParameter'=>'someValue'),
// The function which should return something...
public function someFunction()
{
if ($this->someOtherAttribute == 1)
return 2;
return 1;
}
// The custom rule:
public function customValidation($attribute, $params)
{
print_r($params);
echo "function " . $this->someFunction();
DIE();
}
/* The above customValidation prints:
*
* array (
* [parameter]=>
* [anotherParameter]=>someValue
* )
*
* function 1
*/
<?php
/**
* FeedbackForm class.
* FeedbackForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class FeedbackForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
public $someAttribute;
public $someOtherAttribute;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
array('name, email, subject, body', 'required'),
array('email', 'email'),
array('someAttribute', 'customValidation', 'parameter'=>$this->someFunction(), 'anotherParameter'=>'someValue'),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
public function someFunction()
{
if ($this->someOtherAttribute == 1)
return 2;
return 1;
}
// The custom rule:
public function customValidation($attribute, $params)
{
echo "<pre>";
print_r($params);
echo "function:" . $this->someFunction();
echo "</pre>";
DIE();
}
}
Could you try to access a public variable in someFunction()? Maybe that is where my problem is. I am trying to get a value which has been set through a POST request.
So simply try to return $this->name or $this->email in someFunction():
public function someFunction()
{
if ($this->someOtherAttribute == 1)
return $this->name;
return $this->email;
}}
ur welcome, i’m learning from it too. sometimes the issue is not ‘important’ per say, since we could always find out a workaround. however, getting a clear picture worth more than that.