Set selected value on entity field (Symfony Forms) - php

I'm working with the Sonata AdminBundle and I would like to set the selected value of my select list.
I have a Category with fields: CategoryID, parentID, tag. The parentID can be NULL.
The code how I build my form:
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
// If edit -> get tag and id from tag
if($this->subject->getCategoryId() !== null)
{
$tag_current = $this->subject->getCategoryId()->getTag();
$tag_current_id = $this->subject->getCategoryId()->getParentid()->getCategoryid();
}
$formMapper
->add('tag', 'text', array('label' => 'Tag'))
->add('name', 'text', array('label' => 'Naam'))
->add('nameEN', 'text', array('label' => 'Naam Engels', 'required' => false, 'data' => 'test'))
->add('parentcategory', 'entity', array(
'class' => 'DX\MyBundle\Entity\Category',
'empty_data' => null,
'empty_value' => "GEEN PARENT CATEGORIE",
'required' => false,
'data' => $tag_current_id,
'query_builder' => function(EntityRepository $er) use ($tag_current) {
return $er->createQueryBuilder('c')
->where('c.parentid IS NULL')
->andWhere('c.tag != :tag')
->andWhere('c.tag != :tag_current')
->setParameter('tag', 'FOTOGRAAF')
->setParameter('tag_current', $tag_current);
}
))
;
}
As you see I've tried to set data property with no result. The empty value NO PARENT CATEGORY is always selected on page load.
My $tag_current_id is an integer, in this case: 11 . And my select list looks like this:
<select id="s54ff22c20ca39_parentcategory" name="s54ff22c20ca39[parentcategory]" class="select2-offscreen" tabindex="-1" title="Parentcategory">
<option value="">GEEN PARENT CATEGORIE</option>
<option value="1">THEMA</option>
<option value="11">FREEM SELECTIE</option>
</select>
But still not selected. What am I doing wrong?

Your query builder should return all the available values, it will select automatically your database value :
$formMapper->add('parentcategory', 'entity', array(
'class' => 'DX\MyBundle\Entity\Category',
'empty_data' => null,
'empty_value' => "GEEN PARENT CATEGORIE",
'required' => false,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('c')
->where('c.parentid IS NULL')
->andWhere('c.tag != :tag')
->setParameter('tag', 'FOTOGRAAF')
}
))
Update:
This is what i'm doing in my project :
$formMapper->add('supplier', 'entity', array(
'class' => 'AcmeCoreBundle:ShopSupplier',
'empty_value' => 'None',
'empty_data' => null,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('ss')
->orderBy('ss.name', 'ASC');
}
))
It selects automatically the database value and set the empty_value when none is selected. If it doesn't work in your project, i have no idea.

Related

How to add a first empty line to a select in Symfony

I'm making createQueryBuilder inside my BuildForm method to get some records from an entity.
Everything work well, I succeded to display a select with the data I want but I have not a first line with an empty value.
<select id="" name="" class="form-control">
<option value="7">A</option>
<option value="8">B</option>
<option value="9">C</option>
</select>
And here's the code I've a made in the BuildForm method
$builder->add('company', EntityType::class, array(
'class' => Company::class,
'query_builder' => function(EntityRepository $er) use ($options) {
return $er->createQueryBuilder('c')
->where("c.id in {$options['id']}");
},
'label' => 'Company',
));
Just add 'required' => false to the options (where you set the label)
You can set required => false
$builder->add('company', EntityType::class, array(
'class' => Company::class,
// Here you set required to false
'required' => false,
'query_builder' => function(EntityRepository $er) use ($options) {
return $er->createQueryBuilder('c')
->where("c.id in {$options['id']}");
},
'label' => 'Company',
));

Symfony query_builder add null option

In my Form type I have a select choice which list my team entities.
When I do this
$builder->add('teams');
it lists all my teams on my form AND an empty choice, so it's possible to have no team or to remove the team (and that behavior is great for what I have to do).
But when I use a query_builder
$builder->add('teams', EntityType::class, array(
'class' => Team::class,
'query_builder' => function (EntityRepository $er) {
return $er->getTeamsNotRestrictedByAdmin();
},
'choice_label' => '_name'
)
);
it returns the entities I want but I don't have that null choice anymore. How could I get it back properly ?
Go with :
$builder->add('teams', EntityType::class, array(
'class' => Team::class,
'query_builder' => function (EntityRepository $er) {
return $er->getTeamsNotRestrictedByAdmin();
},
'choice_label' => '_name',
'required' => false,
'empty_data' => ''
)
);

Sonata/AdminBundle: Selected Option

I'm new in Symfony and Sonata/AdminBundle. I would like to know how to mark selected an option when the entity has a field from other entity. For example: I have two entities: Shop and City. The Shop entity has a field called id_city.
My problem is when I'm rendering the edit form Shop because always the first id_city in the option is selected.
This is the piece of code where I'm rendering the configuration form in AdminStores class:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->tab('Tiendas')
->with('Content', array('class' => 'col-md-9'))
->add('nombreTienda', 'text')
->add('cifTienda', 'text')
->add('direccionTienda', 'text')
->add('personaContacto', 'text', array('required' => false,'empty_data' => ''))
->add('cp', 'text', array('label' => 'Código Postal', 'required' => false, 'empty_data' => '00000'))
->add('urlTienda', 'text', array('required' => false, 'empty_data' => ''))
->add('emailTienda', 'text')
->add('telefonoTienda', 'text')
->add('login', 'text')
->add('pass', 'password', array('required' => false))
->add('idMunicipio', 'entity', array(
'class' => 'AppBundle:Municipios',
'choice_label' => 'municipio',
'query_builder' => function (EntityRepository $er) {
$lista = $er->createQueryBuilder('ss')
->orderBy('ss.municipio', 'ASC');
},
'data' => $this->subject->getIdMunicipio()
)) // end array idMunicipio y add()
->add('idProvincia', EntityType::class, array(
'class' => 'AppBundle:Provincias',
'label' => 'Provincia',
'choice_label' => 'provincia',
'choice_value' => 'getId',
'by_reference' => true,
))
->add('descripcionTienda', 'textarea')
->end()
->end()
->tab('Multimedia')
->with('Content', array('class' => 'col-md-3'))
->add('fotoTienda', 'file', array(
'label' => 'Imagenes (puedes subir hasta 6 imágenes)',
'attr' =>array('class' => 'form-control', 'multiple' => 'multiple', 'accept' => 'image/*'),
'data_class' => null,
'required' => false,
'empty_data' => 'noDisponible',
));
}
In this piece of code, I'm recovering all cities in AdminStores class:
->add('idMunicipio', 'entity', array(
'class' => 'AppBundle:Municipios',
'choice_label' => 'municipio',
'query_builder' => function (EntityRepository $er) {
$lista = $er->createQueryBuilder('ss')
->orderBy('ss.municipio', 'ASC');
},
'data' => $this->subject->getIdMunicipio()
)) // end array idMunicipio y add()
I would like to know, please, the logic for " if this->id_city == entity->id_city then, option is selected".
Thanks in advance
I edit this comment because I think that I solved it.
In my AdminController called ShopsAdmin I have created a method called getAllMunicipios which return an array with their name and id:
$allCities = array(
'Tokyo' => 1
'Madrid => 2
);
This is the method:
protected function getAllMunicipios()
{
$municipios = $this->getConfigurationPool()
->getContainer()
->get('doctrine')
->getRepository('AppBundle:Municipios')
->findBy([], ['municipio' => 'ASC']);
$todosmunicipios = array();
foreach ($municipios as $municipio) {
$todosmunicipios[(string)$municipio->getMunicipio()] = (int)$municipio->getId();
}
return $todosmunicipios;
}
Now my AdminStores::configureFormFields method like that this:
->add('idMunicipio', 'choice', array(
'choices' => $this->getAllMunicipios(),
'required' => false,
'by_reference' => false,
'data' => $this->subject->getIdMunicipio()
))
It is a good way to do it? I think that the method that return all, must be placed into the entity and not int the controller but I dont know how do it static
just call setCity(\AppBundle\Entity\City $city) in your Shop entity. and give the right city entity as the first and only parameter. Do this before you render the form

Customize 'choice_label' of EntityType Field for Twig

I have the following form:
$form = $this->createFormBuilder()
->setMethod('POST')
->add('users', EntityType::class, array(
'class' => 'AppBundle:User',
'choices' => $users,
'expanded' => true,
'multiple' => false,
'choice_label' => function ($user) {
return $user->getUsername();
}
))
->add('selected', SubmitType::class, array('label' => 'select'))
->getForm();
return $this->render('default/showUsers.html.twig', array('form' => $form->createView()));
I have 2 Problems with that:
I can not customize the 'choice_label' like:
'choice_label' => function ($user) {
return ($user->getId() + " " + $user->getUsername());
}
There is not Linebreak after each choice (or after each Radio button), which gets pretty ugly with the alot of users.
How can I customize the 'choice_label's ?
How can I get a Linebreak after each Radio button ?
You can customise this to string method however you want and then remove the 'choice_label' attribute in form builder
//in user entity
public function __toString()
{
$string =$this->getId(). ' ' . $this->getUsername();
return $string;
}
To customise labels you, I would use style sheets. You can add a class using attr or choice_attr for individual radio inputs based on their values .. For example
->add('users', EntityType::class, array(
'class' => 'AppBundle:User',
'choices' => $users,
'attr' => array('class' =>'type_label'),
'choice_attr' => array(
'0' => array('class' => 'class_one'),
'1' => array('class' => 'class_two'),
),
'expanded' => true,
'multiple' => false,
))
See symfony reference for more information

Automatic initialization is only supported on root forms. You should set the "auto_initialize" option to false on the field

I'm having the following error in my Symfony2 project:
Automatic initialization is only supported on root forms. You should set the "auto_initialize" option to false on the field "descriptionEN".
I'm using the Sonata Admin Bundle. I would like to populate a text field in my form before rendering the form. So I am using the form event PRE_SET_DATA . In Sonata you only have prePersist & preUpdate so I am doing it like this:
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('tag', 'text', array('label' => 'Tag'))
->add('description', 'text', array('label' => 'Beschrijving'))
->add('content', 'textarea', array('label' => 'Tekst', 'attr' => array('class' => 'ckeditor'), 'help' =>
'Schrijf 2 paragrafen onder elkaar, deze worden naast elkaar geplaatst op de website.'))
->add('files', 'file', array('required' => false, 'multiple' => true, 'help' =>
'<b>Home:</b> 1277×670.png<br><b>Gallerij:</b> 1284×110.jpg<br><b>Diensten:</b> 1282×375.jpg<br><b>Footer:</b> 1281×375.jpg'))
;
$builder = $formMapper->getFormBuilder();
$factory = $builder->getFormFactory();
$func = function (FormEvent $e) use ($factory) {
$form = $e->getForm();
$page = $e->getData();
$pageLocale = $this->getSubject();
$pageID = $pageLocale->getPageId();
if($pageID === null)
{
return;
}
$form->add($factory->createNamed('descriptionEN', 'text', array(
'auto_initialize' => false,
'label' => 'Beschrijving Engels',
'query_builder' => function (EntityRepository $repository) use ($pageID) {
return $repository->getDescriptionEN($pageID);
}
)));
};
$builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
}
The strange thing is I'm getting the error that auto_initialize should be false when I've specifically set it to false ... . I'm definitely sure that's the field causing problems because when I comment the field I get no errors.
What could be another reason causing this?
The array of options is the fourth parameter of the function createNamed
$form->add($factory->createNamed('descriptionEN', 'text', null, array(
'auto_initialize' => false,
'label' => 'Beschrijving Engels',
'query_builder' => function (EntityRepository $repository) use ($pageID) {
return $repository->getDescriptionEN($pageID);
}

Categories