Symfony 2.6 checked by default checkboxes - symfony

How I can make checkboxes checked by default based on data from database?
Now my form looks like:
...
->add(
"role", "entity", [
"class" => "AppDefaultBundle:OptionRole",
"required" => false,
"label" => "Roles for user: ",
"property" => "name",
"expanded" => true,
"multiple" => true
]
)
...
And I want to select defaults for this checkboxes based on data from other table.

You should probably add the choices property: http://symfony.com/doc/current/reference/forms/types/choice.html#choices
In your case you should have an array with all OptionRoles relevant for the (User ?) entity you are working on (the one you create the form for).
Assuming the doctrine User model knows it's OptionRoles (most likely a ManyToMany association) the form should automatically check the checkboxes of the Users OptionRoles.
Here is one example:
[
'label' => 'Select Modules',
'class' => 'Foo\BarBundle\Entity\Module',
'choices' => $this->availableModules(),
'property' => 'name',
'multiple' => true,
'expanded' => true
]
...
public function availableModules()
{
return $this->get('doctrine')
->getManager()
->getRepository('Foo\BarBundle\Entity\Module')
->findAll();
}

Related

Symfony Form - Collection Type with Checkboxes inside

I am using Symfony 5, I want to have a "User Edit" page in administration, in which I will change User Roles, I want to have checkboxes to define which role assign to user, so for that, I need Collection Type with CheckboxType entry inside (if I am true), but for first I can't use user roles array as value for collection type
$builder
->add('roles', CollectionType::class, [
'entry_type' => CheckboxType::class,
'entry_options' => [
'required' => false,
],
])
This throws error
Unable to transform value for property path "[0]": Expected a Boolean.
after that, I tried to use a model transformer to change the value, below is code how I did that
$builder->get('roles')
->addModelTransformer(new CallbackTransformer(
function($rolesAsArray){
$rolesAsArray = array_flip($rolesAsArray);
foreach($rolesAsArray as &$role){
$role = true; // I also tried to set key instead of value - true
}
return $rolesAsArray;
},
function($rolesAsString){
dump($rolesAsString);die;
}
));
After this, I didn't get an error but I get the form with this look
So I haven't any option to change labels, and even I am submitting a form with these fields it throws an error
Expected argument of type "array", "null" given at property path "roles".
I found a way to do this with Select Box, but I can't found any way to do it with Checkbox.
If you have any ideas tell me, please.
You can use ChoiceType :
$builder->add('roles', ChoiceType::class, array(
'label' => 'form.label.role',
'choices' => User::ROLES,
'choice_translation_domain' => 'user',
'multiple' => true,
'expanded' => true,
'required' => true,
));
In User entity:
const ROLES = array(
'roles.admin' => 'ROLE_ADMIN',
'roles.secretary' => 'ROLE_SECRETARY',
'roles.user' => 'ROLE_USER'
);

Symfony 3.3 EntityType using distinct values in a drop down

I am working on an existing Symfony 3.3 project, and I have been asked to register a dropdown field in a results filter form that should contain all the values from a field in the database.
Until now, what I have do is the following that partially works:
$builder->add(
'newField',
EntityType::class,
[
'class' => Transaction::class,
'required' => false,
'multiple' => false,
'label' => 'New Field',
'choice_label' => 'newField',
'placeholder' => 'Choose a value'
]
)
The above code is able to display the values correctly, but unfortunately, because the table has repeatedly the same values, I get a long list of all the same values.
Instead, what I need to achieve is to display the DISTINCT values from the database.
I have tried the query_builder, but to be honest I am not sure I use it correctly as I am not an experienced Symfony developer.
Any idea on how to display the entries of the given column with DISTINCT results?
As you said yourself, you can use the query builder to achieve this. Something as simple as this should achieve what you're after:
->add('fooBar', EntityType::class, [
'query_builder' => function (EntityRepository $repository) {
return $repository
->createQueryBuilder('f')
->distinct();
},
]);
You can also specify a flag to be distinct and remember not to return the result but return the query. You can read more here
You are right,
Query_builder is the way to go.
So first create the method of what you want to do in TransactionRepository.
class TransactionRepository extends EntityRepository
{
//....
public function getDistinctValues()
{
//Return what you want to get, I cannot write this for you without your entity
}
}
Then use it in the FormType :
$builder->add(
'newField',
EntityType::class,
[
'class' => Transaction::class,
'required' => false,
'multiple' => false,
'label' => 'New Field',
'choice_label' => 'newField',
'placeholder' => 'Choose a value',
'query_builder' => function(TransactionRepository $repository) {
return $repository->getDistinctValues();
}
]
)
And you should be good to go.

Form entity type options pre-checked

I have a form field which displays a bunch of checkboxes, the field is an EntityType. When the form renders on the front-end, a bunch of the checkboxes, not all, are already checked.
I'd like all options to be unchecked when the form renders but I can't figure out why specific ones are already checked. Below is what I currently have:
->add('example', EntityType::class, [
'class' => Example::class,
'multiple' => true,
'required' => false,
'by_reference' => false,
'expanded' => true,
'query_builder' => function (EntityRepository $repository) use ($client) {
return $repository
->createQueryBuilder('ex')
->join('ex.quote', 'e', Expr\Join::WITH, 'e.client = :client')
->setParameter('client', $client->getId());
},
]);
I have tried adding things like:
'choice_attr' => [
'checked' => false,
]
Any help would be great.

Error for Constraint added to Field does not show for field

I dynamically generate a form and add constraints (i.e. Choice).
$builder->add('test', 'choice', [
'choices' => [1, 'one', 2 => 'two'],
'required' => true,
'expanded' => true,
'error_bubbling' => true,
'cascade_validation' => true,
'label' => 'this_is_a_test',
'multiple' => false,
'constraints' => [
new NotBlank([
'groups' => ['Default']
]),
new Choice([
'min' => 1,
'choices' => [1, 2],
'groups' => ['Default']
])
]
]);
When submitting the form with empty data, the error shows up for the form, not the element of the form where i added the constraint (checked in profiler as well).
There is not Option atPath for those constraints and i add them directly to the field, so i do not get why they show up for the form.
That's what the error_bubbling option does (which you set to true in your form type):
If true, any errors for this field will be passed to the parent field or form. For example, if set to true on a normal field, any errors for that field will be attached to the main form, not to the specific field.

Symfony2 - Drop down with the possibility of adding fields

Sorry for my english.
I need to create a drop down list (select option) with values ​​taken from an Entity.
I must also add options (I use select2 to do this).
When I send the form it doesn't work. How can I configure the field type to make it work?
I need the possibilities to adding multiple persons
My current code is
...
->add('person', 'entity', array(
'attr' => array(
'class' => 'tags'
),
'class' => 'AppBundle:Person',
'data_class' => null,
'label' => 'Persons',
'mapped' => false,
'multiple' => true,
'required' => false
));
Select2
$('select.tags').select2({
language: 'it',
tags: true,
tokenSeparators: [','],
width: '100%'
});
Error message
The offset "0" does not exist.

Resources