Reputation: 761
I'm working on my Symfony 2 project and I'm doing the twig of one of my form. I want to know how to check if the select in my form as at least one option.
My form looks like this:
<?php
namespace AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
Class ProjetsType extends AbstractType
{
public function buildForm(FormBuilderInterface $constructeur, array $options)
{
$constructeur
->add('Ajouter', 'submit', array('label'=>'Ajouter un projet'))
->add('Projet', 'entity', array(
'label'=>false,
'class'=>'PublicBundle\Entity\Projet',
'property'=>'id'
))
->add('Modifier', 'submit')
->add('Supprimer', 'submit');
/*This is the way I do it if I pass my projects as a parameter*/
/*if(!empty($options['choix']))
{
$constructeur
->add('Projet', 'choice', array('label'=>false, 'choices'=>$options['choix']))
->add('Modifier', 'submit')
->add('Supprimer', 'submit');
}*/
}
public function getName()
{
return 'projets_type';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'choix' => null,
));
}
}
My template looks like this
{{ form_start(formulaire) }}
{{ form_widget(formulaire.Ajouter) }}
{% if formulaire.Projet is defined %}
{{ form_widget(formulaire.Projet) }}
{{ form_widget(formulaire.Modifier) }}
{{ form_widget(formulaire.Supprimer) }}
{% endif %}
{{ form_end(formulaire) }}
My goald is that if there aren't any project, only the 'ajouter' (it's french for add) button will appear. I previously used to pass the list of my projects, that I got with an other function, and my form just added the select if there was at least a project, but I got told that it's better to use a entity type field. Using the entity type field could result in having a select field without any option. If it happen I wish to not show the select and the two following buttons.
So I guess that the best way would be to check if the select contains at least one option and if it doesn't, don't add that part of the form in my template. How do I do that?
Upvotes: 1
Views: 962
Reputation: 7800
Try this :
{% if (formulaire.Projet.vars['choices'] | length > 0) %}
// empyty select
{% else %}
// not empty select
{% endif %}
Check this question : Get options of an entity Field in twig
And the documentation : http://symfony.com/doc/current/reference/forms/twig_reference.html#twig-reference-form-variables
Upvotes: 2