Passing variables to a Custom Zend Form Element
I'm trying to create a custom form element which extends Zend_Form_Element_Text with a validator (so I don't have to keep setting up the validator when I use certain elements). Anyway, I'm having trouble passing $maxChars variable to it when I instantiate it in my Main form. I've provided my shortened code below
This is my custom element below
class My_Form_Custom_Element extends Zend_Form_Element_Text
{
public $maxChars
public function init()
{
$this->addValidator('StringLength', true, array(0, $this->maxChars))
}
public function setProperties($maxChars)
{
$this->maxChars= $maxChars;
}
}
This is where I instantiate my custom form element.
class My_Form_Abc extends Zend_Form
{
public function __construct($options = null)
{
parent::__construct($options);
$this->setName('abc');
$customElement = new My_Form_Custom_Element('myCustomElement');
$customElement->setProperties(100); //**<----This is where i set the $maxChars**
$开发者_开发问答submit = new Zend_Form_Element_Submit('submit');
$submit -> setAttrib('id', 'submitbutton');
$this->addElements(array($customElement ,$submit));
}
}
When I try to pass '100' using $customElement->setProperties(100) in my Form, it doesnt get passed properly to my StringLength validator. I assume it's because the validator is getting called in Init? How can I fix this?
init()
is called when you create an element, so before you call setProperties()
and your $maxChars
is not set then.
I see two solutions:
1 - Remove init()
and move addValidator()
to setProperties()
method:
public function setProperties($name, $value)
{
switch( $name ) {
case 'maxChars':
$this->addValidator('StringLength', true, array(0, $value));
break;
}
return $this;
}
2 - Do what you did in init()
in render()
- element is rendered at the end.
public function render()
{
$this->addValidator('StringLength', true, array(0, $this->maxChars))
return parent::render();
}
I think first is better one.
精彩评论