简体   繁体   中英

Set default value of an element in Zend_Form by reference from the controller

Via the command line I set up a new form called BookSlot:

zf create form BookSlot

Which most of you may know, creates a form directory in the application directory of the Zend framework.

In the init method of the form, I added a text element called time and given it the label 'time':

$time = new Zend_Form_Element_Text('time');
$this->addElement($time);
$time->setLabel('Time');

I need it to have a default value that cannot be changed by the user so I add:

$time->setValue($value);

In my controller I create a function to get the book slot form above:

public function getBookSlotForm(){
        return new Application_Form_BookSlot();
    }

I also have a book slot action in my index controller.

I assign the form to a variable and make it passable to the view in the book slot action:

$form = $this->getBookSlotForm();
    $this->view->form = $form;

In the same book slot action, I have an id variable which is dynamically generated but for this assume its 5:

$id = 5;

How do I get the value of $id to be the default value of $time in my book slot form above? Also, I want to make it so that the user cannot change this value.

For the user can not change the value use the readOnly attribute. In your form class

$time->setAttrib('readonly', 'readonly');

To assign your id as the default value of your time field, in your action

$form->time->setValue($id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM