How to pre fill a select box in render

Notice: This thread is very old.
pistols
Member | 26
+
0
-

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
+
+2
-

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

pistols
Member | 26
+
0
-

Hello Matej,

Yes, That did the job, thanks. Just a best practice question should I pre fill my forms always in the action cycle? What I don't get, but i can blame me for that, is why the other values work?

Greets

David Matějka
Moderator | 6445
+
0
-

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)