Passing variables to a Custom Zend Form Element

Posted by user322003 on Stack Overflow See other posts from Stack Overflow or by user322003
Published on 2010-04-22T09:17:22Z Indexed on 2010/04/22 9:33 UTC
Read the original article Hit count: 292

Hi,

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?

© Stack Overflow or respective owner

Related posts about zend-framework

Related posts about zend-form