Web API POST method getting null values from Angular2 service call - asp.net-web-api

I created the HTML and TS Component. I gave the service TS code and API code. please help. i tried many options to play with content-type and Accept headers but no luck. all the time i am getting NULL values to my web API method.
HTML page:
<h1>User Preference</h1>
<div class="panel panel-default panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Edit User</h3>
</div>
<div class="panel-body">
<div class="col-md-6" *ngIf="oneUser">
<form autocomplete="off" #userForm="ngForm" (submit)="updateUserInfo(userForm.value)">
<div class="form-group">
<label for="msUserID">MS User ID:</label>
<input id="msUserID" readonly type="text" class="form-control"
[(ngModel)] = "oneUser.msUserId" name="msUserId"
placeholder="Enter MS User ID..."/>
</div>
<div class="form-group">
<label for="firstName">First Name:</label>
<input id="firstName" readonly type="text" class="form-control"
[(ngModel)] = "oneUser.firstName" name="firstName"
placeholder="Enter First Name.." />
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input id="lastName" readonly type="text" class="form-control"
[(ngModel)] = "oneUser.lastName" name="lastName"
placeholder="Enter Last Name..." />
</div>
<div class="form-group">
<label for="userReportAccess">User Report Access:</label>
<select [(ngModel)]="oneUser.userReportAccess" class="form-control" name="userReportAccess">
<option value=""></option>
<option value="0">false</option>
<option value="1">true</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
</div>
COMPONENT:
import { Component, OnInit } from '#angular/core'
import { UserDetails } from "../shared/user-details.model";
import { UserService } from "../shared/user.service";
#Component({
selector: "user-one",
templateUrl: "./user.component.html"
})
export class UserComponent implements OnInit {
public oneUser: UserDetails;
testVa: string = "TEST";
constructor(private userService: UserService) {
}
ngOnInit() {
this.userService.getOneUserDetails()
.then(user => this.oneUser = user);
console.log("DATA" + JSON.stringify(this.oneUser));
}
updateUserInfo(userForm) {
alert("UPDATE method call" + JSON.stringify(userForm));
//data: UserDetails = {
// msUserId: userForm.msUserId,
//};
console.log("Update data" + JSON.stringify(userForm));
let data: UserDetails = {
msUserId: userForm.msUserId,
firstName: userForm.firstName,
lastName: userForm.lastName,
userReportAccess: userForm.userReportAccess
};
this.userService.updateUserDetails(data);
}
}
SERVICE:
import { Injectable, Inject } from '#angular/core';
import { Http, Response, RequestOptions, Headers, RequestMethod } from '#angular/http';
import 'rxjs/Rx';
import 'rxjs/Observable';
import { UserDetails } from './user-details.model';
import { Observable } from "rxjs/Rx";
#Injectable()
export class UserService {
private _originalUrl: string;
public headers: Headers;
constructor(private http: Http, #Inject('ORIGIN_URL') originUrl: string) {
this._originalUrl = originUrl;
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json')
this.headers.append('Accept', 'application/json');
console.log("OriginalURL" + originUrl);
}
getOneUserDetails() {
return this.http.get(this._originalUrl + '/api/PAUser/GetOneUserDetails')
.map(response => response.json() as UserDetails)
.toPromise();
}
updateUserDetails(data) {
let headers = new Headers({
'Content-Type': 'application/json;charset=utf-8',
'Accept': 'application/json'
});
let options = new RequestOptions({ headers: headers, method: RequestMethod.Post });//, method: "post"
console.log("Service data" + JSON.stringify(data));
return this.http.post(this._originalUrl + '/api/PAUser/UpdateOneUserDetails', JSON.stringify(data))
.map(response => response.json() as UserDetails)
.toPromise();
}
}
WEB API:
[HttpPost("[action]")]
public void UpdateOneUserDetails([FromBody] PA_Users userDetails)
{
if (userDetails != null)
{
var userFind = _context.PA_Users.Where(x => x.MsUserId.Equals(userDetails.MsUserId)).ToList();
if (userFind.Count > 0)
{
userFind[0].UserReportAccess = userDetails.UserReportAccess;
_context.SaveChanges();
}
}
}

This might do it... not sure if you have already tried this, can you try adding "DataContractAttribute" to the class and "DataMemberAttribute" to all the members/ properties of the class "PA_Users"?
Hope this helps!
Thanks,
Bhadhri

Related

Unable to render redux form select input choices dynamically

I am trying to populate a select menu in redux forms dynamically.
I've been using the debugging tools in chrome and can see that the 'departments' variable sees the array list
({departments.map(department => <option key={department} value={department}>{department}</option>)}
but the final choice list isn't populating. I'm guessing it has something to do with the renderSelectField function, but I'm not sure what I am overlooking?
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import isValidEmail from 'sane-email-validation';
class SimpleReduxForm extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
this.renderSelectField = this.renderSelectField.bind(this);
}
onSubmit = async (data) => {
try {
let response = await fetch('/api/getRecords', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-type': 'application/json'
}
});
let responseJson = await response.json();
//display success message to user
alert('Form successfully submitted')
return responseJson;
//reset form
} catch (error) {
alert(error);
}
}
renderInputField(field) {
return (
<div className="form-group">
<label htmlFor={field.input.name}>{field.label}</label>
<div className="field">
<input placeholder={field.label} {...field.input} className="form-control" type={field.input.type} />
</div>
</div>
)
}
renderSelectField(field) {
return (
<div className="form-group">
<label htmlFor={field.input.name}>{field.label}</label>
<div className="field">
<select {...field.input}
className="form-control"
defaultselection={field.defaultSelection}
><option>{field.defaultselection}</option></select>
</div>
</div>
)
}
render() {
const { handleSubmit, pristine, reset, submitting, invalid } = this.props;
//Options for select - this should be an AJAX call to a table to get options list
const departments = ["Dept 1", "Dept 2", "Dept 3"]
return (
<form onSubmit={handleSubmit(this.onSubmit)}>
<Field
label="Username"
name="username"
component={this.renderInputField}
type="text"
/>
<Field
label="Email"
name="email"
component={this.renderInputField}
type="email"
/>
<Field
label="Age"
name="num_field"
component={this.renderInputField}
type="text"
/>
<Field
label="Department"
name="department"
defaultselection="Select..."
component={this.renderSelectField}>
{departments.map(department => <option key={department} value={department}>{department}</option>)}
</Field>
<div>
<button type="submit" className="btn btn-primary" disabled={pristine || submitting}>Submit</button>
<button type="button" className="btn btn-warning" disabled={pristine || submitting} onClick={reset}> Clear Values </button>
</div>
</form >
)
}
}
//Validate Errors Before Submission
const validate = (values) => {
//create errors object
const errors = {}
/*Example showing to check is a field contains data
* if no, submission == invalid*/
if (!values.username) {
errors.username = 'Required!'
}
/*check to see if email is provided and that submission is an actual email address*/
if (!values.email) {
errors.email = 'Required!'
} else if (!isValidEmail(values.email)) {
errors.email = 'Invalid Email!'
}
/* Example to show that the length of a field
* can be checked as part of validation */
if (values.num_field < 2) {
errors.num_field = "Must be at least 10 years old"
}
return errors
}
const mapStateToProps = state => ({
SimpleReduxForm: state.form.SimpleReduxForm
});
export default reduxForm({
validate,
form: 'SimpleReduxForm',
enableReinitialize: true,
keepDirtyOnReinitialize: true,
})(connect(mapStateToProps)(SimpleReduxForm));
I figured it out. Just in case anyone else runs into this issue. I needed to add {field.children} into the renderSelectField function. So the final function looks like:
renderSelectField(field) {
return (
<div className="form-group">
<label htmlFor={field.input.name}>{field.label}</label>
<select {...field.input}
className="form-control"
defaultselection={field.defaultSelection}
><option>{field.defaultselection}</option>{field.children}</select>
</div>
)
}

How to validate a form on button submit

I have a form, which is getting validated once the control gets the class change from ng-untouched ng-pristine ng-invalid to ng-pristine ng-invalid ng-touched but if i have a form with more controls then i want the user to know which field he/she has missed out on the button submit. how can i do that using angularJS2. I have used ReactiveFormsModule to validate the controls
The following is my code: component
import { Component } from '#angular/core';
import { FormBuilder, Validators, FormGroup, FormControl } from '#angular/forms';
#Component({
selector: 'page',
templateUrl:'../app/template.html'
})
export class AppComponent {
registrationForm: FormGroup;
constructor(private fb: FormBuilder) {
this.registrationForm = fb.group({
username: ['', [Validators.required, Validators.minLength(4)]],
emailId: ['', [Validators.required, this.emailValidator]],
phonenumber: ['', [Validators.required, this.phoneValidation]]
})
}
emailValidator(control: FormControl): { [key: string]: any } {
var emailRegexp = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+#[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
if (control.value && !emailRegexp.test(control.value)) {
return { invalidEmail: true };
}
}
phoneValidation(control: FormControl) {
if (control['touched'] && control['_value'] != '') {
if (!/^[1-9][0-9]{10}$/.test(control['_value'])) {
return { 'invalidPhone': true }
}
}
}
}
The following is my code: module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from '../app/component';
#NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
The following is my code: template
<form [formGroup]="registrationForm" (ngSubmit)="registrationForm.valid && submitRegistration(registrationForm.value)">
<input type="text" formControlName="username" placeholder="username" />
<div class='form-text error' *ngIf="registrationForm.controls.username.touched">
<div *ngIf="registrationForm.controls.username.hasError('required')">Username is required.</div>
</div>
<br />
<input type="text" formControlName="emailId" placeholder="emailId" />
<div class='form-text error' *ngIf="registrationForm.controls.emailId.touched">
<div *ngIf="registrationForm.controls.emailId.hasError('required')">email id is required.</div>
<div *ngIf="registrationForm.controls.emailId.hasError('invalidEmail')">
Email is not in correct format.
</div>
</div>
<br />
<input type="text" formControlName="phonenumber" placeholder="phonenumber" />
<div class='form-text error' *ngIf="registrationForm.controls.phonenumber.touched">
<div *ngIf="registrationForm.controls.phonenumber.hasError('required')">phone number is required.</div>
<div *ngIf="registrationForm.controls.phonenumber.hasError('invalidPhone')">Invalid phone number.</div>
</div>
<br />
<input type="submit" value="Submit" />
</form>
I thought of updating all the invalid controls class to ng-untouched ng-pristine ng-invalid but not sure if this is the right approach
Angular forms don't provide ways to specify when to do validation.
Just set a flag to true when the form is submitted and show validation warnings only when the flag is true using *ngIf="flag" or similar.
<form [formGroup]="registrationForm" (ngSubmit)="submitRegistration(registrationForm.value)">
<div *ngIf="showValidation> validation errors here </div>
showValidation:boolean = false;
submitRegistration() {
if(this.registrationForm.status == 'VALID') {
this.processForm();
} else {
this.showValidation = true;
}
}

Angular 2 - Required field validation if checkbox is selected

Hy guys I'm new to Angular2 and in JS frameworks in general. I'm flowing tutorials on official site and haven't been able to find the solution to this problem.
So I have checkbox which is optional but if the checkbox is "checked" a new input field is shown. this part is not a problem. The problem is that I'm using modal based validation and I can't figure out how to make this new input field required only if the checkbox is checked.
this is may implementation so far:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<!--{{form}}-->
<div formGroupName="test">
<div class="field">
<div class="checkbox">
<input type="checkbox" name="entryRecurring" value="" id="entryRecurring" formControlName="entryRecurring" />
<label for="entryRecurring">
<div class="checkbox_icon"></div>
Recurring Entry
</label>
</div>
</div>
<div *ngIf="form.value.test.entryRecurring">
<div class="field">
<label for="entryRecurringAmount">Repeat Amount</label>
<input type="text" name="entryRecurringAmount" value="" id="entryRecurringAmount" formControlName="entryRecurringAmount" />
</div>
</div>
</div>
<div class="field last">
<button name="submit" id="submit" class="btn btn_sushi" [disabled]="!form.valid">Submit</button>
</div>
import {Component, Input, OnInit, OnChanges} from '#angular/core';
import { Validators } from '#angular/common';
import { REACTIVE_FORM_DIRECTIVES, FormGroup, FormControl, FormBuilder } from '#angular/forms';
import { FormMessages } from './../helpers/formMessages.component';
import {EntriesService} from './entries.service';
import {ValidationService} from '../helpers/validation.service';
import {Category, CategoryByType} from '../../mock/mock-categories';
#Component({
selector: 'entryForm',
templateUrl: 'app/components/entries/entriesEdit.template.html',
directives: [REACTIVE_FORM_DIRECTIVES, FormMessages],
providers: [EntriesService, ValidationService]
})
export class EntriesEditComponent implements OnInit, OnChanges {
#Input() control: FormControl;
public form:FormGroup;
public submitted:boolean = false;
// private selectedId: number;
categories: Category[];
categoriesSortedByType: CategoryByType[];
constructor(
private _fb:FormBuilder,
private _entriesService: EntriesService
// private _router: Router
) {
this.form = this._fb.group({
test: this._fb.group({
entryRecurring: [''],
entryRecurringAmount: [''],
})
});
}
onSubmit() {
this.submitted = true;
// console.log(this.form.value);
if (this.form.dirty && this.form.valid) {
this._entriesService.saveEntry(this.form.value);
}
}
You could do that by using a custom validation service.
import {NgFormModel} from "angular2/common";
import {Component, Host} from 'angular2/core';
#Component({
selector : 'validation-message',
template : `
<span *ngIf="errorMessage !== null">{{errorMessage}}</span>
`,
inputs: ['controlName : field'],
})
export class ControlMessages {
controlName : string;
constructor(#Host() private _formDir : NgFormModel){
}
get errorMessage() : string {
let input = this._formDir.form.find(this.controlName);
let checkBx = this._formDir.form.find('checkBoxName');
if(input.value.trim() === '' && checkBx.checked) {
return 'The input field is now required'
}
return null;
}
}
Then use the new component like bellow
<div *ngIf="form.value.test.entryRecurring">
<div class="field">
<label for="entryRecurringAmount">Repeat Amount</label>
<input type="text" name="entryRecurringAmount" value="" id="entryRecurringAmount" ngControl="entryRecurringAmount" />
<validation-message field="entryRecurringAmount"></validation-message>
</div>
</div>
Hope that helped!

Angular2 How to pass a method located in other file

I am quite a noob in Angular2 and typescript.
I want to pass a method from other class in a other file.
This is the file iam talking about in specific i want to pass the method deleteCondition():
export class ConditionBuilderComponent implements OnInit {
conditions: Condition[] = [];
catalog: Condition[] = [];
constructor(private _conditionService: ConditionService) { }
getConditions() {
this._conditionService.getConditions().then(conditions => this.catalog = conditions);
}
ngOnInit() {
this.getConditions();
}
onChange(conditionsIndex, catalogIndex) {
//console.log(selectedCondition);
//console.log(conditionsIndex);
console.log(catalogIndex);
this.conditions[conditionsIndex] = this.catalog[catalogIndex];
}
newCondition() {
this.conditions.push(this.catalog[0]);
}
deleteCondition() {
this.conditions.pop();
}
}
I want to pass the deleteCondition() method to an other file because in the other file this.conditions.pop() is not recognised of course.
First it was like this: https://www.dropbox.com/s/92z2oe7f4w5x2b5/conditions.jpg?dl=0
Here it deletes the last created but i want to delete each condition separately like this:
https://www.dropbox.com/s/ptwq6sk6da4p21k/new.jpg?dl=0
This is the code from the SelectCondition:
import {Component} from 'angular2/core';
import {Condition} from './condition';
import {ConditionBuilderComponent} from "./conditionbuilder.component";
#Component({
selector: 'select-condition',
template: `
<div class="col-xs-3">
<div class="form-group">
<select class="form-control" [(ngModel)]="selectedOperator">
<option *ngFor="#operator of selectOperators">{{operator}}</option>
</select>
</div>
</div>
<div class="col-xs-3">
<div class="form-group">
<div class="input-group">
<span class="btn-file">
<input type="file" (click)="selectFile()" multiple />
</span>
<input type="text" [(ngModel)]="fileValue" class="form-control" readonly>
<span class="input-group-addon">
<span class="glyphicon glyphicon-folder-open"></span>
</span>
</div>
</div>
</div>
<a class="btn btn-danger pull-right" (click)="deleteCondition()"><i class="glyphicon glyphicon-minus"></i></a>
`
})
export class SelectCondition extends Condition {
public name: string = 'select';
public fileValue: string;
public selectedOperator: string = 'in';
public selectOperators: Condition[] = [
"in"
];
selectFile() {
$(document).on('change', '.btn-file :file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$('.btn-file :file').on('fileselect', function(event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if( input.length ) {
input.val(log);
console.log(input.val());
}
});
}
deleteCondition = () => this.deleteCondition();
}
Please help me out.

FOSUserBundle register in AngularJS

I have a SPA web application that uses AngularJS for the frontend and Symfony2 for the backend.
I used FOSUserBundle for handling the User.
What I want to do right now is to use the AngularJS method of registering my User which is via Ajax
My problem is that whenever I submit the form, it prints "invalid form" in the console log.
Here's my 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 from 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 a CSRF token in your form. Your form may not be validated without CSRF token. Check here first; http://symfony.com/doc/current/cookbook/security/csrf_in_login_form.html
Also it may be better to generate your forms with twig templating engine for complete compatibility. See here; http://symfony.com/doc/current/book/forms.html
For further investigation why your form is not being validated, you can write an else block for $form->isValid() check and use the method in the answer to see your form errors. You can examine why your form is not being validated. https://stackoverflow.com/a/17428869/3399234
UPDATE
I come up with a solution. I used my Vagrant configuration which includes symfony 2.6.10. I have overridden the RegistrationFormType, place it in my own bundle and injected it as a service, just like FOS does. I replaced the FOS registration form with my own service alias. So I managed to switch off csrf protection in my overriden RegistrationFormType.
Also added to set plainPassword to user model to 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 as BaseController;
use Symfony\Component\HttpFoundation\Request as Request;
use Symfony\Component\HttpFoundation\JsonResponse as 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 The 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 does the 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 is the fos_user configuration in config.yml to change default form with your overridden form whenever FOS User bundle's registration form is summoned.
config.yml
fos_user:
registration:
form:
type: acme_user_registration
And that's it I can post with the form and persist the user to database then return the {"valid":true} response as expected. And finally i have chance to learn how to inject AngularJS to Symfony 2, cheers for that.

Resources