简体   繁体   中英

ChoiceType Not Mapping to Entity Field

I have an Announcement Entity that where a EditAnnouncementType form is mapped to. I have two other CheckBoxType forms that automatically update their respective fields, but the ChoiceType form isn't working.

$builder
        ->add('edit', SubmitType::class,
            array
            (
                'label' => 'Save changes',
                'attr' => ['class' => 'btn btn-primary']

            ))

        ->add('type', ChoiceType::class,
            [
                'choices' => [
                    'info_type' => 1,
                    'star_type' => 2,
                    'alert_type' => 3,
                    'lightbulb_type' => 3,
                    'event_type' => 4,
                    'statement_type' => 5,
                    'cat_type' => 6,
                    'hands_type' => 7
                ],

                'mapped' => true,
                'expanded' => true,
                'required' => true,
            ])

The Announcement entity and type field

class Announcement
{
    /**
     * @var int
     */
     private $type;

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

    /**
    * @param int $type
    *
    * @return $this
    */
    public function setType(int $type)
    {
        $this->type = $type;
        return $this;
    }

My suspicion would be that Symfony somehow strict checks the value (using === ).
And since your getter returns a string , the mapping doesn't happen properly.

You should try fixing your getter:

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

Also mind that you might have a problem in your choice array:

// be careful: those two have the same value
'alert_type' => 3, 
'lightbulb_type' => 3,

This would surely cause an issue to Symfony, especially if it uses array_values in order to select the right choice out of the value of your entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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