Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

submit a symfony2 form using angularjs

I am building an application with symfony2 on the backend. I am thinking about using AngularJS on the frontend, but I would still like to use symfony forms. I have setup the form with the correct modules and everything, but the problem occurs when the data is actually submitted.

Problem

When Symfony renders the form, it sets the inputs 'name' attribute to an array, like user[username], and this is the format that it expects to receive the data once it is submitted. I can't figure out how to get Angular to submit the data in this format. This is what I have:

<body ng-app="formApp" ng-controller="formController">
{{ form_start(form, {'attr':{'id': 'registerForm', 'ng-submit':'processForm()'}}) }}

{{ form_row(form.username, {'attr':{'ng-model':'formData.username'}}) }}
{{ form_row(form.password.first, {'attr':{'ng-model':'formData.password'}}) }}
{{ form_row(form.password.second) }}
{% for address in form.userAddresses %}
        {{ form_row(address.postalCode, {'attr':{'ng-model':'formData.postalCode'}}) }}
{% endfor %}

<div><input type="submit" value="Save" /></div>
{{ form_end(form) }}
</body>

and the controller:

function formController($scope, $http) {

$scope.formData = {};

$scope.processForm = function() {
    $http({
        method  : 'POST',
        url     : submit,
        data    : $.param($scope.formData), 
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
        .success(function(data) {
            alert(data.message);
        });
};
}

When I submit, obviously the name-value pair uses the formData variables, so username=testuser instead of user[username]=testuser.

I tried to set the formData variable like formData.user[username], but that didn't work at all.

So is there a way to either use the inputs 'name' when submitting, or do something so that the form is submitted in the correct format? Any help would be great!

like image 424
Sehael Avatar asked Oct 01 '22 20:10

Sehael


1 Answers

You can build the object symfony expects in a $scope function that you would bind to your form's submit with ng-click. So:

<input type="submit" value="Save" /></div>

would become

<input type="submit" value="Save" ng-click="submitForm()" /></div>

and in your controller you would add a function on the $scope object

$scope.submitForm = function() {
  var user = [];
  user['username'] = $scope.formData.username;
  //etc
};
like image 94
akronymn Avatar answered Oct 09 '22 21:10

akronymn