d1596
d1596

Reputation: 1307

Symfony ChoiceType form map choices to a related entity field

Not sure if it is possible, but I want to map the two choices of my ChoiceType form two one different Announcement field each.

Here is the ChoiceType in a EditAnnouncementType I made

->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
            ])

Here are the two fields I want the form to automatically update for the existing Announcement entity.

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;
    }
}

I have this working with two separate CheckBoxType forms instead, however I need to require the user to select at least one of the options, which isn't possible (to my knowledge) as two separate forms.

Upvotes: 1

Views: 1074

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39129

Not sure if I properly understand what you are asking so let me rephrase it.
You would want your audience field to set employees to false and students to true in one case, and employees to true and students to false in the other case?

If I am correct then here is a possible way to go:

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;
    }
}

Your EditAnnouncementType class should already handle this correctly.
But can be further improved by the usage of class constants

->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,
    ]
)

Upvotes: 1

Related Questions