Customize form field rendering - forms

I would like to customize the rendering of a form field in the edit page from sonata admin bundle to include an applet that uses the text content of a field.
I know that I have to edit the configureFormFields function in the admin class, but I need to know 3 things:
What is the syntax to provide a field form template
Where to put the template file ( which directory )
What the template have to looks like.

Found a solution
What i have done is:
Created a field type, lets call it myfieldType in myCompany\myBundle\Form\Type\myfieldType.php
namespace myCompany\myBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class myfieldType extends AbstractType
{
public function getParent()
{
return 'text';
}
public function getName()
{
return 'myfield';
}
}
Registered the Type in app/config/services.yml
myCompany.myBundle.form.type.myfield:
class: myCompany\myBundle\Form\Type\myfieldType
tags:
- { name: form.type, alias: myfield }
In my myentityAdmin class,
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('myfieldname', 'myfield')
...
}
and
public function getFormTheme() {
return array('myCompanymyBundle:Admin:myfield_edit.html.twig');
}
and the template :
{# src/mycompany/myBundle/Resources/views/Form/myfield_edit.html.twig #}
{% block myfield_widget %}
{% spaceless %}
{{ block('textarea_widget') }}
{% endspaceless %}
{% endblock %}
And now i can access the form field value by the twig variable "value" !
So easy... when you got it.

user1254498's solution won't work unless the block name prefix matches the name of the form type. At least with the last version of sonata admin bundle (2.2.12). In this case:
{# src/mycompany/myBundle/Resources/views/Form/myfield_edit.html.twig #}
{% block myfield_widget %}
{% spaceless %}
{{ block('textarea_widget') }}
{% endspaceless %}
{% endblock %}
And, regarding getFormTheme(), you shoud return also the parent theme, otherwise you may break the whole style...
public function getFormTheme()
{
return array_merge(
parent::getFormTheme(), array(
'mycompanyBundle:Form:myfield_edit.html.twig')
);
}
Also, you can access the admin service in the twig template with the variable sonata_admin.admim.

In your services.yml file you define the template for your edit Action:
app.admin.product:
class: AppBundle\Admin\ProductAdmin
arguments: [~, AppBundle\Entity\Product, AppBundle:Admin\Product]
tags:
- {name: sonata.admin, manager_type: orm, group: Products, label: Products}
calls:
- [ setTemplate, [edit, AppBundle:Product:edit.html.twig]]
In that template you can then override templates for fields in your form:
{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}
{% form_theme form.selectall 'AppBundle:Form:selectall.html.twig' %}
{% form_theme form.Country 'AppBundle:Form:country.html.twig' %}
Then my template looks like that:
{% block form_row %}
<div class="form-group">
{{ form_label(form) }}
{% set c = 0 %}
{% for i in form %}
{% set c = c+1 %}
{% if (c == 1) %}
<div style="float: left; width: 20%;">
{% endif%}
{{ form_row(i) }}
{% if ((c == 60) or (form|length == loop.index)) %}
</div>
{% set c = 0 %}
{% endif%}
{% endfor %}
</div>
{% endblock form_row %}
In this case, my countries check boxes appear in column of 60 elements, not in one column with the whole list of elements.
Hope this is helpful to someone else.

Related

How to check if form has errors in twig?

Beside the form field specific error messages directly attached to the form field I would like to display a message above the form that the form contains errors.
How can I check in a Symfony3 twig template if a form has errors? There used to be something like this in Symfony2:
{% if form.get('errors') is not empty %}
<div class="error">Your form has errors. Please check fields below.</div>
{% endif %}
But this doesn't work in Symfony3. Any ideas? (form.vars.errors doesn't work.)
Use form.vars.errors:
{% if form.vars.errors is not empty %}
{# ... #}
{% endif %}
Attention! Note that this just evaluatues to true, if your root form has errors (or if child forms have errors and allow bubbling the error up to the root form). If regular child elements of your form have errors, this will not evaluate to empty!
So the valid variable is probably of more suitable:
{% if not form.vars.valid %}
{# ... errors ! #}
{% endif %}
With symfony 3.4 it's not possible through form.vars.errors anymore except if you have error_bubbling = true and form compound = false which is unlikely.
You can either use a dirty code like this :
{% set errors = false %}
{% for child in form.children %}
{% if child.vars.errors is defined and child.vars.errors|length %}
{% set errors = true %}
{% endif %}
{% endfor %}
{% if errors %}
[...]
{% endif %}
If you are trying to build a login form with AuthenticationUtils, use a code like this in controller :
//Get the login error if there is one
if ($error = $authenticationUtils->getLastAuthenticationError()) {
//Add error message to mail field
$form->get('mail')->addError(new FormError($error->getMessageKey()));
}
//Last username entered by the user
if ($lastUsername = $authenticationUtils->getLastUsername()) {
$form->get('mail')->setData($lastUsername);
}
//Render view
return $this->render('#ExampleBundle/template.html.twig', array('form' => $form->createView(), 'error' => $error));
And use a simple code like this in twig template :
{% if error %}
[...]
{% endif %}

Pass a variable to a parent form in twig

I need to pass a variable to a parent form in twig:
{# This block is called for the children and the parent #}
{% block form_rows %}
{% for child in form %}
{% if child.vars.foo == 'bar' %}
{% set form.vars = form.vars|merge({'key': 'value'}) %}
{% endif %}
{# Parent check children key var #}
{% if child.vars.key %}
{# do something #}
{% endif %}
{# Will call children form_rows block recursively #}
{{ form_row(child) }}
{% endfor %}
{% endblock form_rows %}
This of course don't work because you cannot set a variable like this and form is an object not an array.
I couldn't find any solution until now.
Ok, the whole thing is a bad idea, but it should be possible since Twig v1.2 using the attribute function. For that you need a setter Method in you form object, eg:
class YourFormClass {
public $vars;
/* your class code comes here */
public function setVars($newVars) {
$this->vars = $newVars;
}
}
Assuming that the twig form variable is an instance of YourFormClass you can now use the attribute function like this:
{% set newVal = form.vars|merge({'key': 'value'}) %}
{{ attribute(form, 'setVars', [newVal]) }}
{{ dump(form.vars) }}

Symfony 2 Forms with Twig: add form variable to existing types

I need my symfony2/twig forms to adhere to a certain condition: All form rows must look similar to this:
{% block form_row %}
<div class="CONSTANT_CLASS class_based_on_field_type class_based_on_error">
{{ form_label(form) }}
{{ form_widget(form) }}
...
</div>
{% endblock form_row %}
Notice that I need to get the field type within the form_row block. Alas, the field type is only defined at the widget level.
I definitely need a way to let my form_row know what type of field it is dealing with.
So i suppose it would be best to somehow override the form_row twig function.
Where can the default twig functions be overridden? And how could this be done?
Remember, this is not about customizing a form. I need to know how to add to existing form variables for existing field types.
#nifr:
The key answer for you seems to be the {% set typeClass ... %}. But there is not a defined variable text anywhere for the template. Look at form_div_layout.html.twig at line 158ff, I think the type really gets set only at the form_widget level and is thus capsulated to be there. That means using the type at the form_row level will aways result in the given default (So it occurred to me while testing). If you can prove this wrong I will happily accept your answer.
How to override the form_row block in Twig adding attributes by field-type?
Though you say this is not about form customization it can be achieved with it ... Quick Introduction for others reading this now.
The default symfony twig form extensions can be found here.
The default twig form theme can be found at Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig.
General information on how to override forms can be found in the How to Customize Form Rendering chapter of the Book but i will sum this up shortly.
form_row Default
{% block form_row %}
{% spaceless %}
<div>
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock form_row %}
Overriding Form Level
Add this to the form template you want to customize:
{% form_theme form _self %}
If you want to put the {% block form_row %} into another bundle/template use this:
{% form_theme form 'AcmeDemoBundle:Form:fields.html.twig' %}
Now insert your custom form_row block after the form_theme declaration or put it into the specified template (in our case this would be AcmeDemoBundle:Form:fields.html.twig).
In my example we will add the class 'error' if there is an error in the form row and a another classname nameely the type name of the current field-type.
{% block form_row %}
{% spaceless %}
{# set class to 'error' if errors exist #}
{% set attr = attr|merge({'class': attr.class|default('') ~ (errors|length > 0 ? ' error' : '') }) %}
{% set typeClass = ' ' ~ type|default('text') %}
{#
you could also implement a logic matching input types with an array of their
desired classname-representations here.
#}
{% set attr = attr|merge({'class': attr.class|default('') ~ type) }) %}
<div class="{% for class in attr.class %}{{ class }}{% endfor %}{{ typeClass }}">
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock form_row %}
if you want to apply your form_row block system-wide add your AcmeDemoBundle:Form:fields.html.twig to your twig.templating.form.resources !
# app/config/config.yml
framework:
templating:
form:
resources:
- 'AcmeDemoBundle:Form'
In the form_row block you can use :
{{ form.vars.block_prefixes[2] }}
form.vars.block_prefixes gives you an array with more information and it might change with versions. But from what I have seen so far it is always index 2

Symfony 2 custom form field type: how to add javascript and css only once?

I want to use javascript in custom Symfony 2 form field type extension. So, I have Twig extension template like this:
{% block some_widget %}
<input ... />
<script src="some.js"></script>
<link href="some.css" />
{% endblock %}
But I want to have these script and link tags only once in my HTML, ideally in head tag, without modifing base template. I tried to extend Twig blocks, but I have no access to action template blocks inside form template. Or maybe something like this:
{# widget tempate #}
{% block some_widget %}
<input ... />
{{ use_javascript('some.js') }}
{{ use_css('some.css') }}
{% endblock %}
{# main action template #}
...
<head>
{{ dump_javascripts() }}
{{ dump_css() }}
</head>
...
How to do this with Symfony 2 Forms + Twig?
P.S. Sorry for my bad english.
I had to write a self contained form widget that requires javascript, I was able to achieve what you are trying to do through the event_dispatcher listening on the kernel.response to append the javascript at the end of the Symfony\Component\HttpFoundation\Response. Here's a snippet of my form type :
<?php
namespace AcmeBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
class AcmeFileType extends AbstractType{
private $twig;
private $dispatcher;
public function __construct(\Twig_Environment $twig, EventDispatcherInterface $dispatcher){
$this->twig = $twig;
$this->dispatcher = $dispatcher;
}
public function buildView(FormView $view, FormInterface $form, array $options){
$javascriptContent = $this->twig->render('AcmeBundle:Form:AcmeFileType.js.twig', array());
$this->dispatcher->addListener('kernel.response', function($event) use ($javascriptContent) {
$response = $event->getResponse();
$content = $response->getContent();
// finding position of </body> tag to add content before the end of the tag
$pos = strripos($content, '</body>');
$content = substr($content, 0, $pos).$javascriptContent.substr($content, $pos);
$response->setContent($content);
$event->setResponse($response);
});
}
...
When you define your form type in your services.yml it looks like this :
acme.form.acme_file_type:
class: AcmeBundle\Form\AcmeFileType
arguments:
- #twig
- #event_dispatcher
tags:
- { name: form.type, alias: acmefile }
So now, everytime you build a form with acmefile the javascript will be appended to the <body>. This solution does not prevent the javascript from being present multiple time though, but you should easily be able to improve this to suit your needs.
You can also play around with the $response object to modify the headers instead if you wish.
The best way is to provide the separate template with css & scripts loading.
With the comments in readme so only thing developer will must do is to
{% block stylesheets %}
{{ parent() }}
include "#MyBestBundle/Resources/view/styles.html.twig"
{% endblock %}
or try to intercept the form rendering with DI and add the assets. But it more difficult to do , if possible to implement.
My way of doing was by creating a custom twig extension where I add JS to a buffer and during form rendering and later dump it at the of my layout.
Something like this:
<?php
namespace AppBundle\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class WysiwygExtension extends AbstractExtension
{
/**
* #var array
*
* A pool of elements IDs for Wysiwyg binding.
*/
private $wysiwygElements = [];
/**
* {#inheritdoc}
*/
public function getFunctions()
{
return array(
new TwigFunction('addWysiwygBinding', [$this, 'addWysiwygBinding']),
new TwigFunction('popWysiwygBindings', [$this, 'popWysiwygBindings']),
);
}
public function addWysiwygBinding(string $id): void
{
$this->wysiwyglements[] = $id;
}
public function popWysiwygBindings(): array
{
$elements = array_unique($this->wysiwygElements);
$this->wysiwygElements = [];
return $elements;
}
}
Then form-fields.html.twig:
...
{% block wysiwyg_widget %}
{% apply spaceless %}
{{ form_widget(form) }}
{% do addWysiwygBinding(id) %}
{% endapply %}
{% endblock %}
...
Then layout.html.twig:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
{% set ids = popWysiwygBindings() %}
{% if ids is not empty %}
{% javascripts
'bundles/admin/plugins/wysiwyg_1.js'
'bundles/admin/plugins/wysiwyg_2.js'
%}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endif %}
{% for id in ids %}
{{ include('_wysiwyg.html.twig', { id: id }) }}
{% endfor %}
</body>
</html>
This is how I use it. Hope it's what you're looking for.
base.html.twig
<head>
{% block stylesheets %}
css...
{% endblock %}
</head>
foo.html.twig
{% extends '::base.html.twig' %}
{% block stylesheets %}
{{ parent() }}
css that you need in foo.html.twig
{% endblock %}
I found some 'dirty' method used by many peoples in other situations.
We check the loading of script on client side. In case we have a zlkladr.js file, that have a global object 'zlkladr'
{% block our_widget %}
{% spaceless %}
...
<script>
// We must load the script only once, even if many widgets on form
if ( !window.zlkladr ) {
document.write('<script src="{{ asset('bundles/kladr/js/zlkladr.js') }}"></sc'+'ript>');
}
</script>
{% endspaceless %}
{% endblock %}

Symfony2: Form fragment themeing and TWIG

Can anyone explain why this code:
{% form_theme form _self %}
{% block avo_gallery_upload_widget %}
{% spaceless %}
<label for="name">Name:</label>
{{ form_widget(form.name) }}
<label for="description">Description:</label>
{{ form_widget(form.description) }}
{% endspaceless %}
{% endblock avo_gallery_upload_widget %}
Throws
Method "name" for object "Symfony\Component\Form\FormView" does not exist in MyBundle:Default:upload.html.twig at line 13
For reference: line 13 is {{ form_widget(form.name) }}
But when wrapped in IF clause:
{% form_theme form _self %}
{% block avo_gallery_upload_widget %}
{% spaceless %}
{% if form.name is defined %}
<label for="name">Name:</label>
{{ form_widget(form.name) }}
<label for="description">Description:</label>
{{ form_widget(form.description) }}
{% endif %}
{% endspaceless %}
{% endblock avo_gallery_upload_widget %}
Suddenly everything works fine!
For reference - this is how form looks like:
class GalleryUploadType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name', 'text')
->add('description', 'textarea')
;
}
public function getName()
{
return 'avo_gallery_upload';
}
public function getDefaultOptions(array $options){
return array('data_class' => 'Me\MyBundle\Entity\GalleryUpload');
}
}
fabpot closed github issue (2012-07-03) with comment:
Every month, I spend hours trying to reproduce the problem without luck. So, I'm giving up for now as there is probably something else going on in your application (as it works fine for almost everyone). If you have any new information that can be relevant, feel free to reopen a new ticket. Thanks.
Since it probably is something wrong in my application and there is nothing new I could add to the question I am closeing this question.
If you happen to encounter this error have a look at this workaround.
If you have any additional info on reproducing the problem, post it here.