Symfony2 embedded forms using one class - php

Is it possible to use an Embedded form without using a separated class for it?
The reason is I've got a lot of form classes already, which most of the time contain a single field, so I wonder if it is possible to define embedded forms inline.
So normally we have something like this:
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name')
->add('email')
->add('phone')
->add('key', new KeyType())
;
}
The documentation says that I have to create a class for the key field, KeyType for example, where I would set up the form builder for the embedded form. But I would like to, instead of creating the class KeyType, define the fields inline, in the same class. How can I do that?

Yes this is possible.
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name')
->add('email')
->add('phone')
->add(
$builder->create('key')
->add('someField', 'text')
->add('otherField', 'checkbox')
)
;
}

Related

symfony 3 formbuilder order properties

Using symfony 3, how can I customize form property order?
In my BookType class, I add my properties in my custom order, but when rendered, form will display in another order. Why?
class BookType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('title')
->add('author')
->add('pages')
->add('published_date')
->add('views');
}
}
And this is the result:
author
title
pages
views
published_date
Thx in advance
You can customize your form result by using form_row(form.author) for each field you have to display. have a look there:
https://symfony.com/doc/current/form/form_customization.html#form-rendering-basics

Symfony3: form: populate select with related model entries

I have two models, topic and user. Both are related by many-to-one relationship (a topic is defined by only one user) such as:
class User
{
private $idUser;
private $username;
}
class Topic
{
private $idTopic;
private $topicName;
private $idUser;
}
MAIN CONCERN: I would like (using symfony-forms) to create a creation form for the topic model. The form would contain:
a topic name input
a user select (list populated by the existing users in the database. The displayed value would be the username of course).
I have created a TopicType class that will build the topic creation form:
class TopicType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->
->add('topicName')
->add(/* 'idUser', 'choice', 'THE USER LIST ???*/)
}
public function configureOptions(FormBuilderInterface $builder, array $options)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Topic'
));
}
}
How can I retrieve the list of users and populate the choices considering I don't have access to the entity manager in TopicType context?
Could I pass a $users array in the controller as a parameter when invoking createForm method ? If so, how ?
If you understood what I'm trying to do, Is there a better/simplier way to get it done ? Am I missing something ?
I know this question might look similar but all the solutions I found on related topics are somehow deprecated in Symfony3
Any help would be much appreciated.
Have a good day to you all.
you should try something like this (you must adapt the code):
->add('User', EntityType::class, array(
'class' => 'xxxBundle\Entity\User',
'choice_label' => 'username',
'required' => true,
'multiple' => false,
))
do not forget :
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
More info here : http://symfony.com/doc/current/reference/forms/types/entity.html

Symfony 2.4 - Adding dinamically fields in the form

I have created a form using Symfony 2.4 that is not linked to any entity because I only want to take the data to create a report. I have created a form using an AbstractType extended class and I need to add several items since the form represents a bill. I know about the allow_add attribute, but it just lets to add a field to the form and I need to do something like I show in the image:
I have no idea at all about how to do it, I have created an item class, and it contains two attributes, but I find nowhere any information about this. Until now this is what I've got:
namespace Abadia\FacturaBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;>
class ReciboCajaType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ciudad', 'text')
->add('fecha', 'date')
->add('valor', 'number')
->add('recibi_de', 'text')
->add('suma_recibida', 'number')
->add('suma_letras', 'textarea')
->add('bloque', 'text')
->add('numero', 'text')
->add('descripcion', 'textarea')
->add('areas_comunes', 'number')
->add('cuota_extraordinaria', 'number')
->add('saldo', 'number')
->add('cheque', 'number')
->add('otros', 'number')
->add('efectivo', 'number')
->add('generar', 'submit')
;
}
public function getName()
{
return 'abadia_facturabundle_recibocajatype';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
}
Thanks in advanced.
UPDATE:
I forgot to mention that I am working with the Twig extension. Just in case knows how to do it using it.
Basically you will need 2 forms. One, call it main form and an another form for an item. Then you can embed the item form type into the main form type multiple times using the collection type. You will need some javascript too for adding and removing an item. It would be very long to write down exactly how to do it, but there is a good example in the docs.

Symfony 2 registration form

I'm trying to create a registration form in Symfony 2.4 following the guide here
http://symfony.com/doc/current/cookbook/doctrine/registration_form.html
Lets say I've got 2 FormTypes
PersonType
RegistrationType
PersonType defines all the fields for a specific user.
// PersonType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName','text',['attr'=>['placeholder'=>'First Name']])
->add('lastName','text',['attr'=>['placeholder'=>'Last Name']])
->add('email','email',['attr'=>['placeholder'=>'email#example.com']])
->add('title','choice', ['choices'=>$this->titles, 'required'=>true])
->add('phone','text',['attr'=>['placeholder'=>'(555) 555-1234']])
->add('accountStatus')
->add('organization')
->add('address', 'text',['attr'=>['placeholder'=>'123 Fake St']])
->add('city')
->add('province','choice', ['choices'=>$this->provinces, 'required'=>true])
->add('postalCode','text',['attr'=>['placeholder'=>"A1A 1A1"]])
;
}
RegistrationType adds:
// RegistrationType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$person = new PersonType();
$builder->add('person', $person);
$builder->add('termsAccepted','checkbox');
$builder->add('submit','submit', ['attr'=>['class'=>'btn-primary'], 'label' => "Submit Account Request"]);
}
The issue is - I don't want to include accountStatus on the registration form, as this will be set by code when I persist it to the database. When I output my form it's including the accountStatus.
In Symfony 1.4 to pull this same thing off I simply extended the PersonForm, and unset any widgets I did not require.
Am I going about this wrong? This is my first Symfony 2 project.
EDIT: I found the solution for my case. I wanted accountStatus in my main form, but want to reuse everything except that for my registration form.
I simply added this to my form after rendering all the fields I wanted
{% do form.person.setRendered %}
accountStatus is appearing in the form because of this line:
->add('accountStatus')
remove this line and you won't see it in the form.

Filtering which items to show up in collection field

I have a form using this class type:
class DespesasContainerType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('despesas', 'collection', array(
'type' => new DespesasFamiliasType(),
'by_reference' => false,
))
;
}
// ...
}
This way it shows all items in the despesas attribute of the object.
Is there a way to filter which items to use? Something similar to the query_builder option on the entity field type.
No way from FormTypeInterface, but you can filter this collection before passing it to the Form.
Another tricky tip :
Define a public getter like getFilteredDespeas on your Entity that returns the filtered list of despeas. In your Form, just call the field filteredDespeas instead of despeas. This involves that you specifically manage the form binding, by adding a public setFilteredDespeas to your entity, or any other way...

Categories