Skip to content

Instantly share code, notes, and snippets.

@RemiAWE
Forked from romaricdrigon/formController.js
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RemiAWE/b354c88b80121a4ace80 to your computer and use it in GitHub Desktop.
Save RemiAWE/b354c88b80121a4ace80 to your computer and use it in GitHub Desktop.
{# This is an extension of Twig Form Theme #}
{# We redefine form elements, so they are binded with Angular model #}
{% extends "form_div_layout.html.twig" %}
{# Make data available to current scope as $scope.data - will not work with hidden fields #}
{% block widget_attributes %}
{% spaceless %}
ng-model="data['{{ full_name }}']" {# we add Angular ng-model #}
{% if value is not empty %}
ng-init="data['{{ full_name }}']='{{ value }}'" {# we add ng-init for update forms and input hidden #}
{% endif %}
id="{{ id }}" name="{{ full_name }}"{% if read_only %} readonly="readonly"{% endif %}{% if disabled %} disabled="disabled"{% endif %}{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }}"{% endif %}
{% for attrname, attrvalue in attr %}{% if attrname in ['placeholder', 'title'] %}{{ attrname }}="{{ attrvalue|trans({}, translation_domain) }}" {% else %}{{ attrname }}="{{ attrvalue }}" {% endif %}{% endfor %}
{% endspaceless %}
{% endblock widget_attributes %}
{# current controller submit() will called, instead of submitting the form #}
{% block form_start %}
{% spaceless %}
{% set method = method|upper %}
{% if method in ["GET", "POST"] %}
{% set form_method = method %}
{% else %}
{% set form_method = "POST" %}
{% endif %}
<form name="{{ form.vars.name }}" ng-submit="submit()" method="{{ form_method|lower }}" action="{{ action }}"{% for attrname, attrvalue in attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}{% if multipart %} enctype="multipart/form-data"{% endif %}>
{% if form_method != method %}
<input type="hidden" name="_method" value="{{ method }}" />
{% endif %}
{% endspaceless %}
{% endblock form_start %}
// An example controller binded to the form
function FormCntl($scope, $compile) {
// Consider using FosJsRouting bundle, if you want to use a Symfony2 route
$scope.formUrl = "http://url-to-fetch-my-form";
// Data from the form will be binded here
$scope.data = {};
// Method called when submitting the form
$scope.submit = function() {
// Add your own logic, for example show the response your received from Symfony2
// We have to explictly compile the data received, to parse AngularJS tags
$scope.formResponse = $compile(data)($scope);
}
}
<!-- Form (AngularJS) template -->
<div
ng-include="formUrl"
ng-bind-html-unsafe="formResponse"
ng-controller="FormCntl"
></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment