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

Monday, January 31, 2022

[FIXED] Entity (with constraints) + createFormBuilder (with extra fields) fail

 January 31, 2022     constraints, entity, forms, symfony     No comments   

Issue

My User entity has few properties:

private $id;
/**
Assert\Email
*/
private $email;
/**
 * @Assert\Length( min=6, minMessage="Password is too short (min 6 symbols)" )
 */
private $password;

I'm trying to create a Form for changing password:

createFormBuilder(null, ??? data-class=UserEntity ??? )
->add('YES_CHANGE_PASS',CheckboxType::class,['required'=>false])
->add('old_password',PasswordType::class,['required'=>false])
->add('new_password', RepeatedType::class,['required'=>false])

Problem: if I set the 'data-class=UserEntity::class' to this Form, it stops working (of course, because my Entity doesn't have OLD_PASSWORD\NEW_PASSWORD property). If I don't set 'data-class', the Form obviously won't inherit any constraints (like password @Assert\Length(min=6) constraint)

Solution#1 I dont like: hardcode all the needed constraints right in the createFormBuilder function. I dont like this way because if one day I want to change the Password minLength, I'll have to run through the whole project searching for such forms to edit this

Solution#2 madness: add all the extra fields to my Entity, so it will let me use the 'data-class:UserEntity'... and constraints...and validate... but it's obviously a sick solution

Any hints, please?


Solution

Change your form to this :

$form=$this->createFormBuilder()
     ->add('YES_CHANGE_PASS', CheckboxType::class, array(
         'mapped'=>false,
         'required'=>false,
     ))
     ->add('old_password', PasswordType::class, array(
         'mapped'=>false,
         'required'=>false,
     ))
     ->add('new_password', RepeatedType::class, array(
         'mapped'=>false,
         'required'=>false,
     ));

Then, when the form is submitted :

if($form->get('YES_CHANGE_PASS')->getData()) { // <== Used asked to change password?
    if($passwordEncoder->isPasswordValid($this->getUser(), $form->get('YES_CHANGE_PASS')->getData())) { // <== Check if old password is valid
        $form->get('new_password')->getData(); // <== Do what you need with the new password.
    }
}


Answered By - Preciel
  • 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