Sunday 15 June 2014

How to remove the null value field from form in symfony form handler -


I want to update the data in two situations:

  1. Enters
  2. When the user does not enter the password (I only need to update the name and email).

    I have the following formhandler method.

      Public function process (user interface $ user) {$ this- & gt; Form- & gt; Set data ($ user); If ('post' === $ this-> request-> getMethod ()) receive {$ password = trim ($ this- & request-> ('fos_user_profile_form') [' password']); // is checked where the password is empty // But when I remove the password field, it does not update anything if (empty ($ password)) {$ this- & gt; Form- & gt; Remove ('password'); } $ This- & gt; Form- & gt; Tie ($ - this-> request); If ($ this-> form-> isValid ()) {$ this- & gt; OnSuccess ($ user); Back true; } // Reloads the user to reset your username. // To avoid problems with the security level, when the username or password has been changed, then it needs $ $-> UserManager- & gt; ReloadUser ($ user); }    

    An easy solution to your problem is to disable the mapping of the password field. Manually copy it, unless it is empty. Sample code: $ form = $ this- & gt; CreateFormBuilder () - & gt; Junk ('name', 'text') - & gt; Add ('email', 'repeat', array ('type' = & gt; 'email')) - & gt; Add ('password', 'duplicated', array ('type' = & gt; 'password', 'map' = & gt; wrong)). - & gt; GetForm (); // Symfony 2.3+ $ form- & gt; HandleRequest ($ request); // symphony & lt; 2.3 ('POST' === $ request- & gt; getMethod ()) {$ form-> Tie ($ request); } // All editions if ($ form-> isValid ()) {$ user = $ form-> GetData (); If (blank! == $ form-> get ('password') - & gt; getData ()) {$ user- & gt; Set password (get $ form- & gt; ('password') - & gt; getData ()); } // continue the user}

    If you prefer to clean your controllers, then you can also add this argument to your form type:

     < Code> $ builder- & gt; AddEventListener (FormEvents :: POST_SUBMIT, function (FormInterface $ form) {$ form = $ event-> getForm (); $ user = $ form-> getData (); if (empty! == $ form-> ('Password') - & gt; getData ()) {$ user- & gt; Set passwords (get $ form-> ('password') - & gt; getData ());}}) ;    

No comments:

Post a Comment