How can I make it work clockpicker in Symfony forms? - symfony

I'm trying to make a friendly interface to select TIME and save it to database, so I decided to use bootstrap clockpicker.
This is my layout.html.twig:
{% extends 'base.html.twig' %}
{% block stylesheets %}
{{ parent() }}
<link href="{{ asset('public/css/bootstrap.css') }}" type="text/css" rel="stylesheet" />
<link href="{{ asset('public/css/estilo.css') }}" type="text/css" rel="stylesheet" />
<link href="{{ asset('public/css/dataTables.bootstrap.min.css') }}" type="text/css" rel="stylesheet" />
<link href="{{ asset('public/css/bootstrap-select.min.css') }}" type="text/css" rel="stylesheet" />
<link href="{{ asset('public/css/datepicker.css') }}" type="text/css" rel="stylesheet" />
<link href="{{ asset('public/css/dist/bootstrap-clockpicker.css') }}" type="text/css" rel="stylesheet" />
{% endblock %}
{% block header %}
{% set empresa = app.session.get('empresa') %}
<div class="container header">
<div class="row">
<div class="col-md-2">
{% set env = app.environment %}
{% if env == 'dev' %}
{% set app_link = 'app_dev.php' %}
{% else %}
{% set app_link = 'app.php' %}
{% endif %}
<a href="{{ asset(app_link) }}">
<img src="{{ asset('public/images/logo.png') }}" class="img-responsive"/>
</a>
</div>
<div class="col-md-10">
<h3 class="text-gray">Sistema de planificación de recursos empresariales</h3>
<p class="text-gray" style="font-size: 1.1em;">Centuria version 1.1<br>
{% if empresa|length %}
{{ empresa }}
{% else %}
Potenciado por Symfony 3.4
{% endif %}
</p>
</div>
</div>
<div class="top_div_line"> </div>
</div>
{% endblock %}
{% block body %}
<div id="layout" class="container">
<div class="row">
<div class="col-md-12">
{% block content %}
{% endblock %}
</div>
</div>
</div>
<div class="container footer navbar-default navbar-fixed-bottom">
<p class="text-center text-gray">Derechos de copia reservados &copy MG Datos</p>
</div>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('public/js/jquery-3.2.1.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('public/js/bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('public/js/jquery.dataTables.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('public/js/dataTables.bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('public/js/bootstrap-select.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('public/js/bootstrap-datepicker.js') }}" type="text/javascript"></script>
<script src="{{ asset('public/js/dist/bootstrap-clockpicker.js') }}" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#ftable').DataTable({
stateSave: true,
language: {
"emptyTable": "No hay datos disponibles en la tabla",
"info": "Mostrando _START_ hasta _END_ de _TOTAL_ registros",
"infoEmpty": "Mostrando 0 hasta 0 de 0 registros",
"lengthMenu": "Mostrar _MENU_ registros",
"search": "Buscar:",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"paginate": {
"first": "Primero",
"last": "Ultimo",
"next": "Siguiente",
"previous": "Anterior"
},
"infoFiltered": "(filtrados de _MAX_ registros)"
}
});
$('#ftable2').DataTable({
stateSave: true,
language: {
"emptyTable": "No hay datos disponibles en la tabla",
"info": "Mostrando _START_ hasta _END_ de _TOTAL_ registros",
"infoEmpty": "Mostrando 0 hasta 0 de 0 registros",
"lengthMenu": "Mostrar _MENU_ registros",
"search": "Buscar:",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"paginate": {
"first": "Primero",
"last": "Ultimo",
"next": "Siguiente",
"previous": "Anterior"
},
"infoFiltered": "(filtrados de _MAX_ registros)"
}
});
$('.selectpicker').selectpicker({
size: 8
});
$('.datepicker').datepicker({
format: 'dd-mm-yyyy',
autoclose: true
});
$.datepicker.regional['es'] = {
closeText: 'Cerrar',
prevText: '<Ant',
nextText: 'Sig>',
currentText: 'Hoy',
monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
weekHeader: 'Sm',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
$.datepicker.setDefaults($.datepicker.regional['es']);
$('.clockpicker').clockpicker();
} );
</script>
{% endblock %}
And this is my new.html.twig:
{% extends '#CenturiaMain/Default/index.html.twig' %}
{% block content %}
{% block centuria_menu %}
{{ parent() }}
{% endblock %}
<div class = "main container">
<div class = "row well col-md-12" style = margin-bottom:55px;">
<h3>Nuevo registro</h3>
{{ form_start(form) }}
<div class = "form-group col-md-4">
{{ form_widget(form.idCambiosplanilla, { 'attr':{'hidden':'hidden'} }) }}
<div class = "form-group col-md-12">
<h5>Fecha</h5>{{ form_widget(form.fecha, { "attr" : {"class" : "form-control datepicker"}}) }}
<span class = "text-danger">{{ form_errors(form.fecha) }}</span>
</div>
<div class="input-group clockpicker " data-autoclose="true">
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
<input type="text" class="form-control" value="09:30" />
</div>
<div class = "form-group col-md-6">
<h5>Horario: Desde</h5>{{ form_widget(form.horarioInicio, { "attr" : {"class" : "form-control clockpicker-control"}}) }}
<span class = "text-danger">{{ form_errors(form.horarioInicio) }}</span>
</div>
<div class = "form-group col-md-6">
<h5>Hasta</h5>{{ form_widget(form.horarioFinal) }}{{ form_widget(form.horarioFinal) }}
<span class = "text-danger">{{ form_errors(form.horarioFinal) }}</span>
</div>
<br>
<a href="{{ path('centuria_cambiosplanilladetalle', {'idCd' : 1}) }}"
class = "btn btn-warning glyphicon glyphicon-arrow-left"></a>
<input type="submit" class="btn btn-success glyphicon glyphicon-ok" value="" />
</div>
{{ form_end(form) }}
</div>
</div>
{% endblock %}
I have followed the instrucctions to use clockpicker, In fact I have created a simple HTML file and It works, But I can not make it work in my symfony application, do you have any ideas regarding my code, what I am possible doing wrong?
This is my form:
<?php
namespace Centuria\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TimeType;
class CambiosplanilladetalleType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('idCambiosplanilla')->add('idEmpleado')->add('fecha', TextType::class)->add('horarioInicio', TimeType::class)->add('horarioFinal')->add('extraInicio')->add('extraFinal')->add('tiempoTotal')->add('idAsignacion')->add('fechaRegistro')->add('horaRegistro')->add('idUsuario');
}/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Centuria\MainBundle\Entity\Cambiosplanilladetalle'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'centuria_mainbundle_cambiosplanilladetalle';
}
}
And It appears like this:
Thank you in advice.

In your form type class, you need to add the "clockpicker" css class to the field, like so
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('idCambiosplanilla')
->add('idEmpleado')
->add('fecha', TextType::class)
->add('horarioInicio', TimeType::class, [
'attr' => [
'class' => 'form-control clockpicker-control clockpicker',
]
])
->add('horarioFinal', )
->add('extraInicio')
->add('extraFinal')
->add('tiempoTotal')
->add('idAsignacion')
->add('fechaRegistro')
->add('horaRegistro')
->add('idUsuario');
}
alternatively, in your form twig, you could also set the "clockpicker" class, like so:
<div class = "form-group col-md-6">
<h5>Horario: Desde</h5>{{ form_widget(form.horarioInicio, { "attr" : {"class" : "form-control clockpicker-control clockpicker"}}) }}
<span class = "text-danger">{{ form_errors(form.horarioInicio) }}</span>
</div>

Related

How to use template form when edit object

I have a form with an embedded form (collectionType). I made a template. It works when I add a new object. But how to use this template when I edit an object ? Below my code an 2 pictures to illustrate my problem
{% extends 'base.html.twig' %}
{% form_theme form _self %}
{% block _paris_rencontres_row %}
<div class="sports" id="renc-xx" style="background-color: rgba(182, 184, 185, 0.200);">
<div
class="row">
{# <ul class="sports" data-prototype="{{ form_widget(form.vars.prototype)|e('html_attr') }}"></ul> #}
<div class="col-md-3">
{{ form_row(form.vars.prototype.playedAt) }}
</div>
<div class="col-md-3">
{{ form_row(form.vars.prototype.sport) }}
</div>
</div>
<div class="row">
<div class="col-md-3">
{{ form_row(form.vars.prototype.player_1) }}
</div>
<div class="col-md-3">
{{ form_row(form.vars.prototype.player_2) }}
</div>
<div class="col-md-2">
{{ form_row(form.vars.prototype.cote) }}
</div>
<div class="col-md-2">
{{ form_row(form.vars.prototype.resultat) }}
</div>
</div>
<hr>
</div>
{% endblock %}
{% block body %}
{# {{ include('paris/_form.html.twig', {form:form, button: 'Ajouter'}) }} #}
<button type='button' id='btn-add' class='add_sport_link btn btn-primary'>Ajouter paris</button>
{{ form_start(form) }}
<div class="paris">
<div class="row">
<div class="col-md-4">
{{ form_row(form.mise) }}
</div>
<div class="col-md-4">
{{ form_row(form.type) }}
</div>
<div class="col-md-4">
{{ form_row(form.win) }}
</div>
</div>
<div class="col-md-4 matchs">
{% if form.rencontres|length > 0 %}
{% for index in 0..form.rencontres|length - 1 %}
{{ dump(index) }}
{{ form_row(form.rencontres[index]) }}
{% endfor %}
{% else %}
{{ form_row(form.rencontres) }}
{% endif %}
</div>
</div>
{{ form_end(form) }}
{% endblock %}
add (form.rencontres|length == 0):
enter image description here
edit (form.rencontres|length > 0):
enter image description here
Regards
PS: Sorry for my english
EDIT: My controller
#NicoHaase I dont think the problem is in the code.
I want just display my form template when I edit an object as when I add an object
`code
/**
* #Route("/paris/add", name="paris_add")
*/
public function add(Request $request)
{
$em = $this->getDoctrine()->getManager();
$paris = new paris();
$form = $this->createForm(ParisType::class, $paris);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($paris);
$em->flush();
return $this->redirectToRoute('paris');
}
return $this->render("paris/add.html.twig", [
'form' => $form->createView()
]);
}
/**
* #Route("/paris/{id}", name="paris_edit", requirements={"id":"\d+"})
* #param Paris $paris
* #param Request $request
*/
public function edit(Request $request, Paris $paris)
{
$form = $this->createForm(ParisType::class, $paris);
$form->handleRequest($request);
return $this->render("paris/add.html.twig", [
"paris" => $paris,
"form" => $form->createView(),
]);
}
`

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 %}

Customize symfony data-prototype for edit form

I know it's a common question but I cannot figure out how to achieve that.
I have a Course entity and a CourseDocument entity.
Course(id, documents, ...)
CourseDocument(id, file, course)
In my Course form:
class CourseType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class, [
'label' => 'course.title',
])
->add('documents', CollectionType::class, array(
'entry_type' => MediaType::class,
'label' => 'course.documents_list',
'entry_options' => array(
'label' => false,
'data_class' => CourseDocument::class,
),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
))
;
}
In the form I want to be able to add as many documents as I want. I set up everything, javascript included. My only issue is the data-prototype that is not what I want.
{% import "macros/prototype.html.twig" as prototype %}
{{ form_start(form) }}
<div class="row">
<div class="col-md-6">
<fieldset class="form-group">
{{ form_label(form.documents) }}
<div id="course_documents" class="collection_holder" data-prototype="{{ prototype.tagCollectionItem(form.documents.vars.prototype)|e }}">
{% for widget in form.documents %}
{{ prototype.tagCollectionItem(widget) }}
{% endfor %}
</div>
<button type="button" id="add-document-btn" data-target-collection="#{{ form.documents.vars.id }}" class="btn btn-sm btn-info"><i class="la la-plus"></i> {{ 'course.buttons.add_document' | trans({}, 'labels') }}</button>
</fieldset>
</div>
</div>
{{ form_end(form) }}
I'm generating my prototype with a macro:
{% macro tagCollectionItem(item) %}
<fieldset class="form-group">
<div id="{{ item.vars.id }}">
<div class="custom-file">
{{ form_widget(item.uploadedFile) }}
{{ form_label(item.uploadedFile, item.uploadedFile.vars.label, {'label_attr': {'class': 'custom-file-label'}}) }}
</div>
</div>
</fieldset>
{% endmacro %}
It's working pretty well except for editing. I don't want the input if I already selected a file. But I want the name of the file.
I finally used a macro.
{% macro tagCollectionItem(item) %}
<fieldset class="form-group">
<div id="{{ item.vars.id }}">
{% if item.uploadedFile.vars.file_url or item.uploadedFile.vars.image_url %}
{{ form_errors(item.uploadedFile) }}
{{ form_widget(item.uploadedFile, {'attr': {'hidden': true}}) }}
{% else %}
<div class="custom-file">
{{ form_widget(item.uploadedFile) }}
{{ form_label(item.uploadedFile, item.uploadedFile.vars.label, {'label_attr': {'class': 'custom-file-label'}}) }}
</div>
{% endif %}
</div>
</fieldset>
{% endmacro %}
The twig file for the form
<fieldset class="form-group">
{{ form_label(form.documents) }}
<div id="course_documents" class="collection_holder" data-prototype="{{ prototype.tagCollectionItem(form.documents.vars.prototype)|e }}">
{% for widget in form.documents.children %}
{{ prototype.tagCollectionItem(widget) }}
{% endfor %}
</div>
<button type="button" id="add-document-btn" data-target-collection="#{{ form.documents.vars.id }}" class="btn btn-sm btn-info"><i class="la la-plus"></i> {{ 'course.buttons.add_document' | trans({}, 'labels') }}</button>
</fieldset>

MissingMandatoryParametersException: Some mandatory parameters are missingto generate a URL for route

It seems that I am missing something here and I am keep getting the following message:
## An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("fooId") to generate a URL for route "foo_edit".") in AdminFooBundle:Default:base.html.twig at line 1. ##
This is the Controller's action:
/**
* #Route("/{fooId}/edit", name="foo_edit", requirements={"fooId" = "\d+"})
* #param $fooId
*
* #return View
*/
public function editFooFormAction($fooId)
{
$foo = $this->getFooRepository()->findOneBy(['fooId' => $fooId]);
return $this->render(
"AdminFooBundle:Competition:show_foo.html.twig",
['foo' => $foo]
);
}
And this is my twig file:
{% extends 'FooAdminToolBundle:Default:base.html.twig' %}
{% block inner_main %}
{{ parent() }}
<form data-spy="scroll" data-target="#affix-nav" action="{{ path('foo_create') }}" method="post">
<button type="submit" style="position: absolute; left:-10000px;"></button>
{% include 'FooAdminBundle:Foo:foo_data.html.twig'%}
<button type="submit" class="btn btn-default">Add new foo</button>
</form>
{% endblock %}
My guess is the issue lives in extending Default:base.html.twig, but I cannot see something right now:
{% set currentPath = path(app.request.attributes.get('_route')) %}
<!DOCTYPE html>
<html lang="en">
<head>
<title> {% block title %}Admin Tool{% endblock %}</title>
{% block stylesheets %}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
{% endblock %}
{% block headcss %}
{% endblock %}
{% block headjavascripts %}
{% endblock %}
<link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
</head>
<body data-spy="scroll" data-target="#affix-nav">
{% include 'FooAdminBundle:Default:navbar.html.twig' %}
<div class="container">
{% block main %}{% endblock %}
<div class="row">
<div class="col-sm-9">
{% block inner_main %}{% endblock %}
</div>
<div class="col-sm-3">
<div id="options" data-spy="affix"></div>
</div>
</div>
</div> <!-- /main -->
Check if you have a valid for parameter $fooId. In your route is mandatory, and maybe because is missing, that error is thrown.

how to create a customized form

I'm working in a project and I would like to create form and not using form_widget. I want to create my own form.
Here is my controller:
public function newAction()
{
$entity = new Etudiant();
$form = $this->createCreateForm($entity);
return $this->render('MyAppRevBundle:Etudiant:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
And my html page is:
{% extends '::base.html.twig' %}
{% block body -%}
<form action="{{ path('etudiant') }}" {{form_enctype(form)}} method="post" >
<label for="username" class="col-md-2 control_label">Login :</label>
<input type="text" id="username" name="_username" value="Thaer"required="required" />
<br>
<input type="submit"/>
{{ form_rest(form) }}
</form>
<ul class="record_actions">
<li>
<a href="{{ path('etudiant') }}">
return
</a>
</li>
</ul>
{% endblock %}
so i solved
so it should be
{% extends '::base.html.twig' %}
{% block body -%}
<form action="{{ path('etudiant') }}" {{form_enctype(form)}} method="post" >
<table>
<tr>
<td>Libelle: </td>
<td>{{ form_widget(form.libelle)}}
</tr>
</table>
< input type="submit" />
{{ form_rest(form) }}
</form>
<ul class="record_actions">
<li>
<a href="{{ path('etudiant') }}">
return
</a>
</li>
{% endblock %}

Resources