Symfony ChoiceType将地图选择形式映射到相关的实体字段

问题描述 投票:1回答:1

不确定是否可能,但我想将我的ChoiceType的两个选项映射到两个不同的Announcement字段。

这是我制作的EditAnnouncementType中的ChoiceType

->add('audience', ChoiceType::class,
        [
            'choices' =>
            [
                'Students: anybody with a student level field populated' => 'students',
                'Employees: anybody with an employee ID number' => 'employees'
            ],
                'expanded' => true,
                'required' => true,
                'multiple' => true
            ])

以下是我希望表单自动更新现有Announcement实体的两个字段。

class Announcement
{
    /**
     * @param bool $employees
     *
     * @return $this
     */
    public function setEmployees(bool $employees)
    {
        $this->employees = $employees;
        return $this;
    }

    /**
     * @param bool $students
     *
     * @return $this
     */
    public function setStudents(bool $students)
    {
        $this->students = $students;
        return $this;
    }
}

我使用两个单独的CheckBoxType表单,但是我需要用户选择至少一个选项,这是不可能的(据我所知)作为两个单独的表单。

php symfony symfony-forms
1个回答
1
投票

不确定我是否正确理解你的要求所以让我改一下。 你希望你的audience字段在一种情况下将employees设置为falsestudents设置为true,而在另一种情况下将employees设置为truestudents设置为false

如果我是正确的,那么这是一个可能的方法:

class Announcement
{
    public const AUDIENCE_EMPLOYEES = 'employees';
    public const AUDIENCE_STUDENTS = 'students';

    public function getAudience(): array
    {
        $audience = [];

        if($this->employees()) { 
            $audience[] = self::AUDIENCE_EMPLOYEES;
        }
        if($this->employees()) { 
            $audience[] = self::AUDIENCE_STUDENTS;
        }

        return $audience;
    }

    public function setAudience(array $audience): Announcement
    {
        $this->employees = in_array(self::AUDIENCE_EMPLOYEES, $audience);
        $this->students = in_array(self::AUDIENCE_STUDENTS, $audience);

        return $this;
    }
}

你的EditAnnouncementType类应该已经正确处理了这个问题。 但是可以通过使用类常量来进一步改进

->add('audience', ChoiceType::class,
    [
        'choices' =>
        [
            'Students: anybody with a student level field populated' => Announcement::AUDIENCE_STUDENTS,
            'Employees: anybody with an employee ID number' => Announcement::AUDIENCE_EMPLOYEES,
        ],
        'expanded' => true,
        'required' => true,
        'multiple' => true,
    ]
)
© www.soinside.com 2019 - 2024. All rights reserved.