my form 'Donacion' have a relationship with 'pajuela' OneToMany.
When i add 'Pajuela' with addTagForm, it is created, but if i submit the form and i do dump(formulario), the ArrayCollection 'pajuelas' is empty.
I have read the official documentation but not found my problem...
This is the link: https://symfony.com/doc/3.3/form/form_collections.html
This is my code:
# DonacionType
...
case 4:
$builder
->add('pajuelas',CollectionType::class, array(
'entry_type' => PajuelaType::class,
'entry_options' => array(
'tipo_sede' => $options['tipo_sede'],
'sede_id' => $options['sede_id'],
),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
))
->add('observacionesPajuelas', TextareaType::class)
;
break;
...
# PajuelaType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('tipo', ChoiceType::class, array(
'choices' => array(
'Completa' => 'Completa',
'Controles' => 'Controles'
)
))
;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Pajuela::class,
'tipo_sede' => null,
'sede_id' => null,
));
}
#Twig:
...
{% form_theme formulario _self %}
{% block _entidadbundle_donacion_pajuelas_entry_widget %}
{% if form is defined %}
{% if form.parent != null %}
<div class="form-group {% if form_errors(form.tipo) %}has-error{% endif %} col-lg-2 col-md-12 col-sm-12">
{% if form_errors(form.tipo) %}
{{ form_label(form.tipo, 'pajuela.tipo' | trans) }}
{{ form_widget(form.tipo, {'attr': {'class': 'form-control error'}}) }}
<label for="{{ form.tipo.vars.id }}"
class="error">{{ form_errors(form.tipo) }}</label>
{% else %}
{{ form_label(form.tipo, 'pajuela.tipo' | trans) }}
{{ form_widget(form.tipo, {'attr': {'class': 'form-control'}}) }}
{% endif %}
</div>
{% endif %}
{% endif %}
{% endblock %}
<div class="pajuelas" data-prototype="{{ form_widget(formulario.pajuelas.vars.prototype)|e('html_attr') }}">
{% for pajuela in formulario.pajuelas %}
<div class="row pajuela pajuela-persitida">{{ form_widget(pajuela) }}</div>
{% endfor %}
</div>
...
I can not find what is the problem that I am having.
Related
I try to insert images with relations OneToMany, but I get an error.
Expected argument of type "App\Entity\CategoryImage", "array" given at property path "images".
I have entities Category and CategoryImage:
/**
* #ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
*/
class Category
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\CategoryImage", mappedBy="category", orphanRemoval=true ,cascade={"persist", "remove"})
*/
private $images;
.......
}
/**
* #ORM\Entity(repositoryClass="App\Repository\CategoryImageRepository")
*/
class CategoryImage
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $path;
/** #var \SplFileInfo */
protected $file;
....
}
Two forms:
class CategoryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$data = $builder->getForm()->getData();
$builder
->add('name')
->add('parent',OptionType::class,[
'class'=>Category::class,
'selectType'=>'flatexcept',
'required'=>false,
])
->add('images',CollectionType::class,[
'entry_type' => ImageTypeMultiple::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
]);
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Category::class,
]);
}
}
class ImageTypeMultiple extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options )
{
$builder->add('file',FileType::class,[
'label'=>false,
'required'=>false,
'constraints' => [
new Image([
'maxSize' => '5M'
])
]
]);
}
public function getBlockPrefix()
{
return 'image_multiple';
}
}
My custom ImageTypeMultiple form_theme widget:
{% block image_multiple_widget -%}
{% spaceless %}
{% if form.vars.value.path|default(null) is null %}
<label for="{{ form.file.vars.id }}" class="image-upload btn btn-secondary btn-block"><i class="fa-cloud fa icon"></i> {{ 'select'|trans }}</label>
{% else %}
<img src="{{ form.vars.value.path|imagine_filter('sylius_small') }}" />
<label for="{{ form.file.vars.id }}" class="image-upload btn btn-secondary btn-block"><i class="fa-cloud fa icon"></i> {{ 'replace'|trans }}</label>
{% endif %}
<div class="d-none">
{{ form_widget(form.file) }}
</div>
<div class="element">
{{- form_errors(form.file) -}}
</div>
{% endspaceless %}
{% endblock %}
{% block collection_widget -%}
{% import _self as self %}
{% set attr = attr|merge({'class': attr.class|default ~ ' controls collection-widget'}) %}
{% spaceless %}
<div data-form-type="collection" {{ block('widget_container_attributes') }}
{% if prototype is defined and allow_add %}
data-prototype='{{ self.collection_item(prototype, allow_delete, 'Delete', '__name__')|e }}'
{%- endif -%}
>
{{ form_errors(form) }}
{% if prototypes|default is iterable %}
{% for key, subPrototype in prototypes %}
<input type="hidden" data-form-prototype="{{ key }}" value="{{ self.collection_item(subPrototype, allow_delete, button_delete_label, '__name__')|e }}" />
{% endfor %}
{% endif %}
<div data-form-collection="list" class="row">
{% for child in form %}
{{ self.collection_item(child, allow_delete, 'Delete', loop.index0) }}
{% endfor %}
</div>
{% if prototype is defined and allow_add %}
<a href="#" class="btn btn-primary" data-form-collection="add">
Add
</a>
{% endif %}
</div>
{% endspaceless %}
{%- endblock collection_widget %}
{% macro collection_item(form, allow_delete, button_delete_label, index) %}
{% spaceless %}
<div data-form-collection="item" data-form-collection-index="{{ index }}" class='col-lg-2 col-md-4 col-sm-6 imagetype_widget ml-3 mb-3' >
{{ form_widget(form) }}
{% if allow_delete %}
<a href="#" data-form-collection="delete" class="btn btn-warning btn-block">
<i class="fa fa-trash "></i>
Delete
</a>
{% endif %}
</div>
{% endspaceless %}
{% endmacro %}
My controller:
/**
* #Route("/{id}/edit", name="category_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Category $category): Response
{
$form = $this->createForm(CategoryType::class, $category);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
...}
}
I can open my edit page without error:
but after I select an image under images field and submit, it shows this error:
It shows
Expected argument of type "App\Entity\CategoryImage", "array" given at property path "images".
on the line $form->handleRequest($request) in the controller ,something goes wrong, I have been dealing with this problem for days, but cannot solve it.
I'm new to Symfony, I got a page in where I have a list of articles, and I created a form above it that allow me to filter the results of my query :
The form works fine, but when I click on the 2nd page of my paginator table, the form reset, so my filter is reset too. What I want is that we can filter results and be able to paginate the table, with the same filter, and that the form keep his data.
Here's my code right now :
Controller :
public function listeAction(Request $request, $page) {
if ($page < 1 && strlen($page) != 0) {
throw new NotFoundHttpException('Page "' . $page . '" inexistante.');
} else if (strlen($page) == 0) {
$page = 1;
}
$nbPerPage = 5;
$form = $this->createForm(ArticleRechercheType::class);
$form->setData(array('rds' => true));
//if we use filters
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$data = $form->getData();
$form = $this->createForm(ArticleRechercheType::class, $data);
if ($data['famille'] != null) {
$data['famille'] = $data['famille']->getId();
}
$listArticles = $this->getDoctrine()
->getManager()
->getRepository('GRBackOfficeBundle:Article')
->getFilteredArticles($page, $nbPerPage, $data);
} else {
$data = $form->getData();
$form = $this->createForm(ArticleRechercheType::class, $data);
$listArticles = $this->getDoctrine()
->getManager()
->getRepository('GRBackOfficeBundle:Article')
->getArticles($page, $nbPerPage);
}
$nbPages = ceil(count($listArticles) / $nbPerPage);
if ($nbPages != 0 && $page > $nbPages) {
throw new NotFoundHttpException('Page "' . $page . '" inexistante.');
}
if ($nbPages == 0) {
$nbPages = 1;
}
return $this->render('GRBackOfficeBundle:Article:liste_articles.html.twig', array(
'form' => $form->createView(),
'listArticles' => $listArticles,
'nbPages' => $nbPages,
'page' => $page
));
}
Form :
class ArticleRechercheType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('famille', EntityType::class, array(
'class' => 'GRBackOfficeBundle:Famille',
'choice_label' => 'nom',
'required' => false
))
->add('rds', CheckboxType::class, array('required' => false))
->add('recherche', TextType::class, array('required' => false))
->add('Rechercher', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'translation_domain' => false
));
}
}
View :
{% extends "GRBackOfficeBundle::layout.html.twig" %}
{% block title %}
Liste des articles
{% endblock %}
{% block gr_bo_body %}
<h2>Liste des articles</h2>
<div class="row">
<div class="well row">
{{ form_start(form) }}
{{ form_errors(form) }}
<div class="form-group col-md-2">
{{ form_label(form.famille, "Famille d'article", {'label_attr': {'class': 'control-label'}}) }}
{{ form_errors(form.famille) }}
{{ form_widget(form.famille, {'attr': {'class': 'form-control'}}) }}
</div>
<div class="form-group col-md-4">
{{ form_widget(form.rds, {'attr': {'class': ''}}) }}
{{ form_label(form.rds, "Montrer les articles en rupture de stock", {'label_attr': {'class': 'control-label'}}) }}
{{ form_errors(form.rds) }}
</div>
<div class="form-group col-md-3">
{{ form_label(form.recherche, "Recherche", {'label_attr': {'class': 'control-label'}}) }}
{{ form_errors(form.recherche) }}
{{ form_widget(form.recherche, {'attr': {'class': 'form-control'}}) }}
</div>
<div class="form-group col-md-3" style="text-align: center">
{{ form_widget(form.Rechercher, {'attr': {'class': 'btn btn-primary'}}) }}
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
<div class="well row">
<table class="table table-bordered table-striped" id="listeArticles" style="width: 100%" cellspacing="0">
<thead>
<tr>
<th>Référence client</th>
<th>Référence interne</th>
<th>Famille</th>
<th>Libellé</th>
<th>Alerte</th>
<th>Stock</th>
</tr>
</thead>
<tbody id="bodyListeArticles">
{% for article in listArticles %}
<tr>
<td>{{ article.RefArticle }}</td>
<td>{{ article.RefLogistique }}</td>
<td>{{ article.famille.nom }}</td>
<td>{{ article.libelle }}</td>
<td>{{ article.StockAlerte }}</td>
<td>{{ article.StockActuel }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if nbPages > 1 %}
<ul class="pagination">
{% for p in range(1, nbPages) %}
<li {% if p == page %} class="active"{% endif %}>
{{ p }}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
</div>
{% endblock %}
If anyone have an idea of how I can do that, that will be appreciated
You can use a bundle (like the knp paginator bundle for exemple), or put your args in session. But the bundle will make it simple as it does everything for you, you just have to pass your datas
To validate a form I am using a standard:
{{ form_widget(form.save, {'attr': {'class': 'btn btn-sm btn-danger'}, 'label': 'Submit form'}) }}
I want to insert a fontawsome icon in the button. I tried:
{{ form_widget(form.save, {'attr': {'class': 'btn btn-sm btn-danger'}, 'label': '<i class="fa fa-envelope-o"></i> Submit form'}) }}
But it is not working; obviously
Any idea how to that?
I would define a new form template in the same view (or in a template if you need to reuse the code). More details here
{% extends '::base.html.twig' %}
{% form_theme form _self %}
{%- block submit_widget -%}
{%- set type = type|default('submit') -%}
{%- 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 -%}
<button type="{{ type|default('button') }}" {{ block('button_attributes') }}>
<i class="fa fa-envelope-o"></i>
{{ label|trans({}, translation_domain) }}
</button>
{%- endblock submit_widget -%}
{% block content %}
{# ... render the form #}
{{ form_row(form.age) }}
{% endblock %}
EDIT
You can also extend ButtonType to allow icon_before and icon_after in order to add icons easily in form definition :
$form->add('submitReportV2Show', SubmitType::class, array(
'label' => 'My test',
'icon_before' => 'fa-refresh',
'icon_after' => 'fa-refresh',
'attr' => array('class' => 'btn btn-sm btn-success'
)));
Create a new class src/bundle/Form/Extension:
namespace YourBundle\ToolBoxBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
class IconButtonExtension extends AbstractTypeExtension
{
public function getExtendedType()
{
return ButtonType::class;
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['icon_before'] = $options['icon_before'] ?? '';
$view->vars['icon_after'] = $options['icon_after'] ?? '';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'icon_before' => null,
'icon_after' => null
]);
}
}
Declare it in service src/bundle/Resources/config/service.yml
bundle.tools.form.type_extension.icon_button:
class: YourBundle\ToolBoxBundle\Form\Extension\IconButtonExtension
tags:
- { name: 'form.type_extension', extended_type: 'Symfony\Component\Form\Extension\Core\Type\ButtonType' }
app/Resources/views/Form/fields.html.twig
{%- block button_widget -%}
{%- if label is empty -%}
{%- if label_format is not empty -%}
{% set label = label_format|replace({
'%name%': name,
'%id%': id,
}) %}
{%- elseif label is same as(false) -%}
{% set translation_domain = false %}
{%- else -%}
{% set label = name|humanize %}
{%- endif -%}
{%- endif -%}
<button type="{{ type|default('button') }}" {{ block('button_attributes') }}>
{% if icon_before is defined and icon_before is not null %}
<i class="fa {{ icon_before }}"></i>
{% endif %}
{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}
{% if icon_after is defined and icon_after is not null %}
<i class="fa {{ icon_after }}"></i>
{% endif %}
</button>
{%- endblock button_widget -%}
sdespont's answer is the correct answer and worthy of being selected. I have, however, extended the functionality of it to include adding the custom fa class icon as well as whether the icon is placed to the left or right of the button text.
Since this functionality accepts variables the best thing to do is to create a template to be reused instead of customising just the view.
Form template: app/Resources/views/form/submit.html.twig
{# app/Resources/views/form/submit.html.twig #}
{% block submit_widget %}
{% set type = type|default('submit') %}
{% 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 %}
<button type="{{ type|default('button') }}" {{ block('button_attributes') }}>
{% if fa is defined %}
{% if left is defined and left %}
<i class="fa {{ fa }}"></i>
{% endif %}
{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}
{% if right is defined and right %}
<i class="fa {{ fa }}"></i>
{% endif %}
{% else %}
{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}
{% endif %}
</button>
{% endblock submit_widget %}
Controller:
$form = $this->createFormBuilder($user)
...
->add('submit', SubmitType::class, array(
'attr'=> array('class'=>'myclass')
))
->getForm();
Twig template:
{{ form_widget(form.submit, {'fa' : 'fa-long-arrow-right','right' : true}) }}
You can set any old fa icon and even sizing like so: fa-long-arrow-right fa-2x
The easiest, you can put your button with html and form vars:
<button type="submit" name="{{ form.send.vars.full_name }}" id="{{ form.send.vars.id }}" class="btn btn-sm btn-danger"><i class="fa fa-envelope-o"></i></button><
You can just add a new custom service css class per icon
/*
* css selector for a class attribute that starts with "btn-fa-" or has " btn-fa-" in it:
*/
[class^="btn-fa-"]:before,
[class*=" btn-fa-"]:before
{
font-family: "Font Awesome 5 Free";
font-weight: bold;
margin: 0 6px 0 2px;
}
/*
* And then only 1 setting per font awesome class
*/
.btn-fa-plus:before {
content: '\f067';
}
And add the class to the ButtonType
->add('Add an item', ButtonType::class, [
'attr' => [
'class' => 'btn btn-primary btn-fa-plus',
]
])
In YourFormType.class -> buildForm
->add('submit', SubmitType::class, [
'attr' => [
'class' => 'main-btn primary-btn',
],
'label' => '<i class="fas fa-search"></i> Search',
'label_html' => true,
])
I have this
{% block form_row %}
<div class="form-group">
{{ form_label(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
Its used to override the main Twig form fields.
But I need the label to be different depending on the type of form field that is being rendered.
How can I get that here and then call something else instead of form_label ?
I essentially want to be able to do this, this is because the label it would appear comes after the input for checkboxes, but I want to reverse this / customise it.
{% block form_row %}
<div class="form-group">
{% if(type is checkbox) %}
// checkbox label here
{% else %}
{{ form_label(form) }}
{% endif %}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
You can override the blocks that are used to render a specific form type.
For example, if you want to override the label template of an email input, you should override the email_label block:
{% block email_label %}
This is the template used for all email input
{% endblock %}
{% block form_label %}
This is the fallback template for all other input types
{% endblock %}
You can check which blocks you can override for a specific form view by looking into form.vars.block_prefixes.
For example, for a "personnal_email" field of type "email", it'll contain :
array:4 [▼
0 => "form"
1 => "text"
2 => "email"
3 => "_form_personnal_email"
]
which mean you can override blocks (starting with the less specific one) form_(widget|label|error), text_(widget|label|error), email_(widget|label|error) and _form_personnal_email_(widget|label|error) (the last one is usefull to override the rendering of a very specific field).
Does it answer your question?
UPDATE
here's what you have to do:
{% block form_row %}
<div class="form-group">
{{ form_label(form) }}
{{ form_widget(form) }}
</div>
{% endblock %}
{% block checkbox_label %}
<!-- Your checkbox specific label -->
{% endblock %}
You cannot access type in the form_row block as it's only defined in sub blocks of form_widget (see here for example)
You can use custom format:
<div class="form-group">
{{ form_label(form.your_value, 'Your Title of field', { 'label_attr': {'class': 'col-sm-3 control-label'} }) }}
<div class="col-sm-9">
{{ form_widget(form.your_value, { 'attr': {'class': 'form-control selectJS'} }) }}
</div>
</div>
or you can use FormType (if you generate entity, this is file in Form folder), like a:
<?php
namespace Ens\YourBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class NoticeType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title','text', array(
'label'=>'Title',
'label_attr'=>array( 'class'=>'col-sm-3 control-label' ),
'attr'=>array( 'class'=> 'form-control')
))
->add('text', 'textarea', array(
'label'=>'Text',
'label_attr'=>array( 'class'=>'col-sm-3 control-label' ),
'attr'=>array( 'class'=> 'form-control')
))
->add('keep_on_top','checkbox', array(
'label'=>'Keep on top',
'required'=>false
))
->add('start', 'date', array(
'attr'=>array( 'class'=> 'hidden')
))
->add('end', 'date', array(
'attr'=>array( 'class'=> 'hidden')
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ens\YourBundle\Entity\Notice'
));
}
/**
* #return string
*/
public function getName()
{
return 'notice';
}
}
I have such problem with symfony2.
I have base.html.twig and this base is the template for others twigs.
I want to render controller, which contains form with locale-type input field.
The form will be used to change language of site.
My LanguageController:
<?php
namespace Soczewki\PlatformaBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class LanguageController extends Controller {
public function createAction(Request $Request)
{
$form = $this->createFormBuilder()
->setMethod('POST')
->setAction(null)
->add('locale', 'locale', array(
'label' => ' ',
'choices' => array('pl' => 'Polski', 'de' => 'Deutsch', 'en' => 'English'),
'data' => $this->getRequest()->getLocale(),
'required' => true))
->add('submit', 'submit')
->getForm();
$form->handleRequest($Request);
if($form->isValid()) {
$this->getRequest()->setLocale('en');
}
return $this->render("SoczewkiPlatformaBundle::myForm.html.twig",
array(
'form' => $form->createView(),
'req' => $r
));
}
}
The whole base.html.twig:
<html>
<head>
<title>{% block pageTitle %}{% endblock %}</title>
{#js#}
<script src="{{ asset('bundles/soczewkiplatforma/js/jquery.js') }}"></script>
<script src="{{ asset('bundles/soczewkiplatforma/js/bootstrap.js') }}"></script>
{#/js#}
{% block stylesheets %}
<link href="{{ asset('bundles/soczewkiplatforma/css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ asset('bundles/soczewkiplatforma/css/my-style.css') }}" rel="stylesheet">
{% endblock stylesheets %}
</head>
<body>
{% if app.security.getToken().getUser().getAuthKey() is defined %}
{% if app.security.getToken().getUser().getAuthKey() is not empty %}
{% set diff = ( app.security.getToken().getUser().getEndDate()|date('U') - "now"|date('U') ) / 3600 %}
<div style="width: 300px; height: 140px; position: absolute; bottom: 90px; right: 50px;" class="alert alert-danger alert-error">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<strong>Uwaga!</strong> Twoje konto nadal nie zostało aktywowane!<br />
Pozostało Ci: <span class="badge">{{ diff[0:2] }} godzin {{ ( diff[3:] * 60 )[0:2] }} minut </span>
<br /><br />
<button type="button" class="btn btn-danger">Wpisz kod</button>
<button type="button" class="btn btn-default" data-dismiss="alert">Zamknij</button>
</div>
{% endif %}
{% set hasParams = app.request.get('id') %}
{% if hasParams is empty %}
{% set currentPath = url( app.request.attributes.get( '_route', app.request.attributes.get('_route_params'))) %}
{% else %}
{% set currentPath = url( app.request.attributes.get( '_route', app.request.attributes.get('_route_params')),{'id': 0} ) %}
{% endif %}
{% set dirs = currentPath|split('/') %}
{% set flag = "" %}
{% set url = "" %}
<ol class="breadcrumb">
<li>Główna</li>
{% for key, dir in dirs %}
{% if url is not empty %}
{% set url = url ~ '/' ~ dir %}
{% else %}
{% set url = url ~ dir %}
{% endif %}
{% if flag == true %}
{% if '=' in dir %}
{% set _temp = dir|split('=') %}
{% else %}
{% set _temp = dir|split(' ') %}
{% endif %}
{% if key + 1 == dirs|length %}
<li class="active"> {{ _temp[0]|capitalize|replace('-',' ') }} </li>
{% else %}
<li> {{ _temp[0]|capitalize|replace('-',' ') }} </li>
{% endif %}
{% endif %}
{% if dir == 'app_dev.php' %}
{% set flag = true %}
{% endif %}
{% endfor %}
<li class="dropdown" style="float: right !important;">
Zalogowano jako: {{ app.security.getToken().getUser().getName() }} <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Moje konteło</li>
<li>Wyloguj</li>
</ul>
</li>
</ol>
{% else %}
<ol class="breadcrumb">
<li>Główna</li>
<!--- logowanie --->
<li class="dropdown" style="float: right !important;">
Zaloguj <span class="caret"></span>
<div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px; left: -200px;">
<form action="{{ path('login_check') }}" method="post">
<label for="username">Email/NIP:</label>
<input type="text" id="username" name="_username" />
<br />
<label for="password">Hasełko:</label>
<input type="password" id="password" name="_password" />
<br /><br />
<button type="submit">Loguj do Afganistanu</button>
</form>
</div>
</li>
<!--- log ---->
</ol>
{% endif %}
{{ render(controller('SoczewkiPlatformaBundle:Language:create')) }}
{% block pageContainer %}
{% endblock %}
</body>
</html>
Nothing shows and I get too any error.
Why is it like that?
// codes updated
myForm.html.twig:
{{ dump(req) }}
{{ form(form) }}
and LocaleListener.php:
<?php
namespace Soczewki\PlatformaBundle\Translations;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'pl')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
You have created a situation where you are calling the same method an infinite amount of times until the page just dies.
You original base is being rendered which is in the end rendering the SoczewkiPlatformaBundle::base.html.twig template. Within this template a render() is calling an action that is then rendering the SoczewkiPlatformaBundle::base.html.twig template, which then calls the render(), which then render SoczewkiPlatformaBundle::base.html.twig, and on and on...
You need to specify a template for the form to be rendered in rather than the base and then call that in your changeAction.
For example...
Soczewki\PlatformaBundle\Controller\LanguageController
public function changeAction(Request $Request)
{
// ..
return $this->render("SoczewkiPlatformaBundle:Locale:change_form.html.twig",
array(
'form' => isset($form) ? $form->createView() : null,
));
}
SoczewkiPlatformaBundle:Locale:change_form.html.twig
{{ form_start(form, {'method': 'POST', 'action': 'your_locale_change_route' }) }}
{{ form_row(form.locale) }}
{{ form_end(form) }}
Your next problem would be that your changeAction isn't actually performing an action (apart from creating a form), although you may just be wanting that page to show before you get to that part.
You need to add this code where you want that the form appear
{{ form(form) }}
Edited after the comments below;
Create a file named myForm.html.twig and put in SoczewkiPlatformaBundle;
Now write this code inside:
{{ form(form) }}
now your controller should be:
public function changeAction(Request $Request)
{
$form = $this->createFormBuilder()
->add('locale', 'locale', array(
'label' => 'user.locale',
'required' => true,
'choices' => array('en' => 'English', 'de' => 'Deutsch', 'pl' => 'Polish')
))
->getForm();
$form->handleRequest($Request);
return $this->render("SoczewkiPlatformaBundle::myForm.html.twig",
array(
'form' => $form->createView(),
));
}