I've got a problem with displaying collection in my form.
When displaying my entity collection I've got something like this :
0
Name: myInputName
Address: myInputAddress
1
Name: myInputName
Address: myInputAddress
My question is why Symfony2 display the index...
And this for all saved entities into my collection...
Here the code I use:
$builder
->add('person', 'collection', array(
'label' => ' ',
'type' => new PersonType(),
'prototype' => true,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
))
;
In my twig file:
<div>
{{ form_widget(edit_form) }}
</div>
Help please
Sam
Removing indexes (labels) for collection items:
$builder
->add('person', 'collection', array(
...
'options' => array('label' => false)
))
;
Use key entry_options instead of options for Symfony 3 and 4
If you want to add custom labels per row you can produce the form yourself:
{{ form_start(edit_form) }}
{% for person in form.persons %}
{{ form_row(person, {'label': 'custom label per item' }) }}
{% endfor %}
{{ form_end(edit_form) }}
Note: tested on Symfony 2.3 & 2.4
This one is some days ago but because I was facing same question for Symfony 3 the answer of sectus is the correct one.
Use the
'entry_options' => ['label'=>false],
option within your builder to hide he object item.
Best Regards
You can custom the rendering of your collection for don't display the index with, by example:
{% block _FORMNAME_person_widget %}
{% spaceless %}
{% for child in form %}
{{ form_widget(child.Name) }}
{{ form_widget(child.Address) }}
{% endfor %}
{% endspaceless %}
{% endblock %}
I know this has been closed for a while. And not sure if this has been solved elsewhere. This issue is actually pretty simple to fix and I am surprised there is no documentation about this anywhere. In the PersonType or any type that is used in a collections just modify the vars['name'] in the buildView to be what you want displayed as the label.
public function buildView(FormView $view, FormInterface $form, array $options)
{
// Adjust the view based on data passed
$this->vars['name'] = $form->getData();
// Or...
$this->vars['name'] = 'Some random string';
}
If you want it dynamic, you would use the object by form->getData(). Since, in my problem, I am using a form theme, overriding the twig is not really an option for me.
Hope this helps someone.
Using #MrBandersnatch's solution below, I had to use $view->vars['name'] instead of $this->vars['name'] (Symfony 2.3).
(apologies for not adding this as a comment on #MrBandersnatch's answer, I've not got enough reputation yet).
Related
I would like to duplicate the same field several times with different values in the drop-down list in twig. I add a simple form with a TextType, but in twig in a for loop, the rendering of the field is done only once. How can I make this system under symfony ? ( In a for loop )
When you try to create a form in your controller and then you render it to you'r view , it gonna be one and only one form , you can't duplicated with a loop because at the end, it gonna give you 2 forms with the same form_id , so if you need 2 forms you need to instantiate them with your builder the same thing with you'r fileds.
Take a look:
$task1 = new Task();
$task2 = new Task();
$form1 = $this->createFormBuilder($task1)
->add('task', TextType::class)->add('task2', TextType::class);
$form2 = $this->createFormBuilder($task2)
->add('task', TextType::class);
And about the drop down , you need to create a form with ChoiceType Field :
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
$builder->add('Tasks', ChoiceType::class, array(
'choices' => array('task1','task2','task3));
CollectionType field type is used to render a "collection" of some field or form. In the easiest sense, it could be an array of TextType fields that populate an array values.
Example:
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
// ...
$builder->add('emails', CollectionType::class, [
// each entry in the array will be an "email" field
'entry_type' => EmailType::class,
// these options are passed to each "email" type
'entry_options' => [
'attr' => ['class' => 'email-box'],
],
]);
The simplest way to render this is all at once:
{{ form_row(form.emails) }}
A much more flexible method would look like this:
{{ form_label(form.emails) }}
{{ form_errors(form.emails) }}
<ul>
{% for emailField in form.emails %}
<li>
{{ form_errors(emailField) }}
{{ form_widget(emailField) }}
</li>
{% endfor %}
</ul>
Please refer this documents for further details : https://symfony.com/doc/current/reference/forms/types/collection.html
I would like to render the same form multiple times to handle the same action for two different tabs.
The problem is that when I try, only the form of the first tab is shown, event if I change the id and name of the form.
I found out it's the expected behavior of symfony, but I still need it to work.
I found that it may works with a collection but don't get how it would work.
twig:
{{ form(contactForm, {'attr': {'id': 'contactFormId' ~ Client.Id}, 'name': "contactFormName" ~ Client.Id})}}
Form:
$this->contactForm = $this->createFormBuilder($contact, array('allow_extra_fields' =>true))
->add('Nom', TextType::class, array('mapped'=>false))
->add('Prenom', TextType::class, array('mapped'=>false))
->add('Telephone', TextType::class, array(
'label' => 'Téléphone'))
->add('Email', TextType::class)
->add('Ajouter', SubmitType::class)
->getForm();
It is an older question, but I just came across it facing a similar situation. I wanted to have multiple versions of one form object in a list view. For me the solution was to move the createView() call on the form object to the view instead of calling it in the controller. This is kind of a dirty solution regarding separation of concerns, but I thought to post it so it may help others anyway.
My controller action looks like this:
/**
* #Route("", name="cart_show")
* #Method("GET")
*/
public function showAction(Request $request)
{
/** #var CartInterface $cart */
$cart = $this->get('rodacker.cart');
$deleteForm = $this->createDeleteForm();
return $this->render(
'AppBundle:Cart:show.html.twig',
['cart' => $cart, 'deleteForm' => $deleteForm]
);
// ...
private function createDeleteForm()
{
return $this->createForm(
OrderItemDeleteType::class,
null,
[
'action' => $this->generateUrl('cart_remove_item'),
'method' => 'DELETE',
]
);
}
}
and in the view I set the form variable by calling the createView function on the form variable (deleteForm) passed from the controller:
{% for item in items %}
{% set form = deleteForm.createView %}
{{ form_start(form) }}
{{ form_widget(form.item, {'value': item.image.filename}) }}
<button type="submit" class="btn btn-xs btn-danger" title="Artikel entfernen">
<i class="fa fa-trash-o"></i> entfernen
</button>
{{ form_end(form) }}
{% endfor %}
Once you render a Symfony form, the same form will not render again.
I would suggest creating a form class and calling Controller::createForm() multiple times to create the desired amount of Form instances; you can call isSubmitted etc. on all forms independently.
http://symfony.com/doc/current/book/forms.html#creating-form-classes
So I have a form that is based on an entity that contains a one to many relationship.
The problem is that this field is rendered as a select (or choice). I really don't want to load all the possible ids (there are many) but just want to load the one that is set in the entity (which is the id that appears selected in the select).
Is there any way of doing this and still keep the relationship? If I really have to change the field how can I access, in the form class, the selected entity given to the entity so that I can retrieve the id?
UPDATE
To make this a bit clearer here is my form code:
$this->createFormBuilder()
->add('items', 'collection', array(
'type' => new \MyBundle\Form\ItemsType(),
'allow_add' => true,
'data' => $itemsEntities
)
)
->add('submit', 'submit')
In the $itemsEntities I have 5 entities all of which generate the select with loads of ids. Hakins answer would work I think if this would be just one field but since there are many I don't really know how to handle this.
I have tried to put an eventListner on the \MyBundle\Form\ItemsType for but I can never access any data.
Maybe you could use the 'query_builder' option of the field (see: http://symfony.com/doc/current/reference/forms/types/entity.html) and create a query that fetches the only result you want, based on it's id. You could pass the id to the constructor of form if necessary.
You can pass the id of the related entity to the form builder parameters, and change your field type to hidden instead of choice (or entity):
In your controller:
$id = $entity->getRelatedEntity()->getId();
$options['id'] = $id;
$form = $this->createForm(new EntityType($options), $entity);
In your EntityType:
public function buildForm(FormBuilderInterface $builder, array $options) {
$options = $this->options;
$builder
->add('relatedEntity', 'hidden', array(
'data' => $options['id'],
'required' => TRUE
));
Update
To avoid rendering a collection without changing the relationship, you can change only your Twig form by rendering the selected item(s) id(s) as hidden field(s), then set rendered the form.items. (If you don't set them rendered, they will be present in the form_rest(form))
With your existing code for the formBuilder, change your twig like this:
{% block body %}
...
{% for item in form.items %}
{% if item.vars.data %}
<input type="hidden" name="{{ item.vars.full_name}}" id="{{ item.vars.id }}" value="{{ item.vars.value }}"
{% endif %}
{% endfor %}
{% do form.items.setRendered %}
...
{% endblock %}
everyone
I’am having trouble with empty dates and forms in Symfony2.
When I create an entity with an empty date, it works fine, a NULL value is inserted in the database. But when I want to edit it, it renders as today, I found no way of rendering the empy_values
As expected, “preferred_choices” does not work because “date” is not a “choice”.
Seems that a new \DateTime() is called somewhere.
Index and show actions have no problem:
[index/show.html.twig]
{% if entity.dueDate %}
{{ entity.dueDate|date('Y-m-d') }}
{% endif %}
If I ask in the controller, the behaviour is the expected one
[controller]
if (!$entity->getDueDate()) {
// enters here when there is NULL in the database
}
Here is the entity and form definitions:
[entity]
/**
* #var date $dueDate
*
* #ORM\Column(name="dueDate", type="date", nullable="true")
*/
private $dueDate;
[form]
$builder->add('dueDate', 'date', array('label'=>'Due date', 'empty_value' => array('year' => '----', 'month' => '----', 'day' => '----'),'required'=>false))
Please give me a hint, thank you in advance.
There is a related question from 2011-06-26 with no answer in google groups
https://groups.google.com/forum/#!msg/symfony2/nLUmjKzMRVk/9NlOB1Xl5RwJ
http://groups.google.com/group/symfony2/browse_thread/thread/9cb5268caccc4559/1ce5e555074ed9f4?lnk=gst&q=empty+date+#1ce5e555074ed9f4
With modern version of Symfony you seem to need:
$builder->add('dueDate', DateType::class, array(
'placeholder' => ['year' => '--', 'month' => '--', 'day' => '--']
)
empty_value has been replaced by placeholder and you need to pass an array with each "empty" value.
You can solve this way:
$builder->add('dueDate', 'date', array(
'label'=>'Due date',
'empty_value' => array('----'),
'required'=>false
))
You were close to the solution.
I did not want to render the form by myself, but as I was already doing that due to an unrelated issue, I developed some kind of fix:
[edit.html.twig]
<div class="entry {% if not entity.dueDate %}nullabledate{% endif %}">
{{ form_label(form.dueDate) }}
{{ form_errors(form.dueDate) }}
{{ form_widget(form.dueDate) }}
</div>
[add to some javascript file]
jQuery(document).ready(function() {
var nullDate = function(id) {
$(".nullabledate select").each(function(key,elem){
$(elem).val('');
})
}
nullDate();
}
I have an entity User and an entity Address. There is a relation One-to-Many between User and Address :
class User
{
/**
* #orm:OneToMany(targetEntity="Address")
*/
protected $adresses;
[...]
}
I have a class AddressType, and class UserType :
class UserType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('addresses', 'collection', array('type' => new AddressType()));
}
[...]
}
In my controller, I build form with :
$form = $this->get('form.factory')->create(new UserType());
... and create view with :
return array('form' => $form->createView());
I display form field in my twig template with :
{{ form_errors(form.name) }}
{{ form_label(form.name) }}
{{ form_widget(form.name) }}
[...]
Okay. Now, how to display fields for one or more addresses ? (it's no {{ for_widget(form.adresses.zipcode) }} nor {{ for_widget(form.adresses[0].zipcode) }} ...)
Any ideas ?
This is how I did it in my form template:
{{ form_errors(form.addresses) }}
{% for address in form.addresses %}
<div id="{{ 'address%sDivId'|format(loop.index) }}" class="userAddressItem">
<h5> Address #{{ loop.index }}</h5>
{{ form_errors(address) }}
{{ form_widget(address) }}
</div>
{% endfor %}
And I have a small action bar, driven by jQuery, that lets the user add and remove addresses. It is a simple script appending a new div to the container with the right HTML code. For the HTML, I just used the same output has Symfony but with updated index. For example, this would be the output for the street input text of the AddressType form:
<input id="user_addresses_0_street" name="user[addresses][0][street]" ...>
Then, the next index Symfony will accept is 1 so the new input field you add would look like this:
<input id="user_addresses_1_street" name="user[addresses][1][street]" ...>
Note: The three dots are a remplacement for required="required" maxlength="255" but could change depending on your needs.
You will need more HTML code than that to add a whole new AddressType to the DOM of the browser but this give you the general idea.
Regards,
Matt
I should top that up with the fact that if you want to dynamically add fields, you need to set the key 'allow_add' to true in your collection field in UserType :
...
$builder->add('addresses', 'collection', array(
'type' => new AddressType(),
'allow_add' => true
));
Just spent hours trying to figure out what was missing, and at the time i'm writing the doc does not mention this yet. Hope it'll help fellow developers.