Search code examples
phpsymfonysymfony-formssymfony-3.2

Symfony - Multiple Fields for one Entity Attribute


I have three three select fields for one entity attribute. As the picture below shows. enter image description here

Is there a way to detect which of the select fields is used; then get its value and map it with the corresponding attribute?

And is it possible to send parameters to a form type (in this example TestType , please see below). I am trying to make it generic and re-usable for other attributes.

Here is what I have up to now.

MyForm.php

<?php

namespace MyBundle\Form;

use MyBundle\Form\Type\TestType;
use ..etc

class MyForm extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('title',      TextType::class)
            ->add('D1',         TestType::class);

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\Entity\Project'
        ));
    }


    public function getBlockPrefix()
    {
        return 'mybundle_project';
    }


}

TestType.php

<?php

namespace MyBundle\Form\Type;

use Sonata\AdminBundle\Form\Type\Filter\ChoiceType;
use ..etc

class TestType extends AbstractType
{
    /*
     * private $myArray1;
     * private $myArray2;
     * private $myArray3; numberOfSeletcs
     * private $numberOfSeletcs;        
    Secondary Question: Is it possible to send these values as parameters?

    public function __construct($array1, $array2, $array3, $n)
    {
        $this->myArray1= $array1;
        $this->myArray2= $array2;
        $this->myArray3= $array3;
        $this->numberOfSeletcs= $n;

    }


    */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $myArray1 = array('label1'=>'','Value1'=>'Value1', 'Value2'=>'Value2','Value3'=>'Value3');
        $myArray2 = array('label2'=>'', 'Value4'=>'Value4','Value5'=>'Value5');
        $myArray3 = array('label3'=>'', 'Value6'=>'Value6','Value6'=>'Value6');

        $builder
            // ...
            ->add('H1', 'choice',  array(
                'choices' => $myArray1,
                'choice_attr' => ['label1' => ['disabled selected hidden'=>'']]))
            ->add('H2', 'choice',  array(
                'choices' => $myArray2,
                'choice_attr' => ['label2' => ['disabled selected hidden'=>'']]))
            ->add('H3', 'choice',  array(
                'choices' => $myArray3,
                'choice_attr' => ['label3' => ['disabled selected hidden'=>'']]));
    }


}

Thanks.


Solution

  • To detect which of the select fields is used you have to use Javascript. As you know Symfony is a PHP framework working on the server-side and to detect event on client-side javascript is needed. And for pass parameter to your form type you have the answer in this topic