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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?