Symfony 3: FosUserBundle Customizing registration form using custom html classes - php

As I was trying to customize a login form fro FosUSerBundle of my symfony 3 project, therefore I had a look on the FosUSerBundle's default twig templates in order to gen an idea, then I noticed that the twig template provided via vendor (vendor/friendsofsymfony/user-bundle/Resources/views/Registration/register_content.html.twig) has the following values:
{% trans_default_domain 'FOSUserBundle' %}
{{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register'}}) }}
{{ form_widget(form) }}
<div>
<input type="submit" value="{{ 'registration.submit'|trans }}" />
</div>
{{ form_end(form) }}
And I noticed that it calls a {{ form_widget(form) }} in order to render the form. so I want to know how this method is called and how can I customize the view. Basically I want the and the html classes of the form in order to look like the registration admin AdminLte's One: https://almsaeedstudio.com/themes/AdminLTE/pages/examples/register.html
Right now what I have done is to create this template app/Resources/FOSUSerBundle/views/Registration/register.html.twig:
{% extends "FOSUserBundle::layout.html.twig" %}
{% set classes='hold-transition register-page'%}
{% block fos_user_content %}
{% trans_default_domain 'FOSUserBundle' %}
<div class="register-box">
<div class="register-logo">
<h1>PhotoShare!</h1>
</div>
<div class="register-box-body">
<p class="login-box-msg">Register a new membership</p>
{{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register')}) }}
{{ form_widget(form) }}
<div class="row">
<div class="col-xs-4">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="{{ 'registration.submit'|trans }}" />
</div>
</div>
{{ form_end(form) }}
</div>
{% endblock fos_user_content %}
That extends app/Resources/FOSUSerBundle/views/layout.html.twig has the following content:
{% extends '::base.html.twig' %}
{% block title %}Photoshare!!{% endblock %}
{% set classes=''%}
{% block body %}
{% block fos_user_content %}
{% endblock fos_user_content %}
{% endblock body %}
That extends the app/Resourses/views/base.html.twig template:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{% block title %}Welcome!{% endblock %}</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% block stylesheets %}
<link rel="stylesheet" type="text/css" href="{{asset('assets/vendor/bootstrap/css/bootstrap.css')}}" >
<link rel="stylesheet" type="text/css" href="{{asset('assets/vendor/adminlte/adminlte.css')}}" >
<link rel="stylesheet" type="text/css" href="{{asset('assets/vendor/adminlte/skin-blue.css')}}" >
{% endblock %}
<link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
{% block javascriptsHeader %}
{% endblock %}
</head>
<body class="{{ classes }}">
{% block body %}
{% endblock body %}
{% block javascriptsFooter %}
{% endblock javascriptsFooter %}
</body>
</html>
The fields I want to render are the default and the very same that are provided via the default FosUserBundle's administrator form. I want to mess around with the html classes in order to achieve the same look from the template that is mentioned above.

A form theme is what you need.
You can either create a form theme and use it only in specific templates like your registration form:
{% form_theme form 'register-form-theme.html.twig' %}
{% trans_default_domain 'FOSUserBundle' %}
{{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register'}}) }}
{{ form_widget(form) }}
<div>
<input type="submit" value="{{ 'registration.submit'|trans }}" />
</div>
{{ form_end(form) }}
Or you can set a global form theme in config.yml:
# Twig Configuration
twig:
# ...
form_themes:
- 'form-theme.html.twig'
Your form theme then should extend the default div layout provided by symfony:
{% extends 'form_div_layout.html.twig' %}
You can then override the blocks from this template:
{# app/Resources/views/form-theme.html.twig #}
{% extends 'form_div_layout.html.twig' %}
{%- block form_start -%}
{% set attr = attr|merge({ 'class': (attr.class|default('') ~ ' custom classes')|trim }) %}
{{ parent() }}
{%- endblock form_start -%}
{%- block form_row -%}
<div class="custom classes">
{{- form_label(form) -}}
{{- form_widget(form) -}}
{{- form_errors(form) -}}
</div>
{%- endblock form_row -%}
{%- block form_widget_simple -%}
{% set attr = attr|merge({ 'class': (attr.class|default('') ~ ' custom classes')|trim }) %}
{{ parent() }}
{%- endblock form_widget_simple -%}

Related

Block [...] on template [...] does not exist

When updating from Symfony3.4 to Symfony4 and verifying the operation, the following error occurred.
When I examined the code, there was no definition in base.twig.html, but there was a definition in the file extending layout.html.
It seems that each is defined and used properly.
How should this be fixed?
Error
Block "contentBackIcon" on template "base.html.twig" does not exist.
layout.html.twig
{% extends 'base.html.twig' %}
{% block body %}
{{ block('contentBackIcon') }}
{% endblock %}
①index.html.twig
{% extends '#AppBundle/Sp/shop_layout.html.twig' %}
{# contentBackIcon #}
{% block contentBackIcon %}
{% if not modal %}
<a class="btn btn-link btn-nav pull-left" href="{{ path("app_shop_default_index")}}" data-ignore="push">
<span class="icon icon-left-nav"></span>
</a>
{% endif %}
{% endblock %}
②input.html.twig
{% extends '#AppBundle/Sp/shop_layout.html.twig' %}
{% block contentBackIcon %}
<a class="btn btn-link btn-nav pull-left" href="{{ path('app_shop_article_index', {"q": {"articleType": "coordinate"}}) }}" data-ignore="push">
<span class="icon icon-left-nav"></span>
</a>
{% endblock %}
Version
symfony v4.0.15
twig/twig 2.14.3
I added it to base.html.twig as below.
base.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}{% endblock %}
</head>
<body>
{% block body %}
//Add
{% block contentBackIcon %}{% endblock %}
{% endblock %}
{% block javascripts %}{% endblock %}
</body>
</html>

Symfony FileType customize

I'm trying to customize the rendering of the File Input in Symfony with twig.
plugins.krajee.com/file-basic-usage-demo
I follow the documentation : https://symfony.com/doc/current/form/form_customization.html
In my config.yml
# Twig Configuration
twig:
form_themes:
- 'bootstrap_3_layout.html.twig'
I try all methode...
1) Custome inside the the view in my view.html.twig (this is a copy past of the existing bootstrap layout, I just add class="file")
{% form_theme form _self %}
{% block _user_file_widget -%}
{% if type is not defined or type not in ['file', 'hidden'] %}
{%- set attr = attr|merge({class: (attr.class|default('') ~ ' form-control')|trim}) -%}
{% endif %}
{%- set type = type|default('text') -%}
<input class="file" type="file" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{%- endblock _user_file_widget %}
And in my FileType
$builder->add('imageFile', FileType::class, array(
'required' => false,
'label' =>false,
'block_name' => 'file',
));
That gives me an error
The merge filter only works with arrays or "Traversable", got "NULL" as first argument.
2) Create an external file
In Ressources/View/Form/fields.html.twig
{% block form_widget_simple -%}
{% if type is not defined or type not in ['file', 'hidden'] %}
{%- set attr = attr|merge({class: (attr.class|default('') ~ ' form-control')|trim}) -%}
{% endif %}
{%- set type = type|default('text') -%}
<input class="file" type="file" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{%- endblock form_widget_simple %}
And in the view
{% form_theme form 'form/fields.html.twig' %}
But all fields are customized...
3) Add class in the rendering in the view
{{ form_widget(form.imageFile, {'attr': {'class': 'file', 'type': 'file'} }) }}
And for this 2 last methods I get this:
I am open to all solution !
Thank you for your help.
I found it !
It's working as I want using kartik-v/bootstrap-fileinput.
After installation, I add some assetic in my config.yml
kartik_js:
inputs:
- "%kernel.root_dir%/../vendor/kartik-v/bootstrap-fileinput/js/fileinput.js"
- "%kernel.root_dir%/../vendor/kartik-v/bootstrap-fileinput/js/locales/fr.js"
- "%kernel.root_dir%/../vendor/kartik-v/bootstrap-fileinput/themes/explorer/theme.js"
kartik_css:
inputs:
- "%kernel.root_dir%/../vendor/kartik-v/bootstrap-fileinput/css/fileinput.min.css"
- "%kernel.root_dir%/../vendor/kartik-v/bootstrap-fileinput/themes/explorer/theme.css"
Then in the view I add the css and js
{% block stylesheets %}
{{ parent() }}
{% stylesheets '#kartik_css' combine=true %}
<link href="{{ asset_url }}" type="text/css" rel="stylesheet" />
{% endstylesheets %}
{% endblock %}
{% javascripts '#kartik_js' combine=true %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
The form widget
{{ form_widget(form.imageFile)}}
And the Javascrip
$("#fos_user_profile_form_imageFile").fileinput({
language: 'fr',
showUpload: false,
allowedFileExtensions: ['jpg', 'png', 'gif']
});
The Result !
Is Amazing
I hope this will help some one :)
Have a good day !

overrid FOS Bundle

I try to override FOS bundle.
To do this I have:
UserBundle that I have created when intalling FOS. It have my User.php file.
UserBundle.php:
<?php
namespace gestEntrSym\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class UserBundle extends Bundle
{
public function getParent() {
return 'FOSUserBundle';
}
}
views/Default/layout.html.twig
{% extends '::base.html.twig' %}
{% block title %}Acme Demo Application{% endblock %}
{% block content %}
{{ block('fos_user_content') }}
{% endblock %}
then I have app/Ressources/Views/base.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div>
{% if is_granted("IS_AUTHENTICATED_REMEMBERED") %}
{{ 'layout.logged_in_as'|trans({'%username%': app.user.username}, 'FOSUserBundle') }} |
<a href="{{ path('fos_user_security_logout') }}">
{{ 'layout.logout'|trans({}, 'FOSUserBundle') }}
</a>
{% else %}
{{ 'layout.login'|trans({}, 'FOSUserBundle') }}
{% endif %}
</div>
{% for type, messages in app.session.flashBag.all %}
{% for message in messages %}
<div class="{{ type }}">
{{ message|trans({}, 'FOSUserBundle') }}
</div>
{% endfor %}
{% endfor %}
<div>aaa
{{ block('fos_user_content') }}
</div>
</body>
</html>
I have now in the page just a link "Connexion", which just link to the page login. I want to have all the inputs in my layout page.
How can I do that?
Thanks
Best regards
If you want to override your login template, create the folder
app/Resources/FosUserBundle
and then respect the structure of the vendor folder which you won't toutch, so your overriden login wil be here :
app/Resources/FosUserBundle/Views/Security/login.html.twig
Then if you want to include that template in base,
{% include('FOSUserBundle:Security:login.html.twig') %}

Symfony2 Form Builder - Remove label, make it placeholder

I am playing with Symfony's form builder, and I can't find a way to not display a label. Further, I am interested in actually setting a placeholder for each input box. Is this possible? I have researched a bit and found nothing.
My form:
<form action="{{ path('searchPeople') }}" method="post" class="form-inline">
{{ form_errors(form) }}
{{ form_row(form.first_name) }}
{{ form_row(form.last_name) }}
{{ form_rest(form) }}
<br />
<button type="submit" class="btn btn-primary" /><i class="icon-search"></i>Search</button>
</form>
I know it's already answered, but might help somebody who is looking for a different solution for placeholders, if you don't want to change anything in your twig template:
$builder->add(
'name',
'text',
array(
'attr' => array(
'placeholder' => 'Your name',
),
'label' => false,
)
);
If you're outputting the field with form_rest you'll have to set the label for the the field to false in the form builder with something like
$builder->add('first_name', 'text', array(
'label' => false,
));
If you output the fields individually, you can omit the form_label for that field in the twig template, or set it to an empty string.
{{ form_label(form.first_name, '') }}
Convert label to placeholder
{% use 'form_div_layout.html.twig' with widget_attributes as base_widget_attributes %}
{% block widget_attributes %}
{% set attr = {'placeholder': label|trans({}, translation_domain)} %}
{{- block('base_widget_attributes') -}}
{% endblock widget_attributes %}
I did this recently! :) You'll want to create a new fields template, for form_row and one for form_widget. Then remove the form_label part, and add your placeholder.
http://symfony.com/doc/current/cookbook/form/form_customization.html
You can do it per field, or set it for all of them.
Or you can also skip the removing the form_label from the form_row template, and just do form_widget() where you're currently calling form_row()
for other that come across this label-question:
you could use form theme to override the form_row tag for every form you want. However I recommend to just set it invisible for page reader optimization. my example with bootstrap:
{% block form_row %}
{% spaceless %}
{{ form_label(form, null, {'label_attr': {'class': 'sr-only'}}) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
{% endspaceless %}
{% endblock form_row %}
don't forget to include your formtheme in config.yml and template.
For those NOT using form_row, you can always add the placeholder as an attribute directly when adding the input to the builder. Like so:
$task = new Task();
$form = $this->createFormBuilder($task)
->add('first_name', 'text', array(
'required' => true,
'trim' => true,
'attr' => array('placeholder' => 'Lorem Ipsum')
)->getForm();
Symfony 2.8 & above
Remove form_label
{% block form_row %}
<div>
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
Add placeholder attribute
{% block form_widget_simple %}
{% set type = type|default('text') %}
<input placeholder="{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}" type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endblock form_widget_simple %}
Expanding on Léo's answer:
{% use 'form_div_layout.html.twig' %}
{% block widget_attributes %}
{% spaceless %}
{% set attr = attr|merge({'placeholder': label}) %}
{{ parent() }}
{% endspaceless %}
{% endblock widget_attributes %}
trans filter has been removed because it is included in the parent.
You must render the form manually.
Here's an example:
<form id="form-message" action="{{ path('home') }}" method="post" {{ form_enctype(form) }}>
{{ form_label(form.name) }}
{% if form_errors(form.name) %}
<div class="alert alert-error">
{{ form_errors(form.name) }}
</div>
{% endif %}
{{ form_widget(form.name) }}
{{ form_row(form._token) }}
<input type="submit" class="btn" value="Submit">
</form>
Related documentation
To sums it up:
Titi's answer is the most simple ;
Mick, Léo & Quolonel's answers are the most effective but are incomplete (for symfony > 2.6) :
If you use the label_format option in your *Type::configureOptions, their solution does not work. You need to add the content of the form_label block to handle all the label possibilities.
The full & most effective answer (code used w/ symfony 3.3) :
Remove form_label
{% block form_row %}
<div>
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
Edit the widget_attribute block
{% block widget_attributes %}
{% spaceless %}
{% if label is not same as(false) -%}
{% if label is empty -%}
{%- if label_format is not empty -%}
{% set label = label_format|replace({
'%name%': name,
'%id%': id,
}) %}
{%- else -%}
{% set label = name|humanize %}
{%- endif -%}
{%- endif -%}
{% set attr = attr|merge({'placeholder': label}) %}
{%- endif -%}
{{ parent() }}
{% endspaceless %}
{% endblock widget_attributes %}
Notes :
Do not translate the labels into the widget_attributes block, otherwise they will appear as missing translations.
The solution does not work for checkboxes or radio buttons, you'll want to add something like :
{%- block checkbox_widget -%}
{{ parent() }}
{{- form_label(form) -}}
{%- endblock checkbox_widget -%}
Bootstrap Forms
In my case best is mix aswers of #Cethy and #Quolonel Questions
{% form_theme form _self %}
{% use 'bootstrap_4_layout.html.twig' %}
{% block widget_attributes %} {# set placeholder #}
{% spaceless %}
{% set attr = attr|merge({'placeholder': label}) %}
{{ parent() }}
{% endspaceless %}
{% endblock widget_attributes %}
{% block form_row %} {# remove label #}
<div class="form-group">
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
It looks the following
It works with translations
You can also copy the labels into the placeholder attribute before rendering the form:
$formView = $form->createView();
foreach($formView->getIterator() as $item) {
/** #var $item FormView */
if ($item->vars['label']) {
$item->vars['attr']['placeholder'] =$item->vars['label'];
}
}

Shortcuts with Symfony2 Twig forms : form_widget

I would like to replace:
{{ form_errors(form.name) }}
{{ form_widget(form.name, { 'attr': {'placeholder': 'Nom'} }) }}
By:
{{ form.name|field('Nom') }}
How could I do that? I tried to do it in a Twig extension but I don't have access to the form_widget function.
Edit: I could do it with the form.name properties (that include the parent form) but I would repeat symfony code, it would be a very ugly big hack
Makes more sense if you ask me to move the attr to your form class:
class SomeForm extends AbstractType {
//.....
$builder->add('name', 'text', array('attr' => array('placeholder'=>'Nom')));
}
Since i guess you need some custom rendering for some of your fields you can check:
http://symfony.com/doc/2.0/cookbook/form/form_customization.html#how-to-customize-an-individual-field
You could also create a new type and customize it as explained here:
http://symfony.com/doc/2.0/cookbook/form/form_customization.html#what-are-form-themes
You could even change the default way of rendering and ask symfony to render your placeholder tag by default using the field's label string (the details of enabling the form theme globally are covered by the link referenced above):
{% block text_widget %}
{% set type = type|default('text') %}
<input type="text" {{ block('widget_attributes') }} value="{{ value }}" />
{% endblock field_widget %}
{% block widget_attributes %}
{% spaceless %}
{% for attrname,attrvalue in attr %}{{attrname}}="{{attrvalue}}" {% endfor %} placeholder="{{ label|trans }}"
{% endspaceless %}
{% endblock widget_attributes %}
{% block form_row %}
{% spaceless %}
<div class="my-class">
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock form_row %}
So you would limit yourself to a form_row(form.name) using the theming that symfony provides.
Symfony's aproach looks "very" DRY/DIE to me.
Hope it helps.

Categories