doulei8861 2016-09-22 21:10
浏览 47
已采纳

从实体方法将选项加载到表单选择字段中

I have symfony form with choice field. I want to load choices from my entity class static method. can i use data or CallbackChoiceLoader? what is the best practise?

this is my field:

        class CarType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('type', ChoiceType::class, [
            // This choices I would like to load from:
            // 'choices' => $car::getTypes(),
            'choices'       => [
                'Critical'  => 'critical',
                'Medium'    => 'medium',
                'Info'      => 'info',
            ],
            'label'         => 'Type'
        ])
        ->add('name', TextType::class, [
            'label' => 'Name'
        ])
        ->add('save', SubmitType::class, [
            'label' => 'Save'
        ])
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => 'AppBundle\Entity\Car'
    ]);
}

public function getName()
{
    return 'car';
}
}

This is my entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="car")
 */
class Car
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var string $type
 *
 * @Assert\NotBlank()
 * @ORM\Column(name="type")
 */
private $type;

/**
 * @var string $name
 *
 * @Assert\NotBlank()
 * @ORM\Column(name="name")
 */
private $name;

/**
 * @var \DateTime $created
 *
 * @ORM\Column(name="created", type="datetime")
 */
private $created;

private static $types = ['main', 'custom'];

public function __construct()
{
    $this->created = new \DateTime('now', new \DateTimeZone('Europe/Ljubljana'));
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Get types
 * 
 * @return array
 */
public function getTypes()
{
    return self::$types;
}

/**
 * Set type
 *
 * @param string $type
 *
 * @return Car
 */
public function setType($type)
{
    if (in_array($type, $this->getTypes())) {
        $this->type = $type;
    }

    return $this;
}

/**
 * Get type
 *
 * @return string
 */
public function getType()
{
    return $this->type;
}

/**
 * Set name
 *
 * @param string $name
 *
 * @return Car
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string
 */
public function getName()
{
    return $this->name;
}

/**
 * Set created
 *
 * @param \DateTime $created
 *
 * @return Car
 */
public function setCreated($created)
{
    $this->created = $created;

    return $this;
}

/**
 * Get created
 *
 * @return \DateTime
 */
public function getCreated()
{
    return $this->created;
}

How and what can i use to load choices from $car::getTypes() method like i commented in form so that the choices are loaded dynamicly based on values in getTypes entity method?

  • 写回答

1条回答 默认 最新

  • douya8978 2016-09-22 21:55
    关注

    Edit: This is option 1. Option 2 below more directly answers the question.

    The preferred method of creating a choice form field from an entity is to use the EntityType field. Here is an example from an application that requires an ethnicity field. Below that is the Ethnicity entity.

    form field:

    ->add('ethnicity', EntityType::class, array(
        'label' => 'Ethnicity:',
        'class' => 'AppBundle:Ethnicity',
        'choice_label' => 'abbreviation',
        'expanded' => false,
        'placeholder' => 'Select ethnicity',
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('e')
                    ->orderBy('e.abbreviation', 'ASC')
            ;
        },
    ))
    

    Ethnicity entity:

    /**
     * Ethnicity.
     *
     * @ORM\Table(name="ethnicity")
     * @ORM\Entity
     */
    class Ethnicity
    {
        /**
         * @var int
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="IDENTITY")
         */
        protected $id;
    
        /**
         * @var string
         *
         * @ORM\Column(name="ethnicity", type="string", length=45, nullable=true)
         */
        protected $ethnicity;
    
        /**
         * @var string
         *
         * @ORM\Column(name="abbr", type="string", length=45, nullable=true)
         */
        protected $abbreviation;
    
        /**
         * @var \Doctrine\Common\Collections\Collection
         *
         * @ORM\OneToMany(targetEntity="AppBundle\Entity\Member", mappedBy="ethnicity", cascade={"persist"})
         */
        protected $members;
    
        /**
         * Constructor.
         */
        public function __construct()
        {
            $this->members = new \Doctrine\Common\Collections\ArrayCollection();
        }
    
        /**
         * Get id.
         *
         * @return int
         */
        public function getId()
        {
            return $this->id;
        }
    
        /**
         * Set ethnicity.
         *
         * @param string $ethnicity
         *
         * @return Ethnicity
         */
        public function setEthnicity($ethnicity)
        {
            $this->ethnicity = $ethnicity;
    
            return $this;
        }
    
        /**
         * Get ethnicity.
         *
         * @return string
         */
        public function getEthnicity()
        {
            return $this->ethnicity;
        }
    
        /**
         * Set abbreviation.
         *
         * @param string $abbreviation
         *
         * @return Ethnicity
         */
        public function setAbbreviation($abbreviation)
        {
            $this->abbreviation = $abbreviation;
    
            return $this;
        }
    
        /**
         * Get abbreviation.
         *
         * @return string
         */
        public function getAbbreviation()
        {
            return $this->abbreviation;
        }
    
        /**
         * Add members.
         *
         * @param \AppBundle\Entity\Member $members
         *
         * @return Ethnicity
         */
        public function addMember(\AppBundle\Entity\Member $members)
        {
            $this->members[] = $members;
    
            return $this;
        }
    
        /**
         * Remove members.
         *
         * @param \AppBundle\Entity\Member $members
         */
        public function removeMember(\Truckee\ProjectmanaBundle\Entity\Member $members)
        {
            $this->members->removeElement($members);
        }
    
        /**
         * Get members.
         *
         * @return \Doctrine\Common\Collections\Collection
         */
        public function getMembers()
        {
            return $this->members;
        }
    
        /**
         * @var bool
         *
         * @ORM\Column(name="enabled", type="boolean", nullable=true)
         */
        protected $enabled;
    
        /**
         * Set enabled.
         *
         * @param bool $enabled
         *
         * @return enabled
         */
        public function setEnabled($enabled)
        {
            $this->enabled = $enabled;
    
            return $this;
        }
    
        /**
         * Get enabled.
         *
         * @return bool
         */
        public function getEnabled()
        {
            return $this->enabled;
        }
    }
    

    Option 2: If you really want to do that, then here's an approach:

    1. Modify your static property $types such that the choices are values in an array, e.g., $types = array(1 => 'main', 2 => 'custom')
    2. In your controller, add a use statement for the Car entity.
    3. In controller action:

      $car = new Car();

      $types = $car->getTypes;

    4. Use the answer to Passing data to buildForm() in Symfony 2.8/3.0 to see how to pass $types to your form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器