Add custom form field that is not in entity - Sonata admin - php

I'm using Sonata Admin in my project. I need to render a field that doesn't belong to entity.
Consider entity User with fields username & password. But I also need a extra field as hobby in form but it is not needed in User entity.
$formMapper
->add('username')
->add('password')
->add('hobby');
But I'm getting the symfony error as,
Neither the property "hobby" nor one of the methods "getHobby()", "hobby()", "isHobby()", "hasHobby()", "__get()" exist and have public access in class "App\Entity\User".
How can I solve this? Thanks in advance!!

This answer for Symfony2 should still hold true if I am not mistaken: How to add additional non-entity fields to entity form in Symfony2
In symfony 2.1+, use mapped:
$form = $this->createFormBuilder($promo)
->add('code', 'text')
->add('image', 'file', array(
"mapped" => false,
))
->getForm();
https://symfony.com/doc/current/reference/forms/types/entity.html#mapped
type: boolean default: true
If you wish the field to be ignored when reading or writing to the
object, you can set the mapped option to false.
So for your case it should be something like:
$formMapper
->add('username')
->add('password')
->add('hobby', null, [
'mapped' => false
]);

Related

Use function to add choices to select form Symfony 2

I'm currently developping a Symfony application (v2.8) with two main bundles : EasyAdmin and FOSUserBundle.
I have users with a particular role and I'm using a 'findBy' with an array to retrieve those users.
I would like to override the form of my admin controller to fill a select form choices with those users. I know it's possible to do it with an array but I want something dynamic if I add or delete some users.
I don't know how can I call a function from one of my controllers (or do I have to declare it as a service ?) to add choices to select form from a query.
Here is an example of what I would like :
$formBuilder->add('field_to_override', 'choice', array(
'choices' => **my_function**,
'multiple' => true,
'expanded' => true,
));
I hope I'm clear in my explanation.
Thank you in advance !
Consider using an EntityType field, which is a specialized form of Choice field which uses Doctrine entities for the choices.
It is possible to specify a custom query for the choices too, e.g.
$builder->add('users', EntityType::class, array(
'class' => 'AppBundle:User',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.username', 'ASC');
},
));

Validation using entity for a FormType inside a form

I have two entities: Company and Location. One company has one location (while one location may "have" multiple companies). Now when a user creates a company, I want him/her to able able, to create the location in the same form. So I use the following
$builder
->add('name', TextType::class, ['label' => 'company.name'])
->add('size', IntegerType::class, ['label' => 'company.size'])
->add( $builder->create('location', FormType::class, [
'label' => 'company.location',
'by_reference' => true,
'data_class' => 'AppBundle\Entity\Location',
])
->add('street', TextType::class, [
'label' => 'location.street',
])
->add('number', TextType::class, [
'label' => 'location.number',
])
This works fine in creating the form. Now it comes to validation. I added #Assert annotations for both entities in their respective files. While company validation works, location does not get automatically validated.
I managed to get validation by adding constraint properties to the new $builder->create('location') elements, but this means duplicated code (once in Entity and at least once in every form that needs location).
How can I solve it so the form gets validated by using the entity's annotation?
By default validation won't traverse to properties that are objects or collections. Use the valid constraint:
http://symfony.com/doc/current/reference/constraints/Valid.html
You cans set the traverse option for collections as well.

Validate choice list in Symfony2

I have a choice list where user can choose one value, but there I even set an empty value if the user doesn't select anything.
The form does not have model, to use #Assert annotation with it, and the choice field is optional, so in some case it will be hidden and need to be validated only if showed to user.
How I can validate this field? When I set it to required in my form type it didn't help (If I am right required equal to true by defaut). Where is my problem?
You need to add the NotBlank validator to your field.
You can add a validator directly to your field, like this:
$this->createFormBuilder()
->add('exampleField', 'choice', array(
'label' => 'Label',
'constraints' => array(
new NotBlank(),
),
))
[...]

setVariables() many to many relation symfony2

I have a many to many relation between let's say entityA and entityB and I will use embeeded forms in order to add the attribute of entityA in the form of entityB as follows
$builder ->add('entityAs', 'entity', array(
'class' => 'xxxBundle:EntityA',
'property' => 'name',
'multiple' => false,
));}
When I set 'multiple' to true, everything is OK.
But when I set it to false, I get the following error
Property "entityAs" is not public in class "xxx\Entity\EntityB". Maybe you should create the method "setEntityAs()"?
As usual the property entityAs in your EntityB class is not public (protected or private). So you have to write (or generate) a setter for it: setEntityAs($entityAs)
multiple true may work, as I think (not sure) it uses the addXxx Setter. Proof me, if you have an addEntityAs Method in your EntityB Class?
Buuuuut, if you have a many to many relation, why you would set multiple to false?

how to have symfony2 formbuilder check in DB as part of validation

What is the best way of checking whether a value exists already before allowing a form to insert it? I want the form validation to be false if there is already a user with the specified username.
I guess a unique constraint somewhere would do here, but to be more all-round, or to be able to check for values in a more customized way. Let's say there are several admin accounts in a customer account, they all have privileges to demote other admins, and one check I would like to be able to make is whether you are disabling the last admin or not (and if so prevent the demote action, with a nice error message right on the form...)
Could I for instance access the entity manager from within my formType, or would that have to be passed from the controller that workaround-ish way?
$builder
->add('username', 'text', array('label' => 'Användarnamn '))
->add('email', 'email', array('label' => 'Epost '))
->add('plainPassword', 'repeated', array('type' => 'password', 'first_name' => 'Lösenord ', 'second_name' => 'Upprepa lösenord',));
You should create a custom validation constraint and inject it with EntityManager to access the database.

Categories