Sonata/AdminBundle: Selected Option - php

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

Related

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

Symfony Form passing variable options from Collection to FormType

i have a collection type:
->add('tipi', CollectionType::class, array(
'entry_type' => TipiType::class,
'allow_add' => true,
'prototype' => true,
'mapped' => false,
'entry_options' => array(
'required' => true,
'label' => false,
)
))
Extend this formtype:
->add('tipi', EntityType::class, array(
'label' => 'Tipo',
'class' => 'AppBundle:Tipi',
'attr' => array('class' => 'form-control'),
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('t')
->innerJoin('t.requests', 'r')
;
},
));
In the first form type i have an options sended from controller in this way:
$idRequest = $request->get('id');
$form = $this->createForm(RequestsType::class, $requests, array(
'id_request' => $idRequest
));
In the first I can use it, but in the child FormType not. I would passing this variable in the collection type. How can I do that?
$form = $this->createForm(new YourForm($options), $class);

Adding extra options in Symfony2 EntityType always gets invalid when submitted

Hi I have successfully added an extra option in my Entity Type field in Symfony.
I have the following code:
class ReportFilterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->setMethod('GET')
->add('users', 'entity', array(
'attr' =>
array(
'class' => 'form-control',
),
'expanded' => false,
'multiple' => false,
'class' => 'AppBundle:User',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.firstName', 'ASC');
},
))
->add('dateFrom', 'date', array(
'attr' =>
array(
'id' => 'dateFrom',
'placeholder' => 'From',
'class' => 'form-control',
'data-format' => "dd/MM/yyyy",
),
'widget' => 'single_text',
'html5' => false,
))
->add('dateTo', 'date', array(
'attr' =>
array(
'id' => 'dateTo',
'placeholder' => 'To',
'class' => 'form-control',
'data-format' => "dd/MM/yyyy",
),
'widget' => 'single_text',
'html5' => false,
))
->add('filterSubmit', 'submit', array(
'attr' => array('class' => 'btn btn-default'),
'label' => 'Filter'
))
->add('pdfSubmit', 'submit', array(
'attr' => array('class' => 'btn btn-default'),
'label' => 'Export to PDF'
));
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$new_choice = new ChoiceView(new User(), 'all', 'All Employees'); // <- new option
$view->children['users']->vars['choices'][] = $new_choice;//<- adding the new option
}
public function getName()
{
return 'report_filter';
}
}
The problem here is, when I submitted my form and choose the extra option that I added it never gets valid. Why is that so? I cannot see where the problem is originating.
Thanks!

Symfony2 form type entity add extra option

I have the following Symfony form field, it's a drop down that loads from an entity:
->add('measureunit', 'entity', array('label' => 'Measure Unit',
'class' => 'TeamERPBaseBundle:MeasureUnit',
'expanded' => false, 'empty_value' => '',
'multiple' => false, 'property' => 'abreviation'
))
As you can see I have added 'empty_value' => '' and everything works fine. Now, what I want is to have an extra option at the end to add a let say new measure unit. In other words the dropdown should display all the content of my entity, the empty value and other extra option called new measure unit or what ever I want to call it. Is it possible?
Edit: The whole form type file has this:
<?php
namespace TeamERP\StoresBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('label'=>'Product name', 'required' => true,
'attr' => array('class' => 'form-control')))
->add('code', 'text', array('label'=>'Code', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('description', 'text', array('label'=>'Description', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('cost', 'money', array('label'=>'Cost', 'divisor' => 100, 'currency' => 'BWP'))
->add('category', new CategoryType(), array('required' => false))
->add('measureunit', 'entity', array('label' => 'Measure Unit',
'class' => 'TeamERPBaseBundle:MeasureUnit',
'expanded' => false, 'placeholder' => '',
'multiple' => false, 'property' => 'abreviation'
))
->add('qtyToPurchase', 'number', array('label'=>'Quantity to purchase', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('reorderPoint', 'number', array('label'=>'Reorder point', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('qtyOnSalesOrder', 'number', array('label'=>'Quantity on sales order', 'required' => false,
'attr' => array('class' => 'form-control')));
}
public function getName()
{
return 'product';
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$new_choice = new ChoiceView(array(), 'add', 'add new'); // <- new option
$view->children['measureunit']->vars['choices'][] = $new_choice;//<- adding the new option
}
}
Error:
Compile Error: Declaration of TeamERP\StoresBundle\Form\Type\ProductType::finishView() must be compatible with Symfony\Component\Form\FormTypeInterface::finishView(Symfony\Component\Form\FormView $view, Symfony\Component\Form\FormInterface $form, array $options)
Edit2 Working form file:
<?php
namespace TeamERP\StoresBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('label'=>'Product name', 'required' => true,
'attr' => array('class' => 'form-control')))
->add('code', 'text', array('label'=>'Code', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('description', 'text', array('label'=>'Description', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('cost', 'money', array('label'=>'Cost', 'divisor' => 100, 'currency' => 'BWP'))
->add('category', new CategoryType(), array('required' => false))
->add('measureunit', 'entity', array('label' => 'Measure Unit',
'class' => 'TeamERPBaseBundle:MeasureUnit',
'expanded' => false, 'placeholder' => '',
'multiple' => false, 'property' => 'abreviation'
))
->add('qtyToPurchase', 'number', array('label'=>'Quantity to purchase', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('reorderPoint', 'number', array('label'=>'Reorder point', 'required' => false,
'attr' => array('class' => 'form-control')))
->add('qtyOnSalesOrder', 'number', array('label'=>'Quantity on sales order', 'required' => false,
'attr' => array('class' => 'form-control')));
}
public function getName()
{
return 'product';
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$new_choice = new ChoiceView(array(), 'add', 'add new'); // <- new option
$view->children['measureunit']->vars['choices'][] = $new_choice;//<- adding the new option
}
}
In your form type override the function finishView:
public function buildForm(FormbuilderInterface $builder, array $options){
$builder->add('measureunit', EntityType::class, array(
'label' => 'Measure Unit',
'class' => 'TeamERPBaseBundle:MeasureUnit',
'expanded' => false,
'empty_value' => '',
'multiple' => false,
'property' => 'abbreviation'
));
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$newChoice = new ChoiceView(array(), 'add', 'Add New'); // <- new option
$view->children['measureunit']->vars['choices'][] = $newChoice;//<- adding the new option
}
You will get a new option 'add new' with value 'add' to the bottom of the field.
In addition to accepted answer:
If you choose the added option you will get validation error (because it's not valid entity), the following snippet can be used to overcome this error:
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
if ($event->getData() === 'add') {
$event->setData(null);
}
}
);
Then you can check if selected option is NULL, if it's => take value from additional input field.

Nested forms error "Entities passed to the choice field must be managed"

I've been stuck on this for days and tried all the solutions I could find online but no luck.
I have a Student linked to many Transfers. Each transfer is linked to a Classe.
To make the form I use the following classes : StudentType, TransferType.
The StudentType form classe had a field of type TransferType. Codes below.
StudentType.php
<?php
// src/PS/PSchoolBundle/Form/StudentType.php
namespace PS\PSchoolBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use PS\PSchoolBundle\Entity\Responsible;
use PS\PSchoolBundle\Entity\AuthorizedPerson;
use PS\PSchoolBundle\Entity\Transfer;
class StudentType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('subNumber', 'text', array('required' => false))
->add('subDate', 'date', array(
'required' => false,
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'attr' => array('class' => 'datepicker')
))
->add('lastName', 'text')
->add('firstName', 'text')
->add('lastNameSecondLanguage', 'text', array('required' => false))
->add('firstNameSecondLanguage', 'text', array('required' => false))
->add('birthDate', 'date', array('required' => false,
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'attr' => array('class' => 'datepicker')
))
->add('birthPlace', 'text', array('required' => false))
->add('birthPlaceSecondLanguage', 'text', array('required' => false))
->add('gender', 'choice', array('choices' => array('' => 'Veuillez choisir', 'm' => 'Garçon', 'f' => 'Fille')))
->add('nationality', 'text', array('required' => false))
->add('homeLanguage', 'text', array('required' => false))
->add('bloodType', 'text', array('required' => false))
->add('familySituation', 'choice', array('required' => false,
'choices' => array(
'' => 'Veuillez choisir',
'm' => 'Mariés',
'd' => 'Divorcés',
'w' => 'Veuve',
'a' => 'Autre')))
->add('schoolStatusBefore', 'choice', array('required' => false, 'choices' => array('' => 'Veuillez choisir', 's' => 'Scolarisé', 'ns' => 'Non scolarisé')))
->add('remark', 'textarea', array('required' => false))
->add('responsibles', 'collection', array('type' => new ResponsibleType,
'prototype' => true,
'allow_add' => true,
'allow_delete' => true))
->add('authorizedPersons', 'collection', array('type' => new AuthorizedPersonType,
'prototype' => true,
'allow_add' => true,
'allow_delete' => true))
->add('transfers', 'collection', array('type' => new TransferType,
'prototype' => true,
'allow_add' => true,
'allow_delete' => true));
}
public function getName()
{
return 'student';
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'PS\PSchoolBundle\Entity\Student'
);
}
}
TransferType.php
<?php
// src/PS/PSchoolBundle/Form/TransferType.php
namespace PS\PSchoolBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use PS\PSchoolBundle\Entity\Transfer;
use Doctrine\ORM\EntityRepository;
class TransferType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('reason', 'choice', array(
'choices' => array('success' => 'Réussite', 'failure' => 'Échec'),
'required' => false
))
->add('date', 'date', array(
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'attr' => array('class' => 'datepicker')
))
->add('school', 'text', array('required' => false))
->add('classe', 'entity', array('class' => 'PSPSchoolBundle:Classe', 'property' => 'name'));
}
public function getName()
{
return 'transfer';
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'PS\PSchoolBundle\Entity\Transfer'
);
}
}
When I added the "classe" field to the TransferType, instead of showing the form, I get this error thrown :
Entities passed to the choice field must be managed 500 Internal
Server Error - FormException
Please note that I have tried TransferType and the form shows correctly with classe choice field populated. This problem only arises when I use the TransferType and the StudentType together.
Thanks
Edit - Below is the action of the controller that generates the form:
public function byIdEditAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
if(!$student = $em->getRepository('PSPSchoolBundle:Student')->find($id))
{
throw $this->createNotFoundException('Student[id='.$id.'] does not exist.');
}
$form = $this->createForm(new StudentType(), $student);
$formHandler = new StudentHandler($form, $this->get('request'), $em);
if($formHandler->process())
{
$this->get('session')->setFlash('wehappy', "L'élève a été mis à jour.");
return $this->redirect($this->generateUrl('_studentsbyidshow', array('id' => $student->getId())));
}
return $this->render('PSPSchoolBundle:Student:edit.html.twig', array(
'form' => $form->createView(),
'student' => $student
));
}
My problem was actually linked to the fact that I'm using a StudentType that has an entity field (Transfer) which itself has an entity field (Classe).
The transfer object that was linked to the Student object did not have a Classe linked to it and thus I had that exception thrown complaining about the fact that the Classe object, that needs to be added to the Classes choice field was not managed. That means that it has to be managed by the entity manager. In other words, it had to be coming from the database.
There are two ways to fix this problem :
The obvious one was to fix the link that was missing on the database as that relation is set to not nullable on Doctrine.
The second way was to create a default Classe object and pull it from the data base, then assign it to the transfer like so :
if(!$classe = $em->getRepository('PSPSchoolBundle:Classe')->find(-2))
{
throw $this->createNotFoundException('Classe[id='.$id.'] does not exist.');
}
$transfer->setClasse($classe);
before actually creating the form using the StudentType...
Hope this helps somebody.

Categories