B
B
BonBon Slick2018-08-09 16:30:50
symfony
BonBon Slick, 2018-08-09 16:30:50

Validate as NumberType but give choice via ChoiceType?

It was

->add(
            'rating', // TODo - should be select with options from 1 to 5
            NumberType::class,
            [
                'attr' => [
                    'placeholder' => 'Rating',
                ],
            ]
        )

I would like to
->add(
            'rating',
            ChoiceType::class,
            [
                'choice_label' => 'Rating',
                'choices' => array(
                    'One' => 1,
                    'Two' => 2,
                    'Three' => 3,
                    'Four' => 4,
                    'Five' => 5,
                ),
            ]
        )

However, if it's an array, it throws an error
PropertyAccessor requires a graph of objects or arrays to operate on, but it found type "integer" while trying to traverse path "Rating" at property "Rating".

Because the accessor method returns numbers in essence
...
        $this->rating     = 0.0;
...

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

    /**
     * @param int $rating
     */
    public function changeRating(int $rating) : void
    {
        $this->rating = $rating;
    }

How to render a form with a select, but validate the value as a number when submitting the form?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question