V
V
v7sila2018-08-07 12:39:18
symfony
v7sila, 2018-08-07 12:39:18

Validating part of a Symfony object?

There is an entity User. This entity has methods that are validated by annotations.
Essence

/**
 * @ORM\Table(name="app_users")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @UniqueEntity(
 * 		"username",
 * 		message="Логин уже используется"
 * )
 * @UniqueEntity(
 * 		"email",
 * 		message="Email уже используется"
 * )
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
   * @Assert\NotBlank(
   *     message="Логин не должен быть пустым"
   * )
   * @Assert\Length(
   *      min = 3,
   *      max = 50,
   *      minMessage = "Логин должен содержать не меньше {{ limit }} символов",
   *      maxMessage = "Логин должен содержать не меньше {{ limit }} символов"
   * )
   * @Assert\Regex(
   * 		pattern="/^[A-Za-z0-9_-]+$/",
   *     	message="Логин может состоять только из латинских из букв, цифр, дефисов и подчёркиваний. Длина от 3 до 16 символов."
   * )
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $plainPassword;

    /**
     * @ORM\Column(type="string", length=64)
   * @Assert\Length(
   *      min = 6,
   *      max = 64,
   *      minMessage = "Пароль должен содержать не меньше {{ limit }} символов",
   *      maxMessage = "Пароль должен содержать не меньше {{ limit }} символов"
   * )
   * * @Assert\NotBlank(
   *     message="Пароль не должен быть пустым"
   * )
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=60, unique=true)
     * @Assert\NotBlank(
     *     message="Email не должен быть пустым"
     * )
     * @Assert\Length(
     *      min = 6,
     *      max = 50,
     *      minMessage = "Email должен содержать не меньше {{ limit }} символов",
     *      maxMessage = "Email должен содержать не меньше {{ limit }} символов"
     * )
     * @Assert\Email(
     *     message = "Email {{ value }} имеет не верный формат.",
     *     checkMX = true
     * )
     */
    private $email;

Only $password is used in the form.
$builder
      ->add('password', RepeatedType::class, array(
        'type' => PasswordType::class,
        'invalid_message' => 'Поля паролей должны совпадать.',
        'options' => array('attr' => array('class' => 'password-field')),
        'required' => true,
        'first_options'  => array('label' => 'Новый пароль'),
        'second_options' => array('label' => 'Повторение нового пароля'),
      ))
      ->add('save', SubmitType::class)
      ->add( 'new_password_hidden' ,  HiddenType :: class, [
        'mapped' => false,
      ])
    ;

// Entity class
$user = new \AppBundle\Entity\User();
// Building the form
$form = $this->createForm(NewPassword::class, $user);
The validator returns false because only the password is valid in the object.
var_dump($form->isValid());
Result bool(false);
!!!How can I use the User class in a form so that $form->isValid() returns true?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artemy Lapko, 2018-08-07
@v7sila

Do not shove essence into the form. Google about dto. And you don't need to validate the entity. You need to validate the request! The base will take care of the rest...

V
v7sila, 2018-08-07
@v7sila

Really. You shouldn't use an entity for validation. An entity must always be valid.
Used a separate class for password validation.

namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;

class Password
{
    /**
   *
   * @Assert\Length(
   *      min = 6,
   *      max = 64,
   *      minMessage = "Пароль должен содержать не меньше {{ limit }} символов",
   *      maxMessage = "Пароль должен содержать не меньше {{ limit }} символов"
   * )
   * * @Assert\NotBlank(
   *     message="Пароль не должен быть пустым"
   * )
     * @var string
     */
    private $password;


    /**
     * Set password
     *
     * @param string $password
     *
     * @return Password
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }
}

In the controller
public function newPasswordAction(Request $request){
    $password = new Password();
    $form = $this->createForm(NewPassword::class, $password);
    /........./
  }

Form class
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

class NewPassword extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
      ->add('password', RepeatedType::class, array(
        'type' => PasswordType::class,
        'invalid_message' => 'Поля паролей должны совпадать.',
        'options' => array('attr' => array('class' => 'password-field')),
        'required' => true,
        'first_options'  => array('label' => 'Новый пароль'),
        'second_options' => array('label' => 'Повторение нового пароля'),
      ))
      ->add('save', SubmitType::class)
      ->add( 'new_password_hidden' ,  HiddenType :: class, [
        'mapped' => false,
      ])
    ;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question