I have a form with 3 entity fields displaying radios input.
->add(
'membership',
'entity',
array(
'class' => 'Comiti\UserBundle\Entity\Membership',
'expanded' => true,
'multiple' => false,
'label' => false,
'empty_value' => 'Aucune adhésion',
'query_builder' => function (MembershipRepository $er) {
return $er->createQueryBuilder('membership')
->where('membership.club = :club')
->setParameter('club', $this->authentication_service->getCurrentClub())
->orderBy('membership.name', 'ASC')
;
},
)
)->add(
'federal_license',
'entity',
array(
'class' => 'Comiti\UserBundle\Entity\FederalLicense',
'expanded' => true,
'multiple' => false,
'label' => false,
'empty_value' => 'Aucune licence',
'query_builder' => function (FederalLicenseRepository $er) {
return $er->createQueryBuilder('federal_license')
->where('federal_license.club = :club')
->setParameter('club', $this->authentication_service->getCurrentClub())
->orderBy('federal_license.name', 'ASC')
;
}
)
)->add(
'insurance',
'entity',
array(
'class' => 'Comiti\UserBundle\Entity\Insurance',
'expanded' => true,
'multiple' => false,
'label' => false,
'empty_value' => 'Aucune assurance',
'query_builder' => function (InsuranceRepository $er) {
return $er->createQueryBuilder('insurance')
->where('insurance.club = :club')
->setParameter('club', $this->authentication_service->getCurrentClub())
->orderBy('insurance.name', 'ASC')
;
}
)
);
I need to define a custom template for those radios input that put in each input an attr whith "data-price".
i made this:
{%- block radio_widget -%}
<input type="radio" data-price="{{Myprivcevar}}" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
Is there any possibility to access to {{MypriceVar }}
I am on Symfony 2.6
You can add attributes to an input without creating a custom template:
{{ form_widget(yourRow, {'attr': {'data-price':'yourValue'}}) }}
Example:
{{ form_widget(choiceFormView, {'attr': {'data-price':'2'}}) }}
result in
<input type="radio" id="form_choice_0" name="form[choice]" required="required" data-price="2" value="1" checked="checked">
Related
I'm trying to make a form to add an entity in my database (a project). I realized exactly the same thing for other entities, everything works, but for this one (a project), it does not work ...
Screen of error : http://image.noelshack.com/fichiers/2019/02/1/1546884788-capture.png
ProjectController :
/**
* #Route("/projects/add", name="add_projects")
*/
public function addProject(Request $request)
{
$em = $this->getDoctrine()->getManager();
$project = new Project();
$form = $this->createForm(AddProjectType::class, $project);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($project);
$em->flush();
return $this->redirectToRoute('index_projects');
}
return $this->render('/project/add.html.twig', [
'form' => $form->createView(),
]);
}
AddProjectType :
class AddProjectType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, array(
'attr' => array(
'placeholder' => 'Nom',
),
'label' => false,
))
->add('price', IntegerType::class, array(
'attr' => array(
'placeholder' => 'Prix',
),
'label' => false,
))
->add('type', ChoiceType::class, array(
'choices' => array(
'Application web' => 'Application web',
'Site internet' => 'Site internet',
'Application mobile' => 'Application mobile',
'Autre' => 'Autre',
),
'label' => false,
))
->add('client', EntityType::class, array(
'class' => User::class,
'choice_label' => function($user) {
return $user->getUsername();
},
'label' => false,
))
->add('state', ChoiceType::class, array(
'choices' => array(
'A faire' => 'A faire',
'En cours' => 'En cours',
'Terminé' => 'Terminé',
),
'label' => false,
))
->add('description', TextareaType::class, array(
'attr' => array(
'placeholder' => 'Description',
),
'label' => false,
))
->add('Ajouter', SubmitType::class, [
'attr' => [
'class' => 'btn btn-success',
]
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Project::class,
]);
}
}
add.html.twig :
{% extends "./base.html.twig" %}
{% block title %}{{ parent() }}Ajouter un projet{% endblock %}
{% block stylesheets %}
{{ parent() }}
<style>
form input, form select, form textarea {
width: 100%;
margin: .5em 0;
}
</style>
{% endblock %}
{% block body %}
{{ parent() }}
<h1 class="title-page">Ajouter un projet</h1>
<div class="container-fluid">
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</div>
{% endblock %}
Did you look into the database whether the project is added?
In your controller I don't see a reason for a ParamConverter, therefore I guess that the error happens after the redirect to index_projects
I just managed to find out why I had this error, I'll post the salution here so that other people have it:
I had in this controller a route /projects/{id} (to access the details of a project), I modified it by /projects/details/{id}
Hi,
i have created a search form using GET method, to my indexAction, the form contains virtual fields.
i created the logic for searching inside the indexAction.
My problem is when i submit the form, all inputs values become empty.
What i want is to keep the values passed as arguments in form inputs
here is my FormType :
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title', TextType::class, array(
'required' => false,
'attr' => array(
'placeholder' => 'Chercher',
)
))
->add('client', EntityType::class, array(
'required' => false,
'class' => 'AppBundle:Person',
'placeholder' => 'Choisir client',
'attr' => array(
'class' => 'select2',
)
))
->add('date_start', DateTimeType::class, array(
'required' => false,
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'inherit_data' => true,
'attr' => array(
'name' => 'date_start',
'class' => 'datepicker',
'placeholder' => 'Date début',
'value' => ''
)
))
->add('date_end', DateTimeType::class, array(
'required' => false,
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'inherit_data' => true,
'attr' => array(
'name' => 'date_end',
'class' => 'datepicker',
'placeholder' => 'Date fin',
'value' => ''
)
))
;
}
The indexAction :
public function indexAction(Request $request)
{
$getArgs = $request->query->get('order');
dump($getArgs);
$form = $this->createForm('AppBundle\Form\Search\OrderType', new Order(), array('get' => $getArgs));
$form->handleRequest($request);
$repo = $this->getDoctrine()->getRepository('AppBundle:Order');
$query = $getArgs ? $repo->findAllMatched($q) : $repo->createQueryBuilder('o');
$paginator = $this->get('knp_paginator');
$orders = $paginator->paginate($query);
return $this->render('AppBundle:Order:index.html.twig', array(
'orders' => $orders,
'form' => $form->createView(),
));
}
Any suggestions are wellcome.
For now, i resolved the problem in this way :
<div class="nav box-search">
<form method="GET" class="form-inline">
<div class="pull-right">
<button type="submit" class="btn btn-default">{{ 'actions.search' | trans }}</button>
</div>
<div class="pull-left">
{% set params = app.request.query.all %}
{{- form_widget(form.title, { 'attr': {'value': params.order.title| default('')} }) -}}
{{ form_widget(form.client, {value: params.order.client| default('') }) }}
{{- form_widget(form.date_start, { 'attr': {'value': params.order.date_start| default('')} }) -}}
<i class="fa fa-exchange"></i>
{{- form_row(form.date_end, { 'attr': {'value': params.order.date_end| default('')} }) -}}
</div>
</form>
</div>
It's not that bad solution, but what i would is to have this parameters configuration in the FormType.
I'm using a collectionType that render a multiple select inputs, I want to add the select2 css class to my form but it just doesn't works.
This is the Form that has the collection.
->add('arrayDiagnosticos', 'collection', [
'type' => 'entity',
'label' => 'Diagnósticos dinámicos',
'allow_add' => true,
'allow_delete' => true,
'attr' => [
'class' => 'select2',
],
'options' => [
'empty_value' => 'Seleccionar Diagnóstico',
'class' => 'AppBundle:Diagnostico',
'required' => true,
'label' => 'Buscador de Diagnósticos',
'attr' => [
'class' => 'select2',
],
],
])
The twig is
<ul class="tags" data-prototype="{{ form_widget(form.arrayDiagnosticos.vars.prototype)|e }}">
{# iterate over each existing tag and render its only field: name #}
{% for diagnostico in form.arrayDiagnosticos %}
<li>
{{ form_row(diagnostico.nombreDiagnostico) }}
</li>
{% endfor %}
</ul>
It should render a select input like this:
1
But it renders like a regular select input
2
This is the output html
<div class="form-group"><label class="control-label required">Diagnósticos dinámicos</label>
<div id="paciente_form_arrayDiagnosticos" class="select2" data-prototype="<div class="row"><div class="col-xs-9"><select id="paciente_form_arrayDiagnosticos___name__" name="paciente_form[arrayDiagnosticos][__name__]" required="required" class="select2 form-control"><option value="" selected="selected">Seleccionar Diagnóstico</option> <option value="1" >se siente mal</option> <option value="2" >asfd</option> <option value="3" >YOLO</option></select></div><div class="col-xs-3"><a href="#" class="btn btn-danger btn-sm" data-removefield="collection" data-field="__id__">Eliminar Diagnóstico</a></div></div>" data-prototype-name="__name__"><ul class="bc-collection list-unstyled"></ul>Agregar Diagnóstico</div></div>
I also tried to do it via jQuery and no luck
<script>
$(function(){
$('#paciente_form_arrayDiagnosticos').addClass('select2')});
</script>
How do I properly attach the select2 css class?
Try this:
->add('arrayDiagnosticos', 'collection', [
'type' => new PreDiagnosticoType(),
'label' => ' ',
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
'attr' => array(
'class' => 'select2',
),
])
Since your <selects /> are created dinamically, you have to set up a listener to apply the select2 function when each select element is created.
Somthing like this might work:
$('body').on('DOMNodeInserted', '.select2', function() {
$(this).select2();
});
I have following form builder:
$builder->add('status', 'choice', array('attr' => array(
'choices' => array('0' => 'Principal', '1' => 'Teacher', '2' => 'Student'),
'required' => true, 'expanded' => 'false', 'multiple' => 'true'
)));
How to present those 3 values as radio buttons in twig template in a way like below presented(it doesn't work)?
{{ form_start(form) }}
{{ form_widget(form.status.choices[0]) }}
{{ form_end(form) }}
If you want radio buttons you need change options to 'expanded' => 'true', 'multiple' => 'false'
In twig:
{{ form_start(form) }}
{{ form_widget(form.status) }}
{{ form_end(form) }}
More information: choice Field Type
I have a form where the dropdown value is coming from another entity.
->add('country', 'entity', array(
'label' => 'Country',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.countryName', 'ASC');
},
'empty_value' => 'Select Country',
'required' => true,
'mapped' => true,
'class' => 'BundleAdminBundle:KidsKulaCountry',
'attr' => array('class' => 'form-control sml-frm'),
//...
))
In the twig file i want to set selected the value at edit.
{{ form_widget(form.country, {value: Setcountry } ) }}
if I print
{{Setcountry}}
its returns result but it does not set selected.Please help me out.
I suppose that your Setcountry is the id of the entity you want to select. You can do this with the conversion of the Setcountry of int to string in the next way:
{{ form_widget(form.country, {value: Setcountry ~ "" } ) }}