Unable to render the form because the block names array contains duplicates - symfony

i'm using Symfony 3.3.9 and when I'm trying to render a form I have the following error:
An exception has been thrown during the rendering of a template
("Unable to render the form because the block names array contains
duplicates: "_fos_user_registration_form_errors", "user_errors",
"user_errors", "fos_user_registration_errors", "form_errors".").
Thank you in advance for your help !
EDIT 17/09/2017
Here you go:
public function indexAction()
{
/** #var $formFactory FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
$form = $formFactory->createForm();
return $this->render('AppTMMainBundle:Default:index.html.twig', array(
'form' => $form->createView(),
));
}
My Twig:
{{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register')}) }}
<div class="card-content">
<h3 class="text-center title" style="color: #3C4858;margin:10px 0;">Inscription</h3>
<div class="social text-center">
<a class="btn btn-just-icon btn-round btn-facebook" href="{{ path('hwi_oauth_service_redirect',{'service': 'facebook'}) }}">
<i class="fa fa-facebook"> </i>
</a>
<a class="btn btn-just-icon btn-round btn-twitter" href="{{ path('hwi_oauth_service_redirect',{'service': 'twitter'}) }}">
<i class="fa fa-twitter"></i>
</a>
<a class="btn btn-just-icon btn-round btn-google" href="{{ path('hwi_oauth_service_redirect',{'service': 'google'}) }}">
<i class="fa fa-google-plus"></i>
</a>
</div>
<p class="description text-center">Ou de façon plus classique</p>
<div class="row">
<div class="col-xs-6">
{{ form_label(form.firstname) }}
{{ form_widget(form.firstname) }}
</div>
<div class="col-xs-6">
{{ form_label(form.lastname) }}
{{ form_widget(form.lastname) }}
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ form_label(form.email) }}
{{ form_widget(form.email) }}
</div>
</div>
<div class="row">
<div class="col-xs-6">
{{ form_widget(form.plainPassword.first, {'attr': {'class': 'form-control', 'placeholder': 'form.password'}}) }}
</div>
<div class="col-xs-6">
{{ form_widget(form.plainPassword.second, {'attr': {'class': 'form-control', 'placeholder': 'form.password_confirmation'}}) }}
</div>
</div>
<!-- If you want to add a checkbox to this form, uncomment this code -->
<div class="input-group">
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes" checked="">
{{ 'index.proceed.agree'|trans }} {{ 'index.proceed.cgu'|trans }}.
</label>
</div>
</div>
<div class="footer text-center">
<input type="submit" class="btn btn-primary btn-round" value="{{ 'index.action.subscribe'|trans }}">
</div>
</div>
{{ form_end(form) }}

for anyone having such an exception:
You probably shouldn't extend a form type, but instead create your own and use getParent to inherit the behaviour.
And if your class name is the same as an other type (excluding namespaces)
you must override the getBlockPrefix from AbstractType.
The getBlockPrefix method from AbstractType uses the last part of fqcn (the class name) and you could have a duplicate block name.

I found the answer to my question.
That was from my RegistrationType class where I was trying to extends with another Type Class. getParent not working as well expected...
RegistrationType > UserType > FOS\UserBundle\Form\Type\RegistrationFormType
I move all fields from UserType in RegistrationType and it's working :)

Related

Django/CSS Icon and form input in same column

I am having a problem putting icon from font awesome and form input in the same column.
<div class="form-group">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.media }}
<div class="row pt-3">
<i class="fa fa-user fa-lg">{{ form.username }}</i>
</div>
</form>
</div>
With the code above, it looks a screenshot bellow:
I would like to look like the image bellow:
Thank you for your help.
It's better to deal with boxes with flexbox rather than row for more alignment flexibility.
Try the following code
<div class="form-group">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.media }}
<div class="d-flex pt-3">
<i class="fa fa-user fa-lg mr-2 "></i>{{ form.username }}
</div>
</form>
</div>

Call JavaScript function from Twig (symfony 5)

I'm working on a Symfony5 project and I want to call a JavaScript function and pass an Ajax Request (which I get from a controller) from a Twig.
i create a function phoneverif() in order to do some verification before the validation of form ..like doing a test if the fields are blanks then an alert will appears also the verification of the existence of data in db.
But a first, very simple test already failed, and an error appear :
Uncaught ReferenceError: phoneverif is not defined
onclick http://localhost:8000/super_admin/telephone/nouveau:1
here is my twig code :
{% extends 'superadmin.html.twig'%}
{% block body %}
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Nouveau téléphone</h1>
</div>
<div class="col-md-12">
{% for flashMessage in app.session.flashbag.get('notice') %}
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>{{ flashMessage }}</h4>
</div>
{% endfor %}
<!-- general form elements -->
<div>
<!-- form start -->
{{ form_start(form)}}
<div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>{{ form_label(form.userGroup) }}</label>
{{ form_widget(form.userGroup) }}
<span class="text-danger">{{ form_errors(form.userGroup) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.protocol) }}</label>
{{ form_widget(form.protocol) }}
<span class="text-danger">{{ form_errors(form.protocol) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.extension) }}</label>
{{ form_widget(form.extension) }}
<span class="text-danger">{{ form_errors(form.extension) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.dialplanNumber) }}</label>
{{ form_widget(form.dialplanNumber) }}
<span class="text-danger">{{ form_errors(form.dialplanNumber) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.voicemailId) }}</label>
{{ form_widget(form.voicemailId) }}
<span class="text-danger">{{ form_errors(form.voicemailId) }}</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>{{ form_label(form.login) }}</label>
{{ form_widget(form.login) }}
<span class="text-danger">{{ form_errors(form.login) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.pass) }}</label>
{{ form_widget(form.pass) }}
<span class="text-danger">{{ form_errors(form.pass) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.confSecret) }}</label>
{{ form_widget(form.confSecret) }}
<span class="text-danger">{{ form_errors(form.confSecret) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.serverIp) }}</label>
{{ form_widget(form.serverIp) }}
<span class="text-danger">{{ form_errors(form.serverIp) }}</span>
</div>
</div>
</div>
</div>
<div>
<button type="button" class="btn btn-primary" onclick="phoneverif();">Ajouter</button>
<a class="btn btn-warning" href="{{ path('Les_telephones') }}">Retour</a>
</div>
{{ form_end(form)}}
</div>
</div>
</div>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}"></script>
<script type="text/javascript">
function phoneverif() {
if ($("#telephone_extension").val() == '') {
alert('Vous devez saisir une extension');
} else {
if ($("#telephone_dialplanNumber").val() == '') {
alert('Vous devez saisir le dialplan du téléphone');
} else {
if ($("#telephone_login").val() == '') {
alert('Vous devez saisir le login du téléphone');
} else {
if ($("#telephone_pass").val() == '') {
alert('Vous devez saisir le mot de passe du téléphone');
} else {
$.ajax({
type: 'get',
url: Routing.generate('phone_verif', {extension: $("#telephone_extension").val()}),
success: function (data) {
if (data.existe == 1) {
alert('Téléphone non valide');
} else {
$("form").submit();
}
},
error: function() { alert('Erreur lors de l'appel AJAX'); }
});
}
}
}
}
}
</script>
{% endblock %}
function verifphone :
public function Phoneverif1(Request $request , $extension){
if ($request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$phone = $em->getRepository(Phones::class)->findOneByExtension($extension);
if ($phone) {
$existe = 1;
} else {
$existe = 0;
}
$response = new JsonResponse();
return $response->setData(array('existe' => $existe));
} else {
throw new \Exception('Erreur');
}
}
my fosjsrouting configuration :
config/packages/routing.yaml:
framework:
router:
utf8: true
# Configure how to generate URLs in non-HTTP contexts, such as CLI commands.
# See https://symfony.com/doc/current/routing.html#generating-urls-in-commands
#default_uri: http://localhost
fos_js_routing:
routes_to_expose: [ phone_verif ]
config/routes/fos_js_routing.yaml:
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
routes.yaml :
verification_telephone:
path: /verification/phone/{extension}
controller: App\Controller\TelephoneController::Phoneverif1
options:
expose: true
Rename the function and try again
I solved this problem by renaming the function. You try too.
Phoneverif1()
{% extends 'superadmin.html.twig'%}
{% block body %}
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Nouveau téléphone</h1>
</div>
<div class="col-md-12">
{% for flashMessage in app.session.flashbag.get('notice') %}
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>{{ flashMessage }}</h4>
</div>
{% endfor %}
<!-- general form elements -->
<div>
<!-- form start -->
{{ form_start(form)}}
<div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>{{ form_label(form.userGroup) }}</label>
{{ form_widget(form.userGroup) }}
<span class="text-danger">{{ form_errors(form.userGroup) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.protocol) }}</label>
{{ form_widget(form.protocol) }}
<span class="text-danger">{{ form_errors(form.protocol) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.extension) }}</label>
{{ form_widget(form.extension) }}
<span class="text-danger">{{ form_errors(form.extension) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.dialplanNumber) }}</label>
{{ form_widget(form.dialplanNumber) }}
<span class="text-danger">{{ form_errors(form.dialplanNumber) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.voicemailId) }}</label>
{{ form_widget(form.voicemailId) }}
<span class="text-danger">{{ form_errors(form.voicemailId) }}</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>{{ form_label(form.login) }}</label>
{{ form_widget(form.login) }}
<span class="text-danger">{{ form_errors(form.login) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.pass) }}</label>
{{ form_widget(form.pass) }}
<span class="text-danger">{{ form_errors(form.pass) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.confSecret) }}</label>
{{ form_widget(form.confSecret) }}
<span class="text-danger">{{ form_errors(form.confSecret) }}</span>
</div>
<div class="form-group">
<label>{{ form_label(form.serverIp) }}</label>
{{ form_widget(form.serverIp) }}
<span class="text-danger">{{ form_errors(form.serverIp) }}</span>
</div>
</div>
</div>
</div>
<div>
<button type="button" class="btn btn-primary" onclick="Phoneverif1()">Ajouter</button>
<a class="btn btn-warning" href="{{ path('Les_telephones') }}">Retour</a>
</div>
{{ form_end(form)}}
</div>
</div>
</div>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}"></script>
<script type="text/javascript">
function Phoneverif1() {
if ($("#telephone_extension").val() == '') {
alert('Vous devez saisir une extension');
} else {
if ($("#telephone_dialplanNumber").val() == '') {
alert('Vous devez saisir le dialplan du téléphone');
} else {
if ($("#telephone_login").val() == '') {
alert('Vous devez saisir le login du téléphone');
} else {
if ($("#telephone_pass").val() == '') {
alert('Vous devez saisir le mot de passe du téléphone');
} else {
$.ajax({
type: 'get',
url: Routing.generate('phone_verif', {extension: $("#telephone_extension").val()}),
success: function (data) {
if (data.existe == 1) {
alert('Téléphone non valide');
} else {
$("form").submit();
}
},
error: function() { alert('Erreur lors de l'appel AJAX'); }
});
}
}
}
}
}
</script>
{% endblock %}

Removing form_start from twig views Symfony3.4

In order to customize the views of the new user page, I need to remove the elements {{ form_start(form) }} and {{ form_end(form) }} from my twig template new.html.twig. It lets the page unorganized. Unfortunately, when I delete it, the insert new user don't display.
here is my twig code new.html.twig :
<div class="content">
{{ form_start(form) }}
<form class="form-horizontal group-border-dashed" action="#" style="border-radius: 0px;">
<div class="form-group">
<label class="col-sm-3 control-label">
Username
</label>
<div class="col-sm-6">
{{ form_widget(form.username, { 'attr': {'class': 'form-control','placeholder':'Username'}} ) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">
EMAIL
</label>
<div class="col-sm-6">
{{ form_widget(form.email, { 'attr': {'class': 'form-control','placeholder':'EMAIL '}} ) }}
</div>
</div>
<--! and so on -->
{{ form_widget(form) }}
<input type="submit" value="Create" />
{{ form_end(form) }}
<ul>
<li>
Back to the list
</li>
</ul>
</form>
</div>
Is there a way to remove the form_start and form_end from my twig
have you consider using the options of form_start?
like this :
form_start(form, 'attr':{ 'class':'form-horizontal group-border-dashed', 'style': 'border-radius: 0px;'})
you'll be able to remove the <form> but keep a concitent templating
note that the style should'nt be in your html page but in your css file. If you're using bootstrap you have access to this :
<span class="rounded-0"></span>
PS : if you fully template your form, you won't have access to the individual errors of each form that are autogenerated by symfony. read this page for more info.
post edit
I have edited your question to see it more clearly and new questions arised.
why are you using the form_widget(form) if you create all the element by yourself ?
you forgot the form_rest(form)that create the hidden csrf token (essential for security) and finnaly if you want to keep your <ul> inside the form why closing the form with form_end(form) before ?

Twig `Variable does not exist` error despite it not being printed

I'm trying to handle non existing variables in my controller which if the database is empty will return a view without any variables:
if(!$votes->findOneById(1) || !$images->findOneById(1)){
return $this->render('admin/stats_and_images.html.twig');
}
return $this->render('admin/stats_and_images.html.twig', [
'images' => $images->countVotesForAllImages(),
'image_podium' => $images->getTopNImages(3),
'form' => $form->createView(),
'votesToday' => $votes->votesToday(),
'votesMonth' => $votes->votesMonth(),
'votesTotal' => $votes->votesTotal()
]);
And in my view I'm trying to handle the lack of variables like so:
{% if (votesTotal[0][1] is defined) and (votesToday[0][1] is defined) and (votesMonth[0][1] is defined) %}
<div class="col-md-6">
<h4 class="sub-section--header">Liczba Oddanych Głosów:</h4>
<hr>
<p>
<div class="col-sm-6">
Dzisiaj:
<span class="text-info large-num">{{ votesToday[0][1] }}</span>
</div>
<div class="col-sm-6">
Ten miesiąc:
<span class="text-info large-num">{{ votesMonth[0][1] }}</span>
</div>
</p>
<p>
<strong>Głosów ogółem: </strong><span class="text-info large-num">{{ votesTotal[0][1] }}</span>
</p>
</div>
<div class="col-md-6">
<h4 class="sub-section--header">Wygrywające zdjęcia:</h4>
<p class="text-muted">Ten miesiąc</p>
<hr>
<div class="row text-center">
<div class="col-md-4">
<a
href="{{ asset("uploads/"~image_podium[0][0].fileName) }}"
target="blank">
<img
src="{{ asset("uploads/"~image_podium[0][0].fileName) | imagine_filter('my_thumb') }}" alt="{{image_podium[0][0].title}}"
class="site-thumbnail"
title="{{image_podium[0][0].title}} - {{image_podium[0][0].author}}">
</a>
<p><strong>Głosów: {{image_podium[0]['votes']}}</strong></p>
</div>
<div class="col-md-4">
<a
href="{{ asset("uploads/"~image_podium[1][0].fileName) }}"
target="blank">
<img
src="{{ asset("uploads/"~image_podium[1][0].fileName) | imagine_filter('my_thumb') }}" alt="{{image_podium[1][0].title}}"
class="site-thumbnail"
title="{{image_podium[1][0].title}} - {{image_podium[1][0].author}}">
</a>
<p>Głosów: {{image_podium[1]['votes']}}</p>
</div>
<div class="col-md-4">
<a
href="{{ asset("uploads/"~image_podium[2][0].fileName) }}"
target="blank">
<img
src="{{ asset("uploads/"~image_podium[2][0].fileName) | imagine_filter('my_thumb') }}" alt="{{image_podium[2][0].title}}"
class="site-thumbnail"
title="{{image_podium[2][0].title}} - {{image_podium[2][0].author}}">
</a>
<p>Głosów: {{image_podium[2]['votes']}}</p>
</div>
</div>
</div>
{% else %}
<h2 class="text-danger text-center">
No votes at the moment :)
</h2>
{% endif %}
But still despite the strict requirement of all three fields to be defined I'm getting this:
Variable "votesToday" does not exist.
And pointing to the <span class="text-info large-num">{{ votesToday[0][1] }}</span> portion of the view.
Why would this be happening? How can it be avoided?
send $votes to twig and check it with {{ dump(votes) }}
If it is a doctrine entity, check your getter. Perhaps is $votes->getVotesToday()

how to override ProfileFormType to edit users? symfony2

I'm working with symfony2.I'm using FOSUserBundle, so i want to override FormType of edit user to add name to builder. so how i should do it?
what i've did :
ProfileFormType :
<?php
namespace UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseType;
class ProfileFormType extends BaseType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
// add your custom field
$builder->add('name')
->add('roles', 'collection', array(
'type' => 'choice',
'options' => array(
'choices' => array(
'ROLE_ADMIN' => 'Admin'))))
->add('image', new ImageType())
;
}
public function getName() {
return 'user_edit_profile';
}
}
services.yml
user.edit.form.type:
class: UserBundle\Form\Type\ProfileFormType
arguments: [%fos_user.model.user.class%]
tags:
- { name: form.type, alias: user_edit_profile }
edit.html.twig
{% extends "UserBundle::layout.html.twig" %}
{% block body %}
<center> <h1> Modification de profile </h1> </center>
<aside class="col-sm-3">
<div class="panel panel-default">
<div class="panel-heading">Modification</div>
<div class="panel-body">
Veuillez remplir les champs
</div>
</div>
</aside>
<!--timeline-->
<section class="timeline col-sm-9">
<!--post Timeline-->
<div class="thumbnail thumbnail-post">
<!--caption-->
<div class="caption">
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="form-horizontal">
<div class="form-group">
{{ form_errors(form.name) }}
<div class="col-sm-9">
Name {{ form_widget(form.name, { 'attr': {'class': 'form-control', 'placeholder': 'form.name'|trans } }) }}
</div>
</div>
<div class="form-group">
{{ form_errors(form.email) }}
<div class="col-sm-9">
Email {{ form_widget(form.email, { 'attr': {'class': 'form-control', 'placeholder': 'form.email'|trans } }) }}
</div>
</div>
<div class="form-group">
{{ form_errors(form.username) }}
<div class="col-sm-9">
Pseudo {{ form_widget(form.username, { 'attr': {'class': 'form-control', 'placeholder': 'form.username'|trans } }) }}
</div>
</div>
<div class="form-group">
{{ form_errors(form.current_password) }}
<div class="col-sm-9">
Mot de passe actuelle {{ form_widget(form.current_password, { 'attr': {'class': 'form-control', 'placeholder': 'form.current_password'|trans } }) }}
</div>
</div>
</br>
{{ form_rest(form) }}
<div class="form-group">
<div class="col-md-4 col-sm-4 col-xs-12 col-md-offset-3">
<input class="btn btn-default submit" type="submit" value="{{ 'registration.submit'|trans }}">
</div>
</div>
</form>
</div> <!--#caption-->
<!--#post timeline-->
</div>
<!--#timeline-->
</section>
{% endblock %}
{% block js %}
<script>
$(document).ready(function () {
$('#roles').hide();
});
</script>
{% endblock %}
i'm getting this error :
Neither the property "name" nor one of the methods "name()",
"getname()"/"isname()" or "__call()" exist and have public access in
class "Symfony\Component\Form\FormView" in
FOSUserBundle:Profile:edit.html.twig at line 28.
How can i resolve that.
profile:
form:
type: fos_user_profile
It needs that at config.yml of fos
Update your service file:
user.edit.form.type:
class: UserBundle\Form\Type\ProfileFormType
arguments: [%fos_user.model.user.class%]
decorates: fos_user.profile.form.type
tags:
- { name: form.type, alias: user_edit_profile }
fos_user.profile.form.type is mean our name of service which will be replace our service that name user.edit.form.type
Add use Symfony\Component\Form\FormBuilderInterface;
You got error:
Neither the property "name" nor one of the methods "name()", "getname()"/"isname()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView" in FOSUserBundle:Profile:edit.html.twig at line 28.
due to fos_user_user table has not name field. If you want to add field whitch not locate in table you'll should add field those fields in entity generate getters and setters and finaly create new migration and migrate up.

Resources