使用基础实体中定义的常量数组填充Symfony表单choiceType的最佳方法是什么,并根据相同的常量添加创建断言。 选项名称应存储在DB中。
我正在使用Symfony 2.8,这就是我所做的。它运作良好,但我认为必须有一个更简单的方法来使用所有新的表单功能。
谢谢,Hannes
实体
class User implements UserInterface, \Serializable
{
const OCCUPATION_SCHOOL_HIGHER_DEGREE = 'Schülerin/Schüler an Gymnasium';
const OCCUPATION_SCHOOL_LOWER_DEGREE = 'Schülerin/Schüler an Haupt-/Real- und anderen Schulen';
const OCCUPATION_WORK_TRAINING = 'Berufsausbildung';
const OCCUPATION_UNIVERSITY = 'Studium an einer Hochschule';
const OCCUPATION_WORK_FULLTIME = 'Vollzeiterwerbstätigkeit';
const OCCUPATION_WORK_PARTTIME = 'Teilzeiterwerbstätigkeit';
const OCCUPATION_NATIONAL_SERVICE = 'Wehrdienst/Zivildienst/FSJ/FÖJ';
const OCCUPATION_UNEMPLOYED = 'keine Beschäftigung';
const OCCUPATION_OTHERS = 'sonstiges';
...
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Assert\NotBlank(message = "Pflichtfeld.")
* @Assert\Choice(
* choices = {
* User::OCCUPATION_SCHOOL_HIGHER_DEGREE,
* User::OCCUPATION_SCHOOL_LOWER_DEGREE,
* User::OCCUPATION_WORK_TRAINING,
* User::OCCUPATION_UNIVERSITY,
* User::OCCUPATION_WORK_FULLTIME,
* User::OCCUPATION_WORK_PARTTIME,
* User::OCCUPATION_NATIONAL_SERVICE,
* User::OCCUPATION_UNEMPLOYED,
* User::OCCUPATION_OTHERS,
* },
* message = "Bitte wähle einen Eintrag aus der Liste."
* )
*/
private $occupation;
...
}
FormType
class UserRegisterType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Occupation
$builder->add('occupation', ChoiceType::class, array(
'label' => 'Beschäftigung*',
'placeholder' => 'Bitte wählen',
'choices' => array(
User::OCCUPATION_SCHOOL_HIGHER_DEGREE => User::OCCUPATION_SCHOOL_HIGHER_DEGREE,
User::OCCUPATION_SCHOOL_LOWER_DEGREE => User::OCCUPATION_SCHOOL_LOWER_DEGREE,
User::OCCUPATION_WORK_TRAINING => User::OCCUPATION_WORK_TRAINING,
User::OCCUPATION_UNIVERSITY => User::OCCUPATION_UNIVERSITY,
User::OCCUPATION_WORK_FULLTIME => User::OCCUPATION_WORK_FULLTIME,
User::OCCUPATION_WORK_PARTTIME => User::OCCUPATION_WORK_PARTTIME,
User::OCCUPATION_NATIONAL_SERVICE => User::OCCUPATION_NATIONAL_SERVICE,
User::OCCUPATION_UNEMPLOYED => User::OCCUPATION_UNEMPLOYED,
User::OCCUPATION_OTHERS => User::OCCUPATION_OTHERS,
),
'choices_as_values' => true,
)
);
... }
答案 0 :(得分:2)
不确定,如果这回答了你的问题,但是自从PHP 5.6(我希望这是正确的版本)你可以创建constancs作为数组:
const OCCUPATION = [
User::OCCUPATION_SCHOOL_HIGHER_DEGREE,
User::OCCUPATION_SCHOOL_LOWER_DEGREE,
....
];
或
const OCCUPATION = [ OCCUPATION_SCHOOL_HIGHER_DEGREE => 'Schülerin/Schüler an Gymnasium', OCCUPATION_WORK_TRAINING => 'Berufsausbildung', .... ];
现在你可以直接以你的形式访问:
'choices' => User::OCCUPATION
或者你可以写一个getter $ user-> getOccupation();
答案 1 :(得分:1)
几个月前我发现了这个bundle,我觉得它可以满足你的需要。
您可以在config.yml
中存储可能的值(您可以使用类常量)。然后,您可以使用专用表单类型来检索您的选择,并在您的实体中添加验证约束。