How to pre fill a select box in render
- pistols
- Member | 26
Hello There
I have this create:
<?php
public function createComponentMyForm() {
$form = new Form();
$form->addSelect('clients_id', 'Klient:', array())
->setPrompt("Choose one");
$form->addCheckbox('settled', 'Settled:');
/* more stuff here */
return $form;
?>
I fill the form in my renderClients method like this:
<?php
public function renderAddClientUsage($userId)
{
$clients = $this->clientsManager
->findByUserId($userId)
->fetchPairs('id', 'company');
$this["MyForm"]["clients_id"]->setItems($clients);
$this["MyForm"]["settled"]->setDefaultValue(TRUE);
}
?>
The form is rendered correctly, In the html source code I can see a populated select with options.
But! if I submit this form and dump the
<?php
$form->getValues();
?>
I get null in the return array for the clients_id key. The settled key is pre filled correctly. could you please explain why? I use this technic to pre fill all kinds of input types but only the select fails?
Thanks in advance
Last edited by pistols (2015-01-23 17:45)
- David Matějka
- Moderator | 6445
See presenter
lifecycle
Form is processed in the “interaction” phase. Therefore calling
->setItems()
in render method is too late. You have to call it
earlier, e.g. in actionAddClientUsage
- David Matějka
- Moderator | 6445
The reason you get null
instead of selected item is, that Nette
drops selected value if it is out of range of items
(in some cases
it throws an exception). Nette does that for security reasons.
IMHO best practise would be calling ->setItems()
in the
createComponent* method. You can access userId parameter using
$this->getParameter('userId')
.
Last edited by matej21 (2015-01-23 19:32)