DatsunBing
DatsunBing

Reputation: 9076

How do I inject a value into Zend Form?

I have a select element in a Zend Form. To populate the multiOptions array of the element, I call a static method on a model which returns an array. I need to pass a parameter to the static method, but first I need to get the parameter into Zend Form. How can I do this?

I tried passing an array to the Zend Form constructor, then using getAttrib() from within the form. This worked OK however the parameter also shows as a HTML parameter on the form, which is not my intention.

Thanks!

Upvotes: 1

Views: 140

Answers (3)

Ali Mousavi
Ali Mousavi

Reputation: 915

Zend_Form constructor looks for a specific pattern in method's names in your form. The pattern is setMethodName. the constructor calls the MethodName() in your class and pass the parameter to it.

So you'll have this in your class :

class My_Form extends Zend_Form
{

    protected $_myParameters;

    public function setParams($myParameters)
    {
        $this->_myParameters = $myParameters;
    }

And you pass the parameters to your form with :

$form = new My_Form( array('params' => $myParameters) );

So instead of params you can use any other names ( of course if it doesn't already exists in Zend_Form ).

Upvotes: 0

b.b3rn4rd
b.b3rn4rd

Reputation: 8830

To prevent constructor options from appearing as form attributes, you have to specify setter for each passed option.

Example:

class Forms_Hello extends Zend_Form
{
    protected $_names = array();

    public function init()
    {
        $names = $this->getNames();
    }

    public function setNames($names)
    {
        $this->_names = $names
    }

    public function getNames()
    {
        return $this->_names;
    }
}

$form = new Forms_Hello(array(
    'names' => array(
        1 => 'hello',
        2 => 'world'
));    

Upvotes: 1

DatsunBing
DatsunBing

Reputation: 9076

OK, so I have settled for setting this from outside the form object, after the object is instantiated. Not exactly what I was looking for but workable, nonetheless...

Upvotes: 0

Related Questions