Entity field type checkbox required - symfony

i don´t know why my entity field type (with checkboxes) not validate as required. May be I am doing something wrong?
$builder ...
...
->add('idiomas', 'entity',
array('class' => 'BackendIdiomasBundle:Idioma',
'expanded' => true,
'multiple' => true,'required' => true))
This is an entity field type with checkboxes ('expanded' => true,'multiple' => true), but i need at least one of entity values must be checked before the form is sent. For this I set to 'required'=> true, but It doesn´t work!!!
Any idea or clue?
Thanks

Try using validation http://symfony.com/doc/current/book/validation.html
Your\MainBundle\Entity\Whatever:
properties:
idiomas:
- NotBlank: ~
- NotNull: ~

Related

symfony 5 form type define the labels

I created the CRUD for my entity and I need to somehow define the labels for the fields of the entity.
I can define them in the form type, for example:
$builder
->add('name' , null, [
'attr' => ['autofocus' => true],
'label' => 'Product name',
])
but I don't think this is the best solution.
Which is the best approach?
Do I have to use translations, even if the app is single language?
Is there any other solution?
Yes is this the best practies, in official documentation explained here
https://symfony.com/doc/current/reference/forms/types/form.html#label-translation-parameters

Non-mapped field is valid whilst it is required and empty

I have a field which is non-mapped and required.
$builder->add('termsAndConditions', CheckboxType::class, [
'required' => true,
'mapped' => false,
'attr' => [
'class' => 'c-custom-option',
],
]);
Clientside validation will throw an error when empty, but serverside says it's valid. Currently i do an extra check on form submission $form->isSubmitted() && $form->isValid() && $form->get('termsAndConditions')->getData()==true but the form->isValid() method shouldn't return true in my opinion
As you can see in docs:
If true, an HTML5 required attribute will be rendered. The corresponding label will also render with a required class.
This is superficial and independent from validation. At best, if you let Symfony guess your field type, then the value of this option will be guessed from your validation information.
So, as you can see, it's only about client side validation.

symfony2 Entity select tag display

I have this Symfony form with a ManyToMany relation working fine, it displays all the parties with the property name on the entity Party.
When submitted, it queries the database according to the parties that are selected and retrieves the persons that are invited to those parties.
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('parties', 'entity', array(
'class' => 'ProtoBundle:Party',
'multiple' => true,
'expanded' => false,
'property' => 'name',
'required' => false,));
}
with the parameter
'multiple' => 'true,
all the parties are displayed at the same time in a select drop down box (not what i want).
What I want is just to have one select tag with parameter
'empty_value' => 'choose a party'
, then when the user clicks on it, the values are displayed. Actually I can do this with the parameter
'multiple'=> false,
but the problem is that I get this error message:
Neither the property "parties" nor one of the methods "setParties()", "__set()" or "__call()" exist and have public access in class "Acme\ProtoBundle\Entity\Person".
Does anyone knows how to make this select tag working and bring me a detailed solution?
In first of all you should get in consideration that if you really need many to many relation when you want simple select box without multiple select.
But...
in entity you will have to check if comming value is array, and that's it:
public function setParties($parties)
{
if (!is_array($parties)) {
$parties = array($parties);
}
$this->parties = $parties;
}

html5 error message, translation

I don't get one thing with forms and I guess with HTML5. I do build a form-text like this:
->add(
'subject', 'text', array(
'constraints' => array(new MaxLength(array('limit' => 5, 'message' => 'subject.maxlength'))),
'required' => true,
'attr'=>array('oninvalid'=> "setCustomValidity('". $this->get('translator')->trans('subject.oninvalid',array(), 'validators') ."')")
))
1.) Problem - form:
If I don't give any input into subject, the HTML-subject.oninvalid is coming up. When I reach the limit 5 because of MaxLength I send this form and I render an extra field error_messages, what doesn't look like subject.oninvalid. Why does symfony do pop up two different ways of errors? Why doesn't subject.maxlength is not popping up like subject.oninvalid?
2.) Problem - translation:
I do have a validators.en.xliff file with plural entries, what is working. Symfony is expecting by subject.maxlength plural translation. Why? How can I pass the %count% like http://symfony.com/doc/2.0/book/translation.html#explicit-interval-pluralization in 'message' => 'subject.maxlength'?

Symfony 2, how to persist join table entities?

This is such a trivial problem that I can't believe I couldn't find an answer.
Symfony 2, doctrine 2.1. I've got two entities and one intermediate entity (join table). User, Pref, and UsersPrefs. Pref table is dictionary table, so that I could change pref name in one place only. Ok, let's see the picture:
infographic http://dl.dropbox.com/u/22495762/infographic.png
As You can see, I want to have a checkbox group, with all the possible choices (prefs) and preferred choices checked. So, if there are 3 prefs, and only 2 selected by the user, there should be 3 checkboxes, 2 selected.
It's simple, if done plain PHP - query database twice to get list of all prefs and user prefs, render checkboxes depending on values, add some actions to handle form submit, done.
But for the life of God I can't get this to work using symfony & doctrine. I was able to get to the point where I can update relationships in doctrine and further in database, but I'm using raw query values for that:
$data = $request->request->get('some_form');
and this supposedly isn't the way it should be done?
Morevoer, I'm completely stuck as to how should I display checkbox list. I either get list of all options, none checked, or only user options, all checked. Or 'left joined' result set with checkboxes for all cases, useless anyway.
I've come to the point where I tried to overload twig checkbox template, but I couldn't pass variables to the form template, and that was the last straw...
EDIT:
This way I'm getting group of checkboxes, not connected to user choices:
->add('prefs', 'entity', array(
'class' => 'Some\TestBundle\Entity\Pref',
'expanded' => 'true',
'multiple' => 'true',
'property' => 'name'
))
And this way I'm getting only user choices, all checked:
->add('prefs', 'entity', array(
'class' => 'Some\TestBundle\Entity\UserPrefs',
'multiple' => 'false',
'expanded' => 'false',
'property' => 'pref.name',
'query_builder' => function(EntityRepository $er) use ($id) {
return $er->createQueryBuilder('u')
->where("u.user = :id")
->setParameter('id', $id)
;
},
))
And I tried left joins and other options, but at best I could get list of all possible options for all possible users, checked accordingly.
EDIT (POSSIBLE SOLUTION):
I'm displaying checkbox group:
->add('pref_ids', 'choice', array(
'choices' => array(
'1' => 'pref one',
'2' => 'pref two',
'3' => 'pref three',
),
'expanded' => 'true',
'multiple' => 'true'
))
I've added $pref_ids array in User entity. Now I just need to set values in array according to preferences chosen by user:
public function setPrefIds()
{
$prefs = $this->getPrefs();
$this->pref_ids = array();
foreach($prefs as $pref){
array_push($this->pref_ids, $pref->getPref()->getId());
}
return $this;
}
This way I get appropriate checkboxes checked.
Writing values to database is reversal of the process. I'm getting input values from request:
$data = $request->request->get('edit_form');
var_dump($data['pref_ids']);
Removing all user prefs:
foreach ($userPrefs as $pref){
$em->remove($pref);
}
And setting actual associations in doctrine from ids:
$entity->setPrefsById($em, $data['pref_ids']);
Here I'm passing entity manager to entity itself, but I need to refactor it, because it looks kinda messy this way.
Then $em->flush(); and that's it.
That's the best I could come up with. Probably it's overcomplicated and should be done entirely different way. Unfortunately couldn't figure out this "other way".
You need the choice field type: http://symfony.com/doc/current/reference/forms/types/choice.html
In your builder, it will be something like
$builder->add('prefs', 'choice', array('multiple' => true, 'expanded' => true, 'choices' => fetch the available prefs from the database here);
Edit: Sorry I'm mistaken, you need the "Entity" type, which fetches automatically the choices from the database: http://symfony.com/doc/current/reference/forms/types/entity.html
You must still put multiple => true expanded => true to get checkboxes.

Resources