ajax - FOSUserBundle register in AngularJS -


i have spa web application uses angularjs frontend , symfony2 backend.

i used fosuserbundle handling user.

what want right use angularjs method of registering user via ajax

my problem whenever submit form, prints "invalid form" in console log.

here's current progress:

new.html

<form class="form-group text-left" ng-submit="submit()" novalidate name="userfrm">     <div class="form-group">         <label for="user.email" class="required">email</label>         <input id="user.email" name="user.email" class="form-control" type="text" ng-model="user.email" />     </div>     <div class="form-group">         <label for="user.username" class="required">username</label>         <input id="user.username" name="user.username" class="form-control" type="text" ng-model="user.username" />     </div>     <div class="form-group">         <label for="user.plainpassword" class="required">password</label>         <input id="user.plainpassword" name="user.plainpassword" class="form-control" type="password" ng-model="user.plainpassword" />     </div>     <div class="form-group">         <label for="confirmpassword" class="required">confirm password</label>         <input id="confirmpassword" name="confirmpassword" compare-to="user.plainpassword" class="form-control" type="password" ng-model="confirmpassword" />     </div>     <input type="submit" value="register" ng-disabled="userfrm.$invalid"  class="btn btn-primary center-block col-lg-2" /> </form> 

new.js

'use strict';  (function () {     angular.module('myapp.user.new', [])         .config(['$stateprovider', function ($stateprovider) {                 $stateprovider                         .state('user.new', {                             url: "/new",                             controller: "newuserctrl",                             templateurl: path + 'user/new/new.html'                         });             }])          .controller('newuserctrl', ["$scope", "$http", "$state", function ($scope, $http, $state) {                  var success = function (response) {                     var valid = response.data.valid;                     if (valid) {                         $state.go('home');                     } else {                         console.log("invalid form");                     }                 };                  var error = function (reason) {                     console.log("submission failed");                 };                  $scope.submit = function () {                     var formdata = {                         fos_user_registration: $scope.user,                         confirmpass: $scope.confirmpassword                     };                      $http.post(routing.generate('fos_user_registration_register'), $.param(formdata), {                         headers: {'content-type': 'application/x-www-form-  urlencoded'}                     })                             .then(success, error);                 };             }]);  }()); 

registrationcontroller.php (overridden fosuserbundle)

public function registeraction(request $request) {     /** @var $formfactory \fos\userbundle\form\factory\factoryinterface */     $formfactory = $this->get('fos_user.registration.form.factory');     /** @var $usermanager \fos\userbundle\model\usermanagerinterface */     $usermanager = $this->get('fos_user.user_manager');      $user = $usermanager->createuser();     $user->setenabled(true);      $form = $formfactory->createform();     $form->setdata($user);      $form->handlerequest($request);      if ($form->isvalid()) {         $user->addrole('role_admin');         $usermanager->updateuser($user);          $response = ['valid' => true];         return new jsonresponse($response);     }      $response = ['valid' => false];    return new jsonresponse($response); } 

i don't see csrf token in form. form may not validated without csrf token. check here first; http://symfony.com/doc/current/cookbook/security/csrf_in_login_form.html

also may better generate forms twig templating engine complete compatibility. see here; http://symfony.com/doc/current/book/forms.html

for further investigation why form not being validated, can write else block $form->isvalid() check , use method in answer see form errors. can examine why form not being validated. https://stackoverflow.com/a/17428869/3399234

update

i come solution. used vagrant configuration includes symfony 2.6.10. have overridden registrationformtype, place in own bundle , injected service, fos does. replaced fos registration form own service alias. managed switch off csrf protection in overriden registrationformtype.

also added set plainpassword user model fix persistence error in usermanager.

the controller, overrides fos registration controller.

<?php  namespace acme\webbundle\controller;  use symfony\bundle\frameworkbundle\controller\controller; use fos\userbundle\controller\registrationcontroller basecontroller; use symfony\component\httpfoundation\request request; use symfony\component\httpfoundation\jsonresponse jsonresponse;  class registrationcontroller extends basecontroller {      public function registeraction()         {              $request = request::createfromglobals();              $form = $this->container->get('fos_user.registration.form');             /** @var $usermanager \fos\userbundle\model\usermanagerinterface */             $usermanager = $this->container->get('fos_user.user_manager');              $user = $usermanager->createuser();             $form->setdata($user);              $form->handlerequest($request);              if ($form->isvalid()) {                              $user->setenabled(true);                 $user->addrole('role_admin');                 $usermanager->updateuser($user);                  $response = ['valid' => true];                 return new jsonresponse($response);             } else {                 $string = (string) $form->geterrors(true, false);                 //show errors                 $response = ['valid' => false];                 return new jsonresponse($response);              }            return $this->container->get('templating')->renderresponse('acmewebbundle:default:index.html.twig');         }  } 

overriden fos registration form,

<?php //acme\webbundle\form\type\registrationformtype.php namespace acme\webbundle\form\type;  use symfony\component\form\abstracttype; use symfony\component\form\formbuilderinterface; use symfony\component\optionsresolver\optionsresolverinterface;  class registrationformtype extends abstracttype {      private $class;      /**      * @param string $class user class name      */     public function __construct($class)     {         $this->class = $class;     }      public function setdefaultoptions(optionsresolverinterface $resolver)     {         $resolver->setdefaults(array(             'data_class' => $this->class,             'intention'  => 'registration',             'csrf_protection' => false, //this line trick ;)         ));     }      public function getparent()     {         return 'fos_user_registration';     }      public function getname()     {         return 'acme_user_registration';     } } 

services.yml

services:     acme.registration.form.type:         class: acme\webbundle\form\type\registrationformtype         arguments: ["%fos_user.model.user.class%"]         tags:             - { name: form.type, alias: acme_user_registration } 

index.html.twig

     <script type="text/javascript">                         var app = angular.module('myapp',  []);                              app.controller('newuserctrl', ["$scope", "$http", function ($scope, $http) {                                      var success = function (response) {                                         var valid = response.data.valid;                                         if (valid) {                                             $state.go('home');                                         } else {                                             console.log("invalid form");                                         }                                     };                                      var error = function (reason) {                                         console.log("submission failed");                                     };                                      $scope.submit = function () {                                         var formdata = {                                             fos_user_registration_form: $scope.user                                         };                                      $http.post('<your url here>', $.param(formdata), {                                             headers: {'content-type': 'application/x-www-form-urlencoded'}                                         }).then(success, error);                                     };                                 }]);                 </script>  <div id="content" ng-app="myapp" ng-controller="newuserctrl" >      <form class="form-group text-left" ng-submit="submit()" novalidate name="userfrm">         <div class="form-group">             <label for="user.email" class="required">email</label>             <input id="user.email" name="user.email" class="form-control" type="text" ng-model="user.email" />         </div>         <div class="form-group">             <label for="user.username" class="required">username</label>             <input id="user.username" name="user.username" class="form-control" type="text" ng-model="user.username" />         </div>         <div class="form-group">             <label for="user.plainpassword.first" class="required">password</label>             <input id="user.plainpassword.first" name="user.plainpassword.first" class="form-control" type="password" ng-model="user.plainpassword.first" />         </div>         <div class="form-group">             <label for="user.plainpassword.second" class="required">confirm password</label>             <input id="user.plainpassword.second" name="user.plainpassword.second" compare-to="user.plainpassword.first" class="form-control" type="password" ng-model="user.plainpassword.second" />         </div>         <input type="submit" value="register" ng-disabled="userfrm.$invalid"  class="btn btn-primary center-block col-lg-2" />     </form> </div> 

this fos_user configuration in config.yml change default form overridden form whenever fos user bundle's registration form summoned.

config.yml

fos_user:     registration:         form:              type: acme_user_registration 

and that's can post form , persist user database return {"valid":true} response expected. , have chance learn how inject angularjs symfony 2, cheers that.


Comments