【问题标题】:Symfony - Multiple Fields for one Entity AttributeSymfony - 一个实体属性的多个字段
【发布时间】:2017-08-20 12:49:01
【问题描述】:

我有一个实体属性的三个三个选择字段。如下图所示。

有没有办法检测使用了哪些选择字段;然后获取它的值并映射到对应的属性?

是否可以将参数发送到表单类型(在此示例中为 TestType ,请参见下文)。我正在尝试使其通用且可重用于其他属性。

这是我目前所拥有的。

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'=>'']]));
    }


}

谢谢。

【问题讨论】:

    标签: php symfony symfony-forms symfony-3.2


    【解决方案1】:

    要检测使用了哪些选择字段,您必须使用 Javascript。如您所知,Symfony 是一个在服务器端工作的 PHP 框架,需要检测客户端 javascript 上的事件。对于将参数传递给您的表单类型,您可以在 topic

    中找到答案

    【讨论】:

    • 谢谢,您回答的第二部分帮助找到了解决方案。这对我有用:stackoverflow.com/questions/44390433/… 我现在将开始处理您的第一个建议。
    • 这就是我得到的结果:stackoverflow.com/questions/45787862/… 我设法通过实现一个 jquery 脚本来检测使用了哪些选择字段,该脚本将更改选择的兄弟姐妹返回为 null(标签值)。然后,找出哪个不为空。但是,我在数据转换器中发现了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    相关资源
    最近更新 更多