user393964
user393964

Reputation:

passing value to Zend_Form through controller?

I have this contact form with a selectbox, where the values on the select box, depend on the user_id. So these values are selected from the DB and I need the user_id in my form.

What I tried is giving my form a public user_id; datamember, so that when I create a form I can do this:

 $form = new My_Form();
 $form->user_id = $theUserId;

Maybe I'm missing something, but I just can't get this to work. $theUserId does have a value in my Controller, but not in my form (Whenever I do $this->user_id in my form I get: Invalid parameter number: no parameters were bound)

Any ideas how I should do this?

Upvotes: 1

Views: 3195

Answers (3)

jah
jah

Reputation: 2131

You need to move the sql query out of the forms init() method which gets called by the constructor (and before you get chance to set the user id). if the results of the sql query are only needed at render time (rather than at validation time) then you might override the forms render() method, do your sql query there and then call parent::render()


/* My Form */

public function render($view = null)
{
    /* SQL here */

    return parent::render($view);
}

EDIT:

Ok, here's what I would do:


class My_Form extends Zend_Form
{
    private $_userId = null;

    /* Getter and Setter for user id here */

    public function init()
    {
        ...
        $this->createElement('Select', 'nameOfTheSelectElem',
            array(
                /* Don't add the multiOptions here */
            )
        );
    }

    private function _addMultiOptionsForMySelectElem()
    {
        /* SQL Query here */
        $this->nameOfTheSelectElem->setMultiOptions($resultsOfTheSQLQuery);
    }

    public function render($view = null)
    {
        $this->_addMultiOptionsForMySelectElem();

        return parent::render($view);
    }

    public function isValid($data)
    {
        $this->_addMultiOptionsForMySelectElem();

        return parent::isValid($data);
    }
}

So in the init method you can create the element, but don't add the options to the element at this point. Create a private method to do the sql query and add the options to the select element and then call the private method from the render method and the isValid method. Hope that's clearer now. Is it?

Upvotes: 0

homelessDevOps
homelessDevOps

Reputation: 20726

I think Zend_Form is the problem. It has magic methods for set and get (__set). Try to write an simple setter/getter inside your Form Class.

<?php

protected $userId = null;

public function setUserId($id) {
   $this->_userId = $id;
}

public function getUserid() {
   return $this->userId;
}

and in your Controller:

<?php

$form = new My_Form();
$form->setUserid($id);

Upvotes: 1

karim79
karim79

Reputation: 342635

Are you assigning the form to the view? If so, then it should be $this->form->user_id.

Upvotes: 0

Related Questions