[sonataAdmin]: test the select imput value - symfony

I want to retrieve the value of select input and make the test on this value. If this value corresponds to what I am looking for in my case "freelance" I display a block if no I display another
this is my code:
$emr = $this->modelManager->getEntityManager('PivotalBOBundle:Role');
$queryr = $kernel->getContainer()->get('doctrine')->getRepository('PivotalBOBundle:Role')->findAll();
$choises=array();
foreach ($queryr as $res){
$choises[$res->getRole()]=$res->getRole();
}
->tab('Spécifique')
->with('Type d\'utilisateur', array('class' => 'col-md-12'))
->add('type', 'choice', array('label' => 'Type',
'choices' => $choises))
->end()
->with('Freelancer', array('class' => 'col-md-12 Freelancer'))
->add('type', 'checkbox', array('required' => false, 'label' => 'Freelancer'))
->add('categories', 'sonata_type_model', array(
"multiple" => true,
'label' => 'Catégorie',
'required' => true,
'query' => $query))
->add('outilsEtTechnologie', 'sonata_type_model', array(
'required' => false,
"multiple" => true,
'label' => 'Outils et Technologie'))
->add('niveauCompetences', 'sonata_type_collection', array(
'required' => false,
'label' => 'Niveau des compétences',
'by_reference' => true), array(
'edit' => 'inline',
'inline' => 'table'
))
->add('niveauLangue', 'sonata_type_collection', array(
'required' => false,
'label' => 'Niveau des langues',
'by_reference' => false), array(
'edit' => 'inline',
'inline' => 'table'
))
->add('formation', 'sonata_type_collection', array(
'required' => false,
'label' => 'Formations',
'by_reference' => false), array(
'edit' => 'inline',
'inline' => 'table'
))
->add('mobilite', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\Mobilite',
'required' => true,
'label' => 'Mobilite'
))
->add('frequence', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\Frequence',
'required' => true,
'label' => 'Frequence'
))
->add('niveauExperience', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\NiveauExperience',
'required' => true,
'label' => 'Niveau Experience'))
->add('missionetranger', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\Missionetranger',
'required' => true,
'label' => 'Mission Etranger'))
->add('note', null, array('label' => 'Note'))
->end()
->with('Jobowner ', array('class' => 'col-md-12 Jobowner'))
->add('type', 'checkbox', array('required' => false, 'label' => 'Jobowner'))
->add('societe', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\Societe',
'property' => 'nom',
'label' => 'Societe',
'required' => false,
))
->end();
this is an image of my render the case 1
and this is my objectif :
the freelancer option
the jobowner option

You can access the current subject with $this->getSubject().
So you could modify your Form by using:
$subject = $this->getSubject();
// with "Type d'utilisateur"
if ($subject && $subject->getType() === 'freelance') {
// with "Freelancer"
}
// other tabs/form-fields
This only works if you gonna re-open your form view. If you need to instantly modify your form if you select "freelance" without reloading the page, you need to write it in Javascript. Depending on your needs, this varies a lot (e.g. hiding the tab/with-section and show it via Javascript).

to do this we should use a java script code like this :
->tab('Spécifique')
->with('Type d\'utilisateur', array('class' => 'col-md-12'))
->add('type', 'choice', array('label' => 'Type',
'choices' => $choises))
->end()
->with('Freelancer', array('class' => 'col-md-12 userFreelancer'))
->add('categories', 'sonata_type_model', array(
"multiple" => true,
'label' => 'Catégorie',
'required' => true,
'query' => $query))
->add('outilsEtTechnologie', 'sonata_type_model', array(
'required' => false,
"multiple" => true,
'label' => 'Outils et Technologie'))
->add('niveauCompetences', 'sonata_type_collection', array(
'required' => false,
'label' => 'Niveau des compétences',
'by_reference' => true), array(
'edit' => 'inline',
'inline' => 'table'
))
->add('niveauLangue', 'sonata_type_collection', array(
'required' => false,
'label' => 'Niveau des langues',
'by_reference' => false), array(
'edit' => 'inline',
'inline' => 'table'
))
->add('formation', 'sonata_type_collection', array(
'required' => false,
'label' => 'Formations',
'by_reference' => false), array(
'edit' => 'inline',
'inline' => 'table'
))
->add('mobilite', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\Mobilite',
'required' => true,
'label' => 'Mobilite'
))
->add('frequence', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\Frequence',
'required' => true,
'label' => 'Frequence'
))
->add('niveauExperience', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\NiveauExperience',
'required' => true,
'label' => 'Niveau Experience'))
->add('missionetranger', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\Missionetranger',
'required' => true,
'label' => 'Mission Etranger'))
->add('note', null, array('label' => 'Note'))
->end();
$formMapper->with('Societe', array('class' => 'col-md-12 Societe'))
->add('societe', 'entity', array(
'class' => 'Pivotal\BOBundle\Entity\Societe',
'property' => 'nom',
'label' => 'Societe',
'required' => false,
))
->end()
->end();
and we should overide the template
like that :
public function getTemplate($name)
{
if ($name == "edit") {
return 'admin/edit.html.twig';
}
return parent::getTemplate($name);
}
and add a javascript code in edit.html.twig :
<script type="text/javascript">
$(document).ready(function () {
var type = $("#{{ admin.uniqId }}_type");
var freelancer = $(".userFreelancer");
var jobowner = $(".userJobowner");
var redacteur = $(".userRedacteur");
var Supperjobowner = $(".userSupperjobowner");
var Nactif = $(".userNactif");
var Societe = $(".Societe");
hideUserBlock()
type.change(function () {
displayUserBlock();
}); // Bind the function to displayBlock
type.change(); // Manual trigger to display block.
function displayUserBlock() {
hideUserBlock();
var type =$("#{{ admin.uniqId }}_type").val()
switch(type) {
case 'Freelancer':
freelancer.css("display", "block");
freelancer.trigger("create");
break;
case 'Jobowner':
Societe.css("display", "block");
Societe.trigger("create");
break;
case 'Super Jobowner':
Societe.css("display", "block");
Societe.trigger("create");
break;
case 'Jobowner non actif':
Societe.css("display", "block");
Societe.trigger("create");
break;
case 'Rédacteur':
Societe.css("display", "block");
Societe.trigger("create");
break;
}
}
function hideUserBlock() {
freelancer.css("display", "none");
freelancer.trigger("create");
Societe.css("display", "none");
Societe.trigger("create");
}
});
</script>

Related

How to getData() on a collectionType field - Symfony 4

I have a collectionType (Equipements) on a Symfony 4 ORM form (intervention).
For example, this equipement field :
<input type="file" id="intervention_equipements_0_photoGraffiti" name="intervention[equipements][0][photoGraffiti]">
I try to get the data of this field with :
$fileToTransfer = $form['intervention_equipements_0_photoGraffiti']->getData();
or
$fileToTransfer = $form['intervention[equipements][0][photoGraffiti]']->getData();
I have the error Child "intervention[equipements][0][photoGraffiti]" does not exist.
Here is my intervention Type :
$builder
->add('idInstallation', EntityType::class, [
'class' => Installation::class,
'choice_label' => 'numeroInstallation',
'required' => false,
])
->add('equipements', CollectionType::class, array(
'entry_type' => EquipementInterventionType::class,
'entry_options' => array('label' => false),
))
And the equipement entity:
$builder
->add('nom', TextType::class, array(
'error_bubbling' => true,
'required' => false,
'disabled' => true
))
->add('numero', TextType::class, array(
'error_bubbling' => true,
'required' => false,
'disabled' => true
))
->add('etatEquipement', ChoiceType::class, array(
'choices' => $choices_controle,
'expanded' => false,
'multiple' => false,
'required' => false,
'error_bubbling' => true,
))
->add('photoEquipement', FileType::class, array(
'error_bubbling' => true,
'required' => false,
'disabled' => false,
'data_class' => null
))
->add('graffiti', CheckboxType::class, array(
'required' => false,
'error_bubbling' => true,
))
->add('photoGraffiti', FileType::class, array(
'error_bubbling' => true,
'required' => false,
'disabled' => false,
'data_class' => null
))
...
How can I fix this, please ?
Directly use $form->getData(). This will return the array with all your form datas that you are looking for.
in your form controller
$equipements = $intervention->getEquipement();
will return the array of collections then
foreach ($equipements as $equipement) {
$fileToTransfer = $equipement->getPhotoGraffiti()
}
Hope you have getter and setter in your entity class

Symfony 4 : Property App\Entity\Ad::$site does not exist (but impossible to find in the code ?)

I had a class Site link to my class Annonce.
I deleted everything about "Site", did the migration with doctrine.
Then this error appeared.
So i did a find in all the file to see if "site" it's somewhere and delete everywhere.
And i still have this error.
I don't know what to do ?
Can have a cache problem ?
This is the stack Trace
ReflectionException:
Property App\Entity\Annonce::$site does not exist
at vendor/doctrine/persistence/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php:63
at ReflectionProperty->__construct('App\\Entity\\Annonce', 'site')
(vendor/doctrine/persistence/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php:63)
at Doctrine\Common\Persistence\Mapping\RuntimeReflectionService->getAccessibleProperty('App\\Entity\\Annonce', 'site')
(vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:970)
at Doctrine\ORM\Mapping\ClassMetadataInfo->wakeupReflection(object(RuntimeReflectionService))
(vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:750)
at Doctrine\ORM\Mapping\ClassMetadataFactory->wakeupReflection(object(ClassMetadata), object(RuntimeReflectionService))
(vendor/doctrine/persistence/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:181)
at Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor('App\\Entity\\Annonce')
(vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:283)
at Doctrine\ORM\EntityManager->getClassMetadata('App\\Entity\\Annonce')
(vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:2692)
at Doctrine\ORM\UnitOfWork->createEntity('App\\Entity\\Categorie', array('id' => 1, 'nom' => 'Bar Tabac PMU'), array('deferEagerLoad' => true, 'fetchAlias' => 'e'))
(vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:271)
at Doctrine\ORM\Internal\Hydration\ObjectHydrator->getEntity(array('id' => 1, 'nom' => 'Bar Tabac PMU'), 'e')
(vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:492)
at Doctrine\ORM\Internal\Hydration\ObjectHydrator->hydrateRowData(array('id_0' => '1', 'nom_1' => 'Bar Tabac PMU'), array())
(vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:162)
at Doctrine\ORM\Internal\Hydration\ObjectHydrator->hydrateAllData()
(vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php:152)
at Doctrine\ORM\Internal\Hydration\AbstractHydrator->hydrateAll(object(PDOStatement), object(ResultSetMapping), array())
(vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php:976)
at Doctrine\ORM\AbstractQuery->executeIgnoreQueryCache(null, null)
(vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php:922)
at Doctrine\ORM\AbstractQuery->execute()
(vendor/symfony/doctrine-bridge/Form/ChoiceList/ORMQueryBuilderLoader.php:50)
at Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader->getEntities()
(vendor/symfony/doctrine-bridge/Form/ChoiceList/DoctrineChoiceLoader.php:85)
at Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader->loadChoiceList(array(object(IdReader), 'getIdValue'))
(vendor/symfony/form/ChoiceList/LazyChoiceList.php:62)
at Symfony\Component\Form\ChoiceList\LazyChoiceList->getChoices()
(vendor/symfony/form/ChoiceList/Factory/DefaultChoiceListFactory.php:53)
at Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory->createView(object(LazyChoiceList), array(), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), null, null)
(vendor/symfony/form/ChoiceList/Factory/PropertyAccessDecorator.php:193)
at Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator->createView(object(LazyChoiceList), array(), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), null, null)
(vendor/symfony/form/ChoiceList/Factory/CachingFactoryDecorator.php:127)
at Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator->createView(object(LazyChoiceList), array(), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), null, null)
(vendor/symfony/form/Extension/Core/Type/ChoiceType.php:410)
at Symfony\Component\Form\Extension\Core\Type\ChoiceType->createChoiceListView(object(LazyChoiceList), array('block_name' => null, 'disabled' => false, 'label_format' => null, 'label_translation_parameters' => array(), 'attr_translation_parameters' => array(), 'translation_domain' => null, 'auto_initialize' => true, 'trim' => false, 'property_path' => null, 'mapped' => true, 'by_reference' => true, 'inherit_data' => false, 'method' => 'POST', 'action' => '', 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'allow_file_upload' => false, 'help_translation_parameters' => array(), 'error_mapping' => array(), 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => array(), 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', 'csrf_protection' => true, 'csrf_field_name' => '_token', 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => object(CsrfTokenManager), 'csrf_token_id' => null, 'multiple' => false, 'expanded' => false, 'block_prefix' => null, 'label' => 'Catégorie de commerce *', 'row_attr' => array(), 'attr' => array(), 'data_class' => null, 'empty_data' => '', 'required' => true, 'error_bubbling' => false, 'label_attr' => array(), 'compound' => false, 'upload_max_size_message' => object(Closure), 'help' => null, 'help_attr' => array(), 'help_html' => false, 'validation_groups' => null, 'constraints' => array(), 'choices' => null, 'query_builder' => null, 'class' => 'App\\Entity\\Categorie', 'em' => object(EntityManager), 'id_reader' => object(IdReader), 'choice_loader' => object(DoctrineChoiceLoader), 'choice_label' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), 'choice_name' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), 'choice_value' => array(object(IdReader), 'getIdValue'), 'choice_attr' => null, 'preferred_choices' => array(), 'group_by' => null, 'placeholder' => 'Choisir une catégorie', 'choice_translation_domain' => false))
(vendor/symfony/form/Extension/Core/Type/ChoiceType.php:185)
at Symfony\Component\Form\Extension\Core\Type\ChoiceType->buildView(object(FormView), object(Form), array('block_name' => null, 'disabled' => false, 'label_format' => null, 'label_translation_parameters' => array(), 'attr_translation_parameters' => array(), 'translation_domain' => null, 'auto_initialize' => true, 'trim' => false, 'property_path' => null, 'mapped' => true, 'by_reference' => true, 'inherit_data' => false, 'method' => 'POST', 'action' => '', 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'allow_file_upload' => false, 'help_translation_parameters' => array(), 'error_mapping' => array(), 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => array(), 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', 'csrf_protection' => true, 'csrf_field_name' => '_token', 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => object(CsrfTokenManager), 'csrf_token_id' => null, 'multiple' => false, 'expanded' => false, 'block_prefix' => null, 'label' => 'Catégorie de commerce *', 'row_attr' => array(), 'attr' => array(), 'data_class' => null, 'empty_data' => '', 'required' => true, 'error_bubbling' => false, 'label_attr' => array(), 'compound' => false, 'upload_max_size_message' => object(Closure), 'help' => null, 'help_attr' => array(), 'help_html' => false, 'validation_groups' => null, 'constraints' => array(), 'choices' => null, 'query_builder' => null, 'class' => 'App\\Entity\\Categorie', 'em' => object(EntityManager), 'id_reader' => object(IdReader), 'choice_loader' => object(DoctrineChoiceLoader), 'choice_label' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), 'choice_name' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), 'choice_value' => array(object(IdReader), 'getIdValue'), 'choice_attr' => null, 'preferred_choices' => array(), 'group_by' => null, 'placeholder' => 'Choisir une catégorie', 'choice_translation_domain' => false))
(vendor/symfony/form/ResolvedFormType.php:148)
at Symfony\Component\Form\ResolvedFormType->buildView(object(FormView), object(Form), array('block_name' => null, 'disabled' => false, 'label_format' => null, 'label_translation_parameters' => array(), 'attr_translation_parameters' => array(), 'translation_domain' => null, 'auto_initialize' => true, 'trim' => false, 'property_path' => null, 'mapped' => true, 'by_reference' => true, 'inherit_data' => false, 'method' => 'POST', 'action' => '', 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'allow_file_upload' => false, 'help_translation_parameters' => array(), 'error_mapping' => array(), 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => array(), 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', 'csrf_protection' => true, 'csrf_field_name' => '_token', 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => object(CsrfTokenManager), 'csrf_token_id' => null, 'multiple' => false, 'expanded' => false, 'block_prefix' => null, 'label' => 'Catégorie de commerce *', 'row_attr' => array(), 'attr' => array(), 'data_class' => null, 'empty_data' => '', 'required' => true, 'error_bubbling' => false, 'label_attr' => array(), 'compound' => false, 'upload_max_size_message' => object(Closure), 'help' => null, 'help_attr' => array(), 'help_html' => false, 'validation_groups' => null, 'constraints' => array(), 'choices' => null, 'query_builder' => null, 'class' => 'App\\Entity\\Categorie', 'em' => object(EntityManager), 'id_reader' => object(IdReader), 'choice_loader' => object(DoctrineChoiceLoader), 'choice_label' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), 'choice_name' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), 'choice_value' => array(object(IdReader), 'getIdValue'), 'choice_attr' => null, 'preferred_choices' => array(), 'group_by' => null, 'placeholder' => 'Choisir une catégorie', 'choice_translation_domain' => false))
(vendor/symfony/form/ResolvedFormType.php:145)
at Symfony\Component\Form\ResolvedFormType->buildView(object(FormView), object(Form), array('block_name' => null, 'disabled' => false, 'label_format' => null, 'label_translation_parameters' => array(), 'attr_translation_parameters' => array(), 'translation_domain' => null, 'auto_initialize' => true, 'trim' => false, 'property_path' => null, 'mapped' => true, 'by_reference' => true, 'inherit_data' => false, 'method' => 'POST', 'action' => '', 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'allow_file_upload' => false, 'help_translation_parameters' => array(), 'error_mapping' => array(), 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => array(), 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', 'csrf_protection' => true, 'csrf_field_name' => '_token', 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => object(CsrfTokenManager), 'csrf_token_id' => null, 'multiple' => false, 'expanded' => false, 'block_prefix' => null, 'label' => 'Catégorie de commerce *', 'row_attr' => array(), 'attr' => array(), 'data_class' => null, 'empty_data' => '', 'required' => true, 'error_bubbling' => false, 'label_attr' => array(), 'compound' => false, 'upload_max_size_message' => object(Closure), 'help' => null, 'help_attr' => array(), 'help_html' => false, 'validation_groups' => null, 'constraints' => array(), 'choices' => null, 'query_builder' => null, 'class' => 'App\\Entity\\Categorie', 'em' => object(EntityManager), 'id_reader' => object(IdReader), 'choice_loader' => object(DoctrineChoiceLoader), 'choice_label' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), 'choice_name' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), 'choice_value' => array(object(IdReader), 'getIdValue'), 'choice_attr' => null, 'preferred_choices' => array(), 'group_by' => null, 'placeholder' => 'Choisir une catégorie', 'choice_translation_domain' => false))
(vendor/symfony/form/Form.php:1030)
at Symfony\Component\Form\Form->createView(object(FormView))
(vendor/symfony/form/Form.php:1033)
at Symfony\Component\Form\Form->createView()
(src/Controller/AnnonceController.php:60)
at App\Controller\AnnonceController->newFree(object(Request))
(vendor/symfony/http-kernel/HttpKernel.php:151)
at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
(vendor/symfony/http-kernel/HttpKernel.php:68)
at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
(vendor/symfony/http-kernel/Kernel.php:198)
at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
(public/index.php:22)
Thanks
It is definitely a cache issue. Try the following in order and see if it helps:
bin/console cache:clear
rm the var/cache folder
manually clear any additional PHP cache you might have enabled
I also has this same issue. I can confirm that it is an issue with the DB cache.
Before running migrations you should run this commands:
bin/console doctrine:cache:clear-query --flush
bin/console doctrine:cache:clear-result --flush
bin/console doctrine:cache:clear-metadata --flush
If you are using redis to store the DB cache you might also need to flush that before executing migrations. You can do this from the redis-cli by typing FLUSHALL

Symfony2 collection of choices different option for each elements

After several search and try I don't know how to solve my problem.
I found this: Symfony2 Form Collection Field with Different Choices but solution was not given only a search trail and I didn't found how to adapt solution in my case.
I have Many to Many relation between Localization and Region, Many to Many relation between LOcalization and Department and Many to Many relation between Localization and City.
To create a localization i have this form:
class LocalizationType extends AbstractType{
private $manager;
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
}
public function buildForm(FormBuilderInterface $builder, array $options){
$builder->add('regions', CollectionType::class, array('entry_type' => ChoiceType::class,
'allow_add' => true,
'allow_delete' => true,
'required' => false,
'entry_options' => array(
'choices' => (array_key_exists('regions', $options['localization_value']) ? $options['localization_value']['regions'] : array('' => '')),
'multiple' => false,
'expanded' => false,
'attr' => array('class' => 'region input'),
),
'data' => (array_key_exists('regions', $options['localization_data']) ? $options['localization_data']['regions'] : null),
))
->add('departments', CollectionType::class, array('entry_type' => ChoiceType::class,
'allow_add' => true,
'allow_delete' => true,
'required' => false,
'entry_options' => array(
'choices' => (array_key_exists('departments', $options['localization_value']) ? $options['localization_value']['departments'] : array('' => '')),
'multiple' => false,
'expanded' => false,
'attr' => array('class' => 'department input')
),
'data' => (array_key_exists('departments', $options['localization_data']) ? $options['localization_data']['departments'] : null),
))
->add('cities', CollectionType::class, array('entry_type' => ChoiceType::class,
'allow_add' => true,
'allow_delete' => true,
'required' => false,
'entry_options' => array(
'choices' => (array_key_exists('cities', $options['localization_value']) ? $options['localization_value']['regions'] : array('' => '')),
'multiple' => false,
'expanded' => false,
'attr' => array('class' => 'city input')
),
'data' => (array_key_exists('cities', $options['localization_data']) ? $options['localization_data']['cities'] : null),
))
;
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event){
$data = $event->getData();
if(!empty($data['regions']) && is_array($data['regions'])){
$regions = array();
foreach($data['regions'] as $region){
$regions[] = $region;
}
$data['regions'] = $this->manager->getRepository('LocalizationBundle:Region')->findRegionsForCreateEntity($regions);
}
if(!empty($data['departments']) && is_array($data['departments'])){
$departments = array();
foreach($data['departments'] as $department){
$departments[] = $department;
}
$data['departments'] = $this->manager->getRepository('LocalizationBundle:Departments')->findDepartmentsForCreateEntity($departments);
}
if(!empty($data['cities']) && is_array($data['cities'])){
$cities = array();
foreach($data['cities'] as $city){
$cities[] = $city;
}
$data['cities'] = $this->manager->getRepository('LocalizationBundle:City')->findCitiesForCreateEntity($cities);
}
$form = $event->getForm();
$form->add('regions', CollectionType::class, array('entry_type' => ChoiceType::class,
'allow_add' => true,
'allow_delete' => true,
'required' => false,
'entry_options' => array(
'choices' => $data['regions'],
'multiple' => false,
'expanded' => false,
'attr' => array('class' => 'region input')
)
));
$form->add('departments', CollectionType::class, array('entry_type' => ChoiceType::class,
'allow_add' => true,
'allow_delete' => true,
'required' => false,
'entry_options' => array(
'choices' => $data['departments'],
'multiple' => false,
'expanded' => false,
'attr' => array('class' => 'department input')
)
))
->add('cities', CollectionType::class, array('entry_type' => ChoiceType::class,
'allow_add' => true,
'allow_delete' => true,
'required' => false,
'entry_options' => array(
'choices' => $data['cities'],
'multiple' => false,
'expanded' => false,
'attr' => array('class' => 'city input')
)
))
;
});
}
public function configureOptions(OptionsResolver $resolver){
$resolver->setDefaults(array(
'data_class' => Localization::class,
'localization_data' => array('regions' => '', 'departments' => '', 'cities' => ''),
'localization_value' => array('regions' => '', 'departments' => '', 'cities' => ''),
));
}
I choose a ChoiceType empty because I have several City for example( more of 25k) so I prefer load few of them with AJAX in my view and render them in a select2, it works for add action but for edit action I have a problem I want each field of my collections have a different value.
To illustrate my story, I want this result:
<label>Region n°1</label>
<select id="" name="">
<option value="foo1">bar1</option>
</select>
<label>Region n°2</label>
<select id="" name="">
<option value="foo2">bar2</option>
</select>
And the result I have for the moment is:
<label>0</label>
<select id="" name="">
<option value="foo1" selected="selected">bar1</option>
<option value="foo2">bar2</option>
</select>
<label>1</label>
<select id="" name="">
<option value="foo1">bar1</option>
<option value="foo2" selected="selected">bar2</option>
</select>
To change label if I understand I need to create my own template, ok but to display only option selected and not others I think I need a FormEventListener on PRE_SET_DATA but I don't see how implement this. So if someone has a solution, I'll take it.
I answer my own question, after try with FormEventListener on PRE_SET_DATA, on POST_SET_DATA, or with a choice_loader it's seems to be impossible to do what i want with a Symfony way, but i don't well understand why. I feel back on Jquery way to remove option who are not selected with following code, i dislike but I don't see others solutions:
<script type="text/javascript">
$.each($('.region'), function(i, val){
$(val).find('option:not(:selected)').remove();
})
$.each($('.department'), function(i, val){
$(val).find('option:not(:selected)').remove();
})
$.each($('.city'), function(i, val){
$(val).find('option:not(:selected)').remove();
})
</script>
I don't pass the topic as solved in case I'm wrong

How to include layout to SonataAdminBundle tab with use sonata_type_admin

I use Symfony2 with SonataAdminBundle, and I have a problem where I add a Tab with sonata_type_admin Entity edit. If I go to Entity edit page - all right, but if I add field in OneToOne relationship on tab layout not loaded and all in one style.
Reading documentation not help me, I don't found this decision of this problem in settings. Please, help me.
Main object edit
$formMapper
->tab('Основная информация')
->with('Данные клуба', ['class' => 'col-md-8'])
->add('name', 'text', array('label' => 'Название'))
->add('alias', 'text', array('label' => 'alias в url на сайте'))
->add('logo', 'text', ['label' => 'Логотип'])
->add('description', 'textarea', ['label' => 'Описание клуба'])
->end()
->with('Основные настройки', ['class' => 'col-md-4'])
->add('type', 'entity', [
'label' => 'Тип клуба',
'class' => 'PbmozgSiteBundle:ClubType',
'query_builder' => function(EntityRepository $repository) {return $repository->createQueryBuilder('ClubType')->orderBy('ClubType.id', 'ASC');},
'property' => 'name',
'empty_value' => 'Выберите тип клуба',
'required' => false
]
)
->add('enabled', 'checkbox', ['label' => 'Включен'])
->add('vip', 'checkbox', ['label' => 'VIP'])
->add('rating', 'text', [
'label' => 'Рейтинг клуба',
'read_only' => true,
'disabled' => true,
]
)
->end()
->end()
->tab('Контактная информация')
->with('Контакты')
->add('contacts', 'sonata_type_admin', ['required' => false, 'delete' => false, 'btn_add' => false])
->end()
->end();
;
And subobject with add data
$formMapper
->with('Способы связи', ['class' => 'col-md-4'])
->add('phones', 'collection',
[
'label' => 'Телефоны',
'type' => new ClubPhonesListType(),
'required' => false,
'allow_add' => true,
'allow_delete' => true,
'attr' => ['class' => 'emails-list'],
'options' => ['label' => ' ', 'required' => false],
],
[
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position',
])
->add('emails', 'collection',
[
'label' => 'Электронная почта',
'type' => new ClubEmailsListType(),
'required' => false,
'allow_add' => true,
'allow_delete' => true,
'attr' => ['class' => 'emails-list'],
'options' => ['label' => ' ', 'required' => false],
],
[
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position',
])
->end()
->with('Геоданные', ['class' => 'col-md-4'])
->add('latitude', 'text', ['label' => 'Широта'])
->add('longitude', 'text', ['label' => 'Долгота'])
->add('polygon', 'text', ['label' => 'Полигон на карте'])
->add('country', 'text', ['label' => 'Город'])
->add('region', 'text', ['label' => 'Регион'])
->add('city', 'text', ['label' => 'Город'])
->add('address', 'text', ['label' => 'Полный адрес'])
->end()
->with('WEB', ['class' => 'col-md-4'])
->add('site', 'text', ['label' => 'Адрес сайта'])
->end()
;
I have the same problem. I found this :
https://sonata-project.org/bundles/admin/master/doc/reference/action_create_edit.html#formgroup-options
Section 8.2 :
To do:
how to embed one Admin in another (1:1, 1:M, M:M)
So, I think for the moment there are no solution ? :/

Complex query in Symfony2 form using query builder

I'm trying to build some kind of complex query using Doctrine Query Builder to use them in a Form Type, see below what I have done:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('category', 'entity', array(
'class' => 'CategoryBundle:Category',
'property' => 'name',
'required' => false,
'multiple' => true,
'expanded' => false,
'query_builder' => function(EntityRepository $er) {
$qb = $er->createQueryBuilder('c')
->where($qb->expr()->eq('c.parent', '?1'), $qb->expr()->isNull('c.parent'))
->setParameter(1, 0);
}
))
->add('detail_group', 'entity', array('class' => 'ProductBundle:DetailGroup', 'property' => 'name', 'required' => false, 'multiple' => true, 'expanded' => false))
->add('parent', 'entity', array('class' => 'ProductBundle:ProductDetail', 'property' => 'label', 'required' => false))
->add('label')
->add('field_type', 'choice', ['choices' => \ProductBundle\DBAL\Types\FieldType::getChoices()])
->add('values_text', 'collection', array('type' => 'text', 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false))
->add('description', 'text', array('required' => false))
->add('measure_unit', 'text', array('required' => false))
->add('status', 'choice', ['choices' => \ProductBundle\DBAL\Types\StatusType::getChoices()])
->add('to_product', 'checkbox', array('label' => 'Detalle de Stock?', 'required' => false));
}
I need to get in that query all the rows from category table with parent=NULL or parent=0 but it's not working since I get this error:
FatalErrorException: Error: Call to a member function expr() on a
non-object in
/var/www/html/src/ProductBundle/Form/ProductDetailType.php line
22
What I'm doing wrong?
It's because $qb doesn't exists.
$qb = $er->createQueryBuilder('c');
$qb->where($qb->expr()->eq('c.parent', '?1'), $qb->expr()->isNull('c.parent'))
->setParameter(1, 0);

Resources