PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 10, 2022

[FIXED] Why assertion skips to validate my symfony5 form username field?

 January 10, 2022     forms, php, symfony, symfony5, validation     No comments   

Issue

my problem concerns one field from User form, namely Username. Since assertion validation works for other fields in the entity I find it odd to behave like this - skipping the Assertion rule I did point for username attribute in User entity and passing null attribute to userFormNewHandler which is generating an error, especially when I find it not really different than other fields. I wonder, what am I missing?

UserType.php:

<?php
namespace App\UserBundle\Form\Type;

use App\UserBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class, ['required'=>true,
                'invalid_message' => 'Username must not be empty!'])
            ->add('plainPassword', RepeatedType::class, array(
                'type'              => PasswordType::class,
                'mapped'            => false,
                'first_options'     => array('label' => 'New password'),
                'second_options'    => array('label' => 'Confirm new password'),
                'invalid_message' => 'The password fields must match.',
                'required' => true,
                'constraints' => [
                    new NotBlank([
                        'message' => 'Password field must not be blank!'
                    ])]
            ))

            ->add('active_status', ChoiceType::class, [
                'choices'  => [
                    'Active' => true,
                    'Inactive' => false,
                ],])
            ->add('first_name',TextType::class, [
                'required'=>true, 'invalid_message' => 'First name must not be empty!'])
            ->add('last_name', TextType::class, [
                'required'=>true, 'invalid_message' => 'Last name must not be empty!'])
            ->add('email', EmailType::class, [
                'required'=>true, 'invalid_message' => 'Email must not be empty!']);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

And this is my User.php entity:

<?php

namespace App\UserBundle\Entity;

use App\UserBundle\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;


/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @Assert\NotBlank(message="Fill username field")
     */
    private $username;

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @ORM\Column(type="boolean")
     */
    private $active_status;

    /**
     * @ORM\Column(type="string", length=30)
     * @Assert\NotBlank(message="Fill first name field")
     */
    private $first_name;

    /**
     * @ORM\Column(type="string", length=30)
     * @Assert\NotBlank(message="Fill last name field")
     */
    private $last_name;

    /**
     * @ORM\Column(type="string", length=40)
     * @Assert\NotBlank(message="Fill email field")
     */
    private $email;

    /**
     * Representation of account status
     */
    public function getActiveStatus(): bool
    {
        return $this->active_status;
    }

    /**
     * Setting account status
     */
    public function setActiveStatus(bool $active_status): self
    {
        $this->active_status = $active_status;

        return $this;
    }
        /**
 * Representation of username
 */
public function getUsername(): string
{
    return (string) $this->username;
}

/**
 * Setting username for user
 */
public function setUsername(string $username): self
{
    $this->username = $username;

    return $this;
}

    //...

and also _form.html.twig, where form is being rendered:

{{ form_start(form, { attr: {novalidate: 'novalidate'} }) }}
    {{ form_widget(form) }}
    <button class="btn" >{{ button_label|default('Save') }}</button>
{{ form_end(form) }}

Solution

I found it! That was because I did point out in setter Username's method to look strictly for string and I guess that prevented me from passing null attribute to the form. Now PHP validation works correctly :)

Part generating error:

User.php

/**
 * Setting username for user
 */
public function setUsername(string $username): self
{
    $this->username = $username;

    return $this;
}

Fix:

/**
 * Setting username for user
 */
public function setUsername($username): self
{
    $this->username = $username;

    return $this;
}


Answered By - Szymon D.
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing