I am trying to populate the values into check box. I want check box to be checked when there is value stored in database.
This is my code in form:
$form ['test_1'] = new Zend_Form_Element_Checkbox('test_1');
$form['test_1']->setLabel('test1')->setCheckedValue('1');
$form ['test_2'] = new Zend_Form_Element_Checkbox('test_2');
$form['test_2']->setLabel('test2')->setCheckedValue('2');
If there is value 1 in database i want first check box to be checked and if its 2 then 2nd checkbox needs to be checked.
What do i need to do in the controller.
Could anyone please help me on this issue.
The easiest way would be to fetch the values from the database as an array that maps to the form input elements, e.g. return a row like
array('test_1' => 'value of checkbox', 'test_2' => 'value of checkbox');
You could then simply call $form->populate($values) and let do Zend_Form do the setting, e.g. in your controller do
public function showFormAction()
{
$form = $this->getHelper('forms')->get('MyForm');
$data = $this->getHelper('dbGateway')->get('SomeTable');
$form->populate($data->getFormData());
$this->view->form = $form;
}
Note: the helpers above do not exist. They are just to illustrate how you could approach this. Keep in mind that you want thin controllers and fat models, so you should not create the form inside the controller, nor put any queries in there.
Related
I have a dropdown menu in my form and the form structure depends on its value. I have managed to solve the "form-update-issue" with event subscriber/listener class, where i am trying to update the main form according to dropdown's value.
The main problem is that i have to modify the form from values that persisted in the database.
My DB schema:
I have 4 table: Model, ModelCategory, ModelCategoryKey, ModelParameter.
ModelCategory 1--n Model 1--m ModelParameter
ModelCategory 1--n ModelCategoryKey
ModelCategoryKey 1--n ModelParameter
After the user choose a ModelCategory from the form's (form based on Model entity) dropdown i have to update the form with ModelParamater rows, but it's number and default values depends on ModelCategory 1--n ModelCategoryKey assocaiton.
I've tried to attach NEW ModelParameter entities to the main Model entity during the PRE_BIND event (also set their default values) and it seems working fine, but when i add the 'parameters' with a 'collection' typed element to the form i get the next error:
Entities passed to the choice field must be managed. Maybe persist them in the entity manager?
Clearly my entities can't be (and shouldn't be) persisted at this time.
All ideas are welcome!
UPDATE:
Modifying the form after preSubmit/preBind:
$form->add('parameters','collection',array(
'type' => new ModelParameterType(),
));
OR
$form->add(
$this->factory->createNamed('parameters','collection',null,
array(
'type' => new ModelParameterType()
))
);
where the 'factory' attribute is a FormFactoryInterface. The error message is the same.
UPDATE2:
Further investigation proved, that if i don't add "default" entities to the assocation. Then it works without error.
Here is the source of my form modifying method:
public function preSubmit(FormEvent $event) {
$form = $event->getForm();
$id = $event->getData()['modelCategory'];
$entity = $form->getData();
$categoryKeys = $this->em->getRepository('MyBundle:ModelCategoryKey')->findByModelCategory(
$this->em->getReference('MyBundle:modelCategory',$id)
);
foreach ($categoryKeys as $key) {
$param = new ModelParameter();
$param->setModel($entity);
$param->setKey($key);
$entity->addParameter($param);
}
$form->add(
$this->factory->createNamed('parameters','collection',null,
array(
'type' => new ModelParameterType(),
'allow_add' => true,
'cascade_validation' => true
))
);
}
SEEMS TO BE SOLVED BY
I have just commented out the $param->setModel($entity); line and it seems to be working fine. I will work this out more and will share the experience, if it realy works.
choice field accepts only managed entities, as the value is set to the entity after submit, and form posts only entities ID, so it must be saved beforehand.
You don't need choice field - you need collection of parameter subforms.
$formBuilder
->add('category', 'category_select')
->add('parameters', 'collection', array('type' => 'parameter'))
;
I'm assuming here that category_select is choice field with categories and parameter is subform with it's own values, depending on your parameter structure.
When you have category in your controller, you can bind the newly created entity with added Parameter entities with their key set, depending on ModelCategoryKey.
I've managed to solve my problem, so here it is what i've found out:
It is enough to add the newly created object by the adder function of the inverse side. I don't have to call the owning side's setter.
Inverse side adder function must be modified, that it calls the owning side's setter.
Inverse side adder function must check if the object is not in the collection already.
PRE_SET_DATA event happens, when the form is created. (so in new entities it is empty, and in old ones it is filled)
Within Laravel 4 I can create a select box in a form with this helper:
Form::select('name', $data)
where $data represents an array of the select options.
However I want to now add an extra attribute of 'Required' to help with form validation on the client side.
I can do this if I use normal php and markup but I'd like to use the laravel helper if I can.
I've tried adding:
Form::select('name', $data, array('required'=>'required'))
This doesn't appear to add anything to the final mark up. I've tried the following but this doesn't work either:
Form::select('name', $data, array('required'))
Is there an easy way of doing this or accept that I should revert to another method without a helper
If you check the FormBuilder class the select field is declared as
public function select($name, $list = array(), $selected = null, $options = array())
So what you are passing is the third parameter which should be the default selected option from the list.
In order to achieve what you need you have to pass the array of $options as the fourth parameter (if you don't have default selection just leave the third parameter null)
Form::select('name', $data, null, array('required'=>'required'))
I have the following issue. I create a Zend_Select element and add multioptions in an array.
Zend automatically translates the options, after which my multioptions are sorted incorrectly.
Right now, my only option seems to be:
$element = $this->createElement("select", "name");
$element->setMultiOptions($myArray);
$options = $element->getMultiOptions(); // OPTIONS HAVE BEEN TRANSLATED HERE
asort($options);
$element->setMultiOptions($options);
Anyone know a better way to do this?
I usually always translate the options before sending them to the element :
$myArray = ...; // key/value array with values translated
asort($myArray);
$element->setMultiOptions($myArray);
But your solution looks just as good from my point of view.
I implemented a page to create an instance of an entity and a user related to this. My problem is to bind the request after the submit.
Now i have this :
$formA = $this->createForm(new \MyApp\ABundle\Form\AddObjectForm());
$formB = $this->createForm(new \MyApp\UserBundle\Form\AddUserForm());
if ($request->getMethod() == 'POST')
{
$formA->bindRequest($request);
$formB->bindRequest($request);
if ($formA->isValid() && $formB->isValid())
{
}
// ...
}
With formA and formB extends AbstractType. But, naturally, $formA->isValid() returns false. How can I do to "cut" the request for example ?
If your forms are related and need to be processed and validated at once, consider using embedded forms. Otherwise, use a separate action for each form.
If you need to provide a select field to choose a user from existing ones, consider using an entity type field.
I know that has been a long time since the answer, but maybe if someone is looking for it this could be helpfull.
I've got two forms: user_form and company_form, and the submit has take place in the same function of the controller. I can know wich form has been submit with the follow code:
if ($request->getMethod() == 'POST') {
$data = $request->request->all();
if (isset($data['user_form'])) //This if means that the user_form has been submit.
{
The company_form will pass through the else.
I have a form, created with Zend_Form, with method = GET used for searching records with elements as below:
[form]
user name [input type="text" name="uname"]
[input type="submit" value="Search" name="search"]
[/form]
After form is submitted all the GET parameters along with submit button value are appearing in the url.
http://mysite.com/users/search?uname=abc&search=Search
How to avoid submit button value appearing in the url? is custom routing the solution ?
When you create your element, you can simply remove the name attribute that was automatically set at creation
$submit = new Zend_Form_Element_Submit('search')->setAttrib('name', '');
Or inside a Zend_Form
// Input element
$submit = $this->createElement('submit', 'search')->setAttrib('name', '');
// Or Button element
$submit = $this->createElement('button', 'search')->setAttribs(array
(
'name' => '', 'type' => 'submit',
);
When a form gets submitted, all of its elements with their names and values become a part of a GET / POST - query.
So, if you don't want an element to appear in your GET - query, all you need to do is to create this element without a name. That's probably not the best approach, but since we're talking about the 'submit' element, I guess it doesn't matter that much.
Looking at Zend_View_Helper_FormSubmit helper, you can see that it's creating the 'submit' element and setting its name. So, the possible solution would be to create your own view helper and use it for rendering the 'submit' element instead of the default helper.
You can set a custom helper with
$element->setAttribs( array('helper' => 'My_Helper_FormSubmit') );
Then build your own form element class and remove the name attribute from the element with preg_replace. The beauty of it is, it will not interfere with the other decorators.
So the something like this:
class My_Button extends Zend_Form_Element_Submit
{
public function render()
{
return preg_replace('/(<input.*?)( name="[^"]*")([^>]*>)/', "$1$3", parent::render(), 1);
}
}
You can remove name attribute for submit button in javascript.
jQuery example:
$('input[name="submit"]').removeAttr('name');
In the controller that represents the form's action, redirect to another (or the same controller) only including the relevant params.
Pseudocode:
$params = $this->getRequest()->getParams();
if isset($params['search'])
unset($params['search']);
return $this->_helper->Redirector->setGotoSimple('thisAction', null, null, $params);
handle form here
This is basically the same idea as Post/Redirect/Get except that you want to modify the request (by unsetting a parameter) in between the different stages, instead of doing something persistent (the images on that Wiki-page shows inserting data into a database).
If I were you, I would leave it in. IMO it's not worth an extra request to the webserver.