简体   繁体   English

使用angularjs提交symfony2表单

[英]submit a symfony2 form using angularjs

I am building an application with symfony2 on the backend. 我正在后端使用symfony2构建应用程序。 I am thinking about using AngularJS on the frontend, but I would still like to use symfony forms. 我正在考虑在前端使用AngularJS,但我仍想使用symfony形式。 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. 当Symfony呈现表单时,它会将输入的“名称”属性设置为一个数组,例如user[username] ,这是它期望在提交数据后会接收数据的格式。 I can't figure out how to get Angular to submit the data in this format. 我不知道如何使Angular以这种格式提交数据。 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 . 当我提交时,显然,名称/值对使用formData变量,因此username=testuser而不是user[username]=testuser

I tried to set the formData variable like formData.user[username] , but that didn't work at all. 我试图设置像formData.user[username]这样的formData变量,但这根本不起作用。

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! 任何帮助将是巨大的!

You can build the object symfony expects in a $scope function that you would bind to your form's submit with ng-click. 您可以在$ scope函数中构建symfony期望的对象,该函数将使用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对象上添加一个函数

$scope.submitForm = function() {
  var user = [];
  user['username'] = $scope.formData.username;
  //etc
};

I think you should keep Angular form logic. 我认为您应该保持Angular表单逻辑。 You should use ng-model to bind data. 您应该使用ng-model绑定数据。 To do this, you can create a Twig Form Theme to add ng-model attributes to your inputs, take a look at this gist . 为此,您可以创建一个Twig表单主题,以将ng-model属性添加到您的输入中,请看一下要点

Then you could pass input values to a $scope.data var in your controller like this: 然后可以将输入值传递给控制器​​中的$ scope.data var,如下所示:

$scope.var = {};

You should serialize data with the function provided in this article at line 109 or use jQuery.param() if you use jQuery. 您应该使用本文第 109行提供的功能序列化数据,或者如果使用jQuery,则使用jQuery.param()。

Then create a submit method like this: 然后创建一个提交方法,如下所示:

$scope.submit = function(){
    $http.post(
        'http://www.myurl.com',
        this.serializeData($scope.data),
        { headers: {
                'Content-Type': 'application/x-www-form-urlencoded' //Fix for Symfony
            }
        })
    .success(function(data) {
       //
    })
    .error(function (data){
        $log.error(data);
    });
}

I solve it using server side code. 我使用服务器端代码解决它。 before handling of the request and validation i call the following function i created to change the format: 在处理请求和验证之前,我调用了我创建的以下函数来更改格式:

   /**
     * Format the request content with the form name
     * @param Request $request
     * @param $formName
     * @param null $content
     * @return Request
     */
     public function formatRequestWithForm(Request $request, $formName, $content = null)
     {
      if ($content === null) {
          $content = $request->getContent();
      }
      $contentArray = array($formName => json_decode($content, true));
      $request->attributes->add($contentArray);
      $request->request->add($contentArray);
      return $request;


     }  

You could use {'data-ng-model': 'formData["user[username]"]'}. 您可以使用{'data-ng-model':'formData [“ user [username]”]'}。 To post formData you should pass it through jQuery.param(). 要发布formData,您应该通过jQuery.param()传递它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM