简体   繁体   English

具有formType的Symfony枚举类型

[英]Symfony Enum Type with formType

I have a symfony entity that have an enum type field and I want to generate a form type for it. 我有一个具有枚举类型字段的symfony实体,我想为其生成一个表单类型。 I want to know the right way to do that. 我想知道正确的方法。

this is my entity : 这是我的实体:

<?php

namespace EvalBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * SessionEvaluation
 *
 * @ORM\Table(name="session_evaluation")
 * @ORM\Entity(repositoryClass="EvalBundle\Repository\SessionEvaluationRepository")
 */
class SessionEvaluation
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=true)
     */
    private $name;

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

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

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", columnDefinition="enum('annual', 'intermediate')")
     */
    private $type;

    /**
     * One SessionEvaluation has Many PerformanceEvaluation.
     * @ORM\OneToMany(targetEntity="PerformanceEvaluation", mappedBy="sessionEvaluation")
     */
    private $performanceEvaluations;

    /**
     * One SessionEvaluation has Many Evaluation.
     * @ORM\OneToMany(targetEntity="Evaluation", mappedBy="sessionEvaluation")
     */
    private $evaluations;

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

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

        return $this;
    }

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

    /**
     * Set startDate
     *
     * @param \DateTime $startDate
     *
     * @return SessionEvaluation
     */
    public function setStartDate($startDate)
    {
        $this->startDate = $startDate;

        return $this;
    }

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

    /**
     * Set endDate
     *
     * @param \DateTime $endDate
     *
     * @return SessionEvaluation
     */
    public function setEndDate($endDate)
    {
        $this->endDate = $endDate;

        return $this;
    }

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

    /**
     * Set type
     *
     * @param string $type
     *
     * @return SessionEvaluation
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

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

    public function __toString() {
        return $this->name;
    }
}

and here is the formType : 这是formType:

<?php

namespace EvalBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SessionEvaluationType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('Name', TextType::class, array(
            'attr'=> array('class'=>'form-control')
        ))
                ->add('startDate', DateType::class, array(
                    'format' => 'yyyy MM dd'
                ))
                ->add('endDate')
                ->add('type', ChoiceType::class, array(
                    'choices' => array(
                        'Annuel' => true,
                        'Itérmidaire' => false,
                    ),
                    'attr' => array('class' => 'dropdown')

                ))
            ->add('Lancer', SubmitType::class, array(
                'attr' => array('class' => 'btn btn-primary')));

    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'EvalBundle\Entity\SessionEvaluation'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'evalbundle_sessionevaluation';
    }


}

the field with enum type is : type 枚举类型的字段是:type

I've defined it as choiceType in the form, is this a good way to do it for save the entity instance in the database after submit the form ? 我已经在表单中将其定义为choiceType,这是提交表单后在数据库中保存实体实例的一种好方法吗?

Enum type can be set like you did with annotation in your entity. 可以像在实体中使用注释一样设置枚举类型。 However you have to secure what string is pass in the function setType for be sure it's part of your enum. 但是,您必须确保在函数setType中传递了什么字符串,以确保它是枚举的一部分。

You should do this 你应该做这个

public function setType($type)
{
    if (!in_array($type, array('annual', 'intermediate'))) {
        throw new \InvalidArgumentException("Invalid type");
    }
    $this->type = $type;
}

Then in your form, you will be sure that the value to save in database passed by your ChoiceType is like your enum. 然后,在您的表单中,您将确保ChoiceType传递的要保存在数据库中的值就像您的枚举一样。 By the way you can choose any type who return string but ChoiceType is the best in this case because your user can select string you have chosen. 顺便说一下,您可以选择返回字符串的任何类型,但是在这种情况下,ChoiceType是最好的,因为您的用户可以选择您选择的字符串。 But for be sure he doesn't pass other value it's a good practice to secure the setter on server side like above. 但是请确保他不会传递其他值,这是一个很好的做法,可以像上面那样在服务器端保护设置器。

Otherwise you can still use an another solution who consist in create a specific type for your Enum who can be found here or here but the first solution is fine. 否则,您仍然可以使用另一个解决方案,该解决方案包括为您的Enum创建一个特定类型,该类型可以在此处此处找到但第一个解决方案很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM