HEllo sorry but my english isnt good.
I'm developing an application in Symfony 2.3.6 where i have to save in a DB (postgres) the values from a user.
The problem happens when my embed form (pais + region) that has 2 submit buttons the user press the second button. The system throw
Child "salvar_region" does not exist.
The question is how can I detect if the second button is being pressed if the system is throwing an exception?
Here is my Default controller
public function addLocalAction(Request $request)
{
$region = new Region();
$localidad = new Pais();
$localidad->setRegion($region);
$form = $this->createForm(new localidadType(), $localidad);
if($request->isMethod('POST')){
$form->handleRequest($request);
$form->getData();
if ($form->get('salvarPais')-> isClicked()){
$objeto = new Pais();
$objeto->setNombrePais($form->get('nombrePais')->getData());
$em = $this->getDoctrine()->getManager();
$em->persist($objeto);
$em->flush();}
if ($form->get('salvarregion')->isClicked()){
$objeto = new Region();
$objeto->setNombreRegion($form->get('nombreRegion')->getData());
$objeto->setNombreRegion($form->get('numeroRegion')->getData());
$em = $this->getDoctrine()->getManager();
$em->persist($objeto);
$em->flush();}
return $this->redirect($this->generateUrl('localidades'));
}
return $this->render('plataformaPlataformaBundle:Default:localidades.html.twig', array('form'=> $form->createView()));
}
My html.twig
<form action="{{ path('localidades')}}" method="post" {{ form_enctype(form) }}>
<h3>Agregar País</h3>
<div class="pais">
{{ form_row(form.nombrePais) }}
{{ form_row(form.salvarPais) }}
</div>
<form action="{{ path('localidades')}}" method="post" {{ form_enctype(form) }}>
<h3>Agregar Region</h3>
<div class="region">
{{ form_start(form) }}
{{ form_errors(form)}}
{{ form_row(form.region.nombreRegion) }}
{{ form_row(form.region.numeroRegion) }}
{{ form_row(form.region.pais) }}
{{ form_row(form.region.salvarregion) }}
{{ form_end(form) }}
</div>
</form>
and my 2 type forms
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nombreRegion', 'text', array('label' => 'Nombre de Región: '));
$builder->add('numeroRegion', 'integer', array('label' => 'Número de Región: '));
$builder->add('pais', 'entity', array('label' => 'País al que pertenece: ',
'class' => 'plataformaPlataformaBundle:Pais',
'property' => 'nombrePais'));
$builder->add('salvarregion', 'submit', array('label' => 'Guardar Región'));
$builder->getForm();
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nombrePais', 'text');
$builder->add('salvarPais', 'submit', array('label' => 'Guardar País'));
$builder->add('region', new regionType());
$builder->getForm();
}
PD: A lot of thanks if someone can help me
PDx2: here is an example of the URL request:{"region":{"nombreRegion":"ewrew","numeroRegion":"4","pais":"3","salvarregion":""},"_token":"853d5460b076e01fdf4cef4c59c33e836ab64af3"}
The error you got doesn't look like the name you gave the button during the builder process.
Anyway, to tell if a specific submit was clicked you can use:
if($form->get('salvarregion')->isClicked()) {
}
Related
I have a SquadType form which contains an embedded SquadMemberType form as a collectionType field.
Each time I press the add squad member button on my form, I can add a squadMember form from the prototype. Works perfectly.
The fact is, each time I add a squadMember form, it displays the name and tag label. I want to find a way to display these labels only for the first squadMember but not for the others.
I tried to set label to false in the form squadMemberType class and to display it directly in the template with no success (didn't find a way to make it work).
Is there a way to achieve that ?
My main form :
class squadType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('squadName', TextType::class)
->add('squadDescription', TextareaType::class)
->add('squadMembers', CollectionType::class, [
'label' => ' ',
'entry_type' => SquadMemberType::class,
'entry_options' => [
'attr' => [
'class' => 'email-box',
'style' => 'display:flex; gap:1rem;',
]
],
'allow_add' => true,
])
->add(
'save',
SubmitType::class, ['label' => 'Create Squad']
)
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Squad::class,
]);
}
}
My embedded form :
class SquadMemberType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('squadMemberName', TextType::class, [
'label_attr' => [
'class' => 'formLabel',
],
'label' => 'Name',
])
->add('squadMemberTag', IntegerType::class, [
'label' => 'Tag',
// 'label' => false,
'label_attr' => [
'class' => 'formLabel',
],
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => SquadMember::class,
]);
}
}
My twig :
<div class="content">
{{ form_start(form, {'attr': {'class': 'form-horizontal', 'id': 'create-squad'}}) }}
<div class="creation-form">
<fieldset class="creation-form-globalInfo">
<div class="form-group {{ form.squadName.vars.valid==false ? "has-error" }}">
{{ form_label(form.squadName, null, {
'label': 'Squad Name',
'label_attr': {'class': 'control-label'}}) }}
<div class="">
{{ form_widget(form.squadName) }}
{{ form_errors(form.squadName) }}
</div>
</div>
<div class="form-group {{ form.squadDescription.vars.valid==false ? "has-error" }}">
{{ form_label(form.squadDescription, null, {
'label': 'Squad Description',
'label_attr': {'class': 'control-label'}}) }}
<div class="">
{{ form_widget(form.squadDescription) }}
{{ form_errors(form.squadDescription) }}
</div>
</div>
</fieldset>
<fieldset class="creation-form-info">
<ul id="squadMember-fields-list"
data-prototype="{{ form_widget(form.squadMembers.vars.prototype)|e }}"
data-widget-tags="{{ '<li></li>'|e }}"
data-widget-counter="{{ form.squadMembers|length }}"
class="squad-form">
{% for squadMemberField in form.squadMembers %}
<li>
{{ form_errors(squadMemberField) }}
{{ form_widget(squadMemberField) }}
</li>
{% endfor %}
</ul>
<button type="button"
class="add-another-collection-widget secundary-button"
data-list-selector="squadMember-fields-list">
{{ 'squad.add.squadMember.button.label'|trans }}
</button>
</fieldset>
</div>
<div class="validation-bottom">
{{ form_row(form.save,{
'label': 'squad.add.confirm.button',
'attr': {
'class': 'primary-button'
}
})
}}
</div>
{{ form_end(form) }}
</div>
my script :
{% block javascripts %}
<script>
$(document).ready( function () {
$('.add-another-collection-widget').click(function (e) {
var list = jQuery(jQuery(this).attr('data-list-selector'));
// Try to find the counter of the list or use the length of the list
var counter = list.data('widget-counter') || list.children().length;
// grab the prototype template
var newWidget = list.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/__name__/g, counter);
// Increase the counter
counter++;
// And store it, the length cannot be used if deleting widgets is allowed
list.data('widget-counter', counter);
// create a new list element and add it to the list
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
newElem.appendTo(list);
});
</script>
{% endblock %}
I have a problem with my Form in symfony4, when I click on the submit button it is not submitted (It doesn't pass the isSubmitted condition)
Here is my Form
<?php
namespace App\Form\Backend\Team;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class AddTeamForm
* #package App\Form\Backend\Team
*/
class TeamForm extends AbstractType
{
const NAME = 'name';
const WEBSITE = 'website';
const IRC = 'irc';
const DISCORD = 'discord';
const TWITTER = 'twitter';
const FACEBOOK = 'facebook';
const HIDDEN = 'hidden';
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', HiddenType::class)
->add(self::NAME, TextType::class, [
'required' => true,
'label' => 'admin.team.form.name'
])
->add(self::WEBSITE, TextType::class, [
'required' => false,
'label' => 'admin.team.form.website'
])
->add(self::IRC, TextType::class, [
'required' => false,
'label' => 'admin.team.form.irc'
])
->add(self::DISCORD, TextType::class, [
'required' => false,
'label' => 'admin.team.form.discord'
])
->add(self::TWITTER, TextType::class, [
'required' => false,
'label' => 'admin.team.form.twitter'
])
->add(self::FACEBOOK, TextType::class, [
'required' => false,
'label' => 'admin.team.form.facebook'
])
->add(self::HIDDEN, CheckboxType::class, [
'required' => false,
'label' => 'admin.team.form.hidden'
]);
}
}
and Here is my action
/**
* #Route("/add", name="add")
*/
public function add(Request $request)
{
$form = $this->createForm(TeamForm::class);
$form->handleRequest($request);
if ($form->isSubmitted()) {
var_dump('submitted');
if($form->isValid())
{
} else {
var_dump('non vlide');exit;
}
$team = $form->getData();
}
return $this->render('backend/team/add.html.twig', [
'form' => $form->createView(),
]);
}
and my view
{{ form_start(form, {attr: {class: 'ui form inverted', novalidate:'novalidate', 'action': url('admin_team_add')} }) }}
{{ form_errors(form) }}
<div class="ui grid two column">
<div class="row">
<div class="twelve wide column">
{{ form_row(form.name) }}
{{ form_row(form.website) }}
{{ form_row(form.irc) }}
{{ form_row(form.discord) }}
{{ form_row(form.twitter) }}
{{ form_row(form.facebook) }}
<div class="field">
<div class="ui checkbox">
{{ form_widget(form.hidden) }}
{{ form_label(form.hidden) }}
{{ form_errors(form.hidden) }}
</div>
</div>
<input type="submit" class="ui button green" value="{{ 'admin.team.form.btn-create' }}"/>
</div>
</div>
</div>
{{ form_end(form) }}
Like I said, When I click my submit button, the var_dump 'submitted' is not shown. The page refreshes but nothing happen, like a normal page refresh.
I must miss something but can't figure what ...
you can check if your route name exist:
php bin/console debug:router admin_team_add
if it's not exist , change your view action to :
{{ form_start(form, {attr: {class: 'ui form inverted', novalidate:'novalidate', 'action': url('add')} }) }}
or change your controller route name to :
/**
* #Route("/add", name="admin_team_add")
*/
public function add(Request $request)
{
I have the following form and Twig template:
FormType
class UserType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name','text',array('label' => 'Name', 'max_length' => 30))
->add('surname','text',array('label' => 'Sjurname', 'max_length' => 30))
....
->add('password', 'repeated', array('error_bubbling' => true,'required' => false, 'first_options' => array('label' => 'New Password'),'second_options' => array('label' => 'Repeat Password'),'type' => 'password' ,'invalid_message'=> 'Passwords must be the same.'));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bundle\Entity\User',
));
}
/**
* #return string
*/
public function getName()
{
return 'user';
}
}
Twig
....
{{form_start(form, {'method':'Put','attr':{'data-toggle':"validator", 'role':"form" ,'novalidate':'novalidate', 'autocomplete':'off'}})}}
{{ form_errors(form) }}
<div class="form-group has-feedback">
{{ form_label(form.password, 'New Password:',{'label_attr':{'class': 'col-md-5'}}) }}
<div class="col-md-7">
{{ form_widget(form.password,{'attr':{'class': 'form-control', 'type': 'password','data-error': 'You must enter a minimum of 6 characters', 'placeholder': 'Min 6 characters', 'data-minlength':"6", 'required':'true' }}) }}
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<div class="help-block with-errors"></div>
</div>
</div>
{{ form_row(form.submit,{'attr':{'class': 'btn btn-primary pull-right' }}) }}
<div class="hidden">
{{ form_rest(form) }}
</div>
{{ form_end(form) }}
...
The problem I have is that the input is not created. The label is displayed. I have tried using form.password.first and form.password.second but neither is the input (only the labels). With the other fields I do not have that problem, the only thing in this case all the others are hidden in a div. What could be the problem?
I appreciate your help.
Take a look at this. it is for symfony 2.8/3+ but you can adapt it to your needs.
FormType
->add('plainPassword', RepeatedType::class, [
'type' => PasswordType::class,
'first_options' => [
'label' => 'registration.password',
],
'second_options' => [
'label' => 'registration.retype.password',
],
]) ...
twig
<div>
{{ form_label(form.plainPassword.first) }}
{{ form_widget(form.plainPassword.first) }}
{{ form_errors(form.plainPassword.first) }}
</div>
<div>
{{ form_label(form.plainPassword.second) }}
{{ form_widget(form.plainPassword.second) }}
{{ form_errors(form.plainPassword.second) }}
</div>
Do you have a version of xDebug installed? You could place a breakpoint on the return section of the Controller and have a look inside the children element of the form. This could tell you what the names of the elements are.
**PS, I would have commented this but I don't have enough rep.
I'm creating a from using Symfony Form builder, and rendering it using twig.
Here is my form builder code:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'required' => TRUE,
))
->add('link', 'text', array(
'required' => TRUE,
))
->add('submit', 'submit', array(
'attr' => array(
'class' => 'btn btn-primary btn-sm custom-btn'
)
))
;
}
And my twig template is like this:
{{ form_start(form)}}
<div>
{{ form_label(form.name) }}
{{ form_widget(form.name) }}
</div>
<div>
{{ form_label(form.link) }}
{{ form_widget(form.link) }}
</div>
<div>
{{ form_widget(form.submit) }}
</div>
{{ form_end(form) }}
In this case, I'm getting everything as expected, except the submit button. Instead of custom submit button created in form builder, it is rendering default submit button with a label create.
What I'm doing wrong here?
Seems it is some issue with 'submit' name. For example, next example works:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
.... // your fields here
->('my_button', 'submit');
}
Then in the twig template:
<div>
{{ form_widget(form.my_button) }}
</div>
UPDATED : according to http://symfony.com/doc/current/reference/forms/twig_reference.html you can use {{ form_widget(form.submit, {'label': 'submit'}) }}. So next lines renders submit with 'submit' name:
{{ form_start(form) }}
{{ form_widget(form.text) }}
{{ form_widget(form.code) }}
{{ form_widget(form.submit, {'label': 'submit'}) }}
{{ form_end(form) }}
And you don't need to add submit to your FormType in this case.
I dont know why not can show a variable, I read the manual and I searched in many websites, but I have no idea what I'm doing wrong...
I have a classType (there is not from a entity), the class form have 3 combobox and a textbox, when I submit the form, another template (show2.html.twig) render the new form where I want show the textbox value... I speend many time and a have 0 result ;)
When I see the Symfony profiler, I can see the values of the form in the "Request POST Parameters" section, but I'cant catch it and show it in the twig template...
that is the code wath dont work for my
$this->get('request')->request->get('campo', 'can not show it ¬¬')
in the template dont show the "campo" value, just "can not show it ¬¬"
this is my classType
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('Pais', 'entity', array(
'class' => 'UnadeniZonaBundle:Pais',
'property' => 'paisnomb',
))
->add('Provincia', 'entity', array(
'class' => 'UnadeniZonaBundle:Provincia',
'property' => 'provnomb',
))
->add('Ciudad', 'entity', array(
'class' => 'UnadeniZonaBundle:Ciudad',
'property' => 'ciudnomb',
))
->add('Campo', 'text', array(
'label' => 'campo',));
}
public function getName() {
return 'ciudad2';
}
}
My controller...
public function newAction(Request $request) {
$form = $this->createForm(new Ciudad2Type());
return $this->render('UnadeniZonaBundle:Ciudad2:new.html.twig', array(
'form' => $form->createView(),
'mensaje' => 'test'
));
}
public function showAction(Request $request) {
if ($request->isMethod('POST')) {
return $this->render('UnadeniZonaBundle:Ciudad2:show2.html.twig', array(
'mensaje' => $this->get('request')->request->get('campo', 'can not show it ¬¬')
));
}
}
this the templates
(new.html.twig)
{% extends '::base.html.twig' %}
{% block content -%}
<form action="{{ path('ciudad2_show') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" />
{{ mensaje }}
</form>
{% endblock %}
(Show2.html.twig)
{% extends '::base.html.twig' %}
{% block content -%}
{{ mensaje }}
{% endblock %}
If you try this :
$postData = $request->request->get('ciudad2');
$targetValue = $postData['Campo'];
return $this->render('UnadeniZonaBundle:Ciudad2:show2.html.twig', array(
'mensaje' => $targetValue)
));
It's a typo issue. Change campo to Campo in your controller.
if ($this->getRequest()->isMethod('POST')) {
$request = $this->getRequest->request;
$campo = $request->get('Campo', 'cannot show it.', true);
return $this->render('UnadeniZonaBundle:Ciudad2:show2.html.twig', array(
'mensaje' => $campo
));
}