How to display error on my input file on Symfony 4? - php

I work on my first symfony project and I need to create nice errors for a form with an uploading input.
Actually, I change with success my parameters to a limit post of 20Mo and a limit size for an uploaded file of 20Mo.
In my entity, I have an Assert (by symfony) on my property "portfolio".
/**
* #Assert\File(
* maxSize="5M",
* mimeTypes = {"application/pdf"},
* mimeTypesMessage = "Votre fichier doit être au format PDF"
* )
*/
public $portfolio;
Btw i made my import like asked in the symfony documentation.
I have the twig expression to display my errors directly when i try to validate a wrong form.
Here is my controller's function :
public function formjob(\Swift_Mailer $mailer, Request $request)
{
$job = new JobForm();
$form = $this->createFormBuilder($job)
->add("name", TextType::class, [
"label" => "Nom :"
])
->add("firstName", TextType::class, [
"label" => "Prénom :"
])
->add("mail", EmailType::class, [
"label" => "E-mail :"
])
->add("telephone", TelType::class, [
"label" => "Tel. ",
"required" => false,
"empty_data" => "Non Renseigné"
])
->add("url", UrlType::class, [
"label" => "Envoyez-nous l’adresse internet vers vos réalisations",
"required" => false,
])
->add("portfolio", FileType::class, [
"label" => "Envoyez votre portfolio au format PDF",
"required" => false,
"error_bubbling" => true
])
->add("envoyer", SubmitType::class)
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$attachment = $data->portfolio;
$mail = $data->mail;
if(isset($attachment) || isset($data->url)) {
$message = (new \Swift_Message())
->setSubject('Formulaire Job')
->setFrom($mail)
->setTo('nicolas.trinquet#laposte.net')
->setBody(
$this->renderView(
'mail/mailjob.html.twig', [
'data' => $data
]
),
'text/html'
);
if (isset($attachment)) {
$message->attach(\Swift_Attachment::fromPath($attachment)->setFilename('portfolio.pdf')->setContentType('application/pdf'));
}
$mailer->send($message);
return $this->redirectToRoute('sent');
}
}
return $this->render('main/formJob.html.twig', [
'form'=> $form->createView(),
]);
}
And here is my template :
{% extends 'layout.html.twig' %}{% block title %}Jobs{% endblock %}{% block stylesheets %}<link rel="stylesheet" type="text/css" href="formJobs.css"> {% endblock %}{% block body %}<div class="row">
<div class="col-lg-12">
<h1 class="antiqueO">Postuler</h1>
<h2 class="robotoR">Intitulé du poste</h2>
<h3 class="robotoM">Type de poste</h3>
<p class="robotoR">Description du poste</p>
<div class="trait_noir_separation"></div>
{{ form_start(form) }}
<div class="col-lg-12">
{{ form_label(form.name) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.name) }}
{{ form_widget(form.name) }}
</div>
<div class="col-lg-12">
{{ form_label(form.firstName) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.firstName) }}
{{ form_widget(form.firstName) }}
</div>
<div class="col-lg-12">
{{ form_label(form.mail) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.mail) }}
{{ form_widget(form.mail) }}
</div>
<div class="col-lg-12">
{{ form_label(form.telephone) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.telephone) }}
{{ form_widget(form.telephone) }}
</div>
<div class="col-lg-12">
{{ form_label(form.url) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.url) }}
{{ form_widget(form.url) }}
</div>
<div class="col-lg-12">
{{ form_label(form.portfolio) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.portfolio) }}
{{ form_widget(form.portfolio, {'attr': {'class': 'form-control-file', 'accept' : 'application/pdf'}})}}
</div>
<div>
{{ form_widget(form.envoyer, {'attr': {'class': 'antiqueO send_button'}}) }}
</div>
{{ form_end(form) }}
</div>
</div>{% endblock body %}
Actually i have a problem : all my errors can be triggered and displayed.
BUT the error on my file input refuse to be displayed even if i have the error in my profiler toolbar :
Profiler Toolbar for size error
Profiler Toolbar for format error
What is the problem in my code? What is blocking my error display?

Based in https://symfony.com/doc/current/reference/forms/types/text.html#error-bubbling
error_bubbling
type: boolean default: false unless the form is compound
If true, any errors for this field will be passed to the parent field or form. For example, if set to true on a normal field, any errors for that field will be attached to the main form, not to the specific field.
So as you are using this attribute in portfilo property, the error is showing on
{{ form_errors(form) }}
and not in
{{ form_errors(form.portfolio) }}
Just try to remove error_bubbling from portfolio property in formjob function and the error should be showed in your form

Related

Cannot find variable - Variable "form" does not exist in...

I am trying to create a simple form within Symfony. Not quite sure why this is not grabbing the form variable.
Receiving error:
Variable "form" does not exist src/Thinkfasttoys/MapWatchBundle/Resources/views/Default/createMapPolicy.html.twig at line 30
Controller - DefaultController.php
class DefaultController extends Controller
{
public function policyFormAction()
{
$form = $this->createFormBuilder()
->add('name', 'text')
->add('age', 'integer')
->add('save', 'submit')
->getForm()
;
return $this->render('ThinkfasttoysMapWatchBundle:Default:createMapPolicy.html.twig', array(
'form' => $form->createView(),
));
}
View - createMapPolicy.html.twig
{% block body %}
<div class="row-fluid">
<div class="span12">
<div class="widget-box">
<h4 align="center", padding="10px 0 10px 0">Create a New MAP Policy</h4>
{{ form(form) }}
<div class="container-1">
</div><!-- /.container -->
</div><!-- /.widgetbox -->
</div>
</div>
{% endblock %}
In twig you have to display the form like this:
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

Add the first entity of a collectionType

I have two entities, Registro and RegistroProfesional.
One Registro has many RegistroProfesional. (OneToMany).
In the form, I want the first RegistroProfesional to appear, but it gives me the error "Entities passed to the choice field must be managed. Maybe they persist in the entity manager?"
This is my field in formtype:
$builder->add('registroProfesionales','collection', array(
'type'=> new RegistroProfesionalType(),
'cascade_validation' => true,
'allow_delete' => true,
'allow_add' => true,
'prototype' => true,
'prototype_name' => '__registro_profesionales__',
'label' => false
))
In my controller:
$entity = new Registro();
$registroProfesional = new RegistroProfesional();
$entity->addRegistroProfesionale($registroProfesional); // Here add the first RegistroProfesional
$flow = $this->get('biobanco.form.flow.crearRegistro');
$flow->bind($entity);
$form = $flow->createForm();
if ($flow->isValid($form)) {
$flow->saveCurrentStepData($form);
if ($flow->nextStep()) {
// form for the next step
$form = $flow->createForm();
} else {
//dump($form,$entity);die();
// flow finished
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$flow->reset(); // remove step data from the session
$this->enviarCorreo($entity->getId(), 'REGISTRO');
return $this->render('BiobancoBundle:Registro:realizado.publico.html.twig');
}
}
View:
{% for rp in form.registroProfesionales %}
<div class="col-sm-6 col-xs-12">
<label>Nombre</label>
{{ form_widget(rp.nombre) }}
{% if form_errors(rp.nombre) is not empty %}
<div class="alert alert-danger alert_form alert-dismissible fade in" role="alert">
{{ form_errors(rp.nombre) }}
</div>
{% endif %}
</div>
<div class="col-sm-6 col-xs-12">
<label>Primer Apellido</label>
{{ form_widget(rp.apellido1) }}
{% if form_errors(rp.apellido1) is not empty %}
<div class="alert alert-danger alert_form alert-dismissible fade in" role="alert">
{{ form_errors(rp.apellido1) }}
</div>
{% endif %}
</div>
<div class="col-sm-6 col-xs-12">
<label>Segundo Apellido</label>
{{ form_widget(rp.apellido2) }}
{% if form_errors(rp.apellido2) is not empty %}
<div class="alert alert-danger alert_form alert-dismissible fade in" role="alert">
{{ form_errors(rp.apellido2) }}
</div>
{% endif %}
</div>
<div class="col-sm-6 col-xs-12">
<label>Email</label>
{{ form_widget(rp.email) }}
{% if form_errors(rp.email) is not empty %}
<div class="alert alert-danger alert_form alert-dismissible fade in" role="alert">
{{ form_errors(rp.email) }}
</div>
{% endif %}
</div>
{% endfor %}
Where is the problem?
The problem, most probably, is not in the code you've listed.
I would say you've got something in $form = $flow->createForm(); or in RegistroProfesionalType itself. Apparently, you've got somewhere some kind of choice field (probably, EntityType, i.e usual doctrine relation) and mapped on this field property has a value which is not yet persisted.

Get default datetime form on Symfony 2 twig

i have some probleme, i would like to have a default value in my datetime twig, i dont want to have the defaut value from BuildForm cause i use it for other twigs.
My add twig
<div class="form-group">
{{ form_label(form.Url, "Le URL", {'label_attr': {'class': 'col-sm-4 textTab control-label'}}) }}
{{ form_errors(form.Url) }}
<div class="col-sm-6">
{{ form_widget(form.Url, {'attr': {'class': 'form-control'}}) }}
</div>
</div>
<div class="form-group">
{{ form_label(form.dateDeLaDemande, "Date de la demande du crawl", {'label_attr': {'class': 'col-sm-4 textTab control-label'}}) }}
{{ form_errors(form.dateDeLaDemande) }}
<div class="col-sm-6" style="margin-top: 8px;">
{{ form_widget(form.dateDeLaDemande, {'attr': {'class': 'col-sm-6'}}) }}
</div>
</div>
<div class="form-group">
{{ form_label(form.DateDuCrawl, "Date du crawl", {'label_attr': {'class': 'col-sm-4 textTab control-label'}}) }}
{{ form_errors(form.DateDuCrawl) }}
<div class="col-sm-6" style="margin-top: 8px;">
{{ form_widget(form.DateDuCrawl, {'attr': {'class': 'col-sm-6' }}) }}
</div>
</div>
And my buildFom
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('site','text')
->add('Url','url')
->add('dateDeLaDemande','date')
->add('DateDuCrawl','date')
->add('DateNextCrawl','date')
->add('faitVP', 'checkbox', array('required' => false))
->add('integrerMavec','checkbox', array('required' => false))
// ->add('historique','textarea')
->add('historiques', 'collection', array(
'type' => new CategoryType(),
'allow_add' => true,
'allow_delete' => true
))
->add('save','submit')
;
}
Can some one help me plz ? thanks and sorry about my english :)
Try something like this
{{ form_widget(form.form.dateDeLaDemande, {value : currentDate}) }}
To declare a variable in twig :
{% set currentDate = "now"|date("m/d/Y") %}
or directely :
{{ form_widget(form.form.dateDeLaDemande, {value : "now"|date("m/d/Y")}) }}

Symfony change style of 'repeated' field

I have a form with a repeated field:
$builder->add('password', 'repeated', array( 'type' => 'password' ));
I want this repeated field to render differently from the other fields - how do I do that? I'm new to Symfony and twig, so if you have suggestions with code, please add some information as to where to put the code.
My form.html.twig looks like this:
{{ form_widget(form) }}
Thanks in advance.
This is how i display my repeated field using twitter bootstrap, of course you can change those classes to the one you are using
<form action="{{ path('passwordReset') }}" method="post" role="form">
{{ form_errors(form) }}
<div class="login-screen">
<h4>Reset Your Password</h4>
<div class="login-form">
<div class="form-group">
{{ form_widget(form.password.first, { 'attr': {'class': 'form-control', 'placeholder': 'Enter your password', 'value':''} }) }}
{% if(form_errors(form.password.first)) %}
<div class="alert alert-danger">{{ form_errors(form.password.first) }}</div>
{% endif %}
<label class="login-field-icon fui-lock" for="login-password"></label>
</div>
<div class="form-group">
{{ form_widget(form.password.second, { 'attr': {'class': 'form-control', 'placeholder': 'Confirm your password', 'value':''} }) }}
{% if(form_errors(form.password.second)) %}
<div class="alert alert-danger">{{ form_errors(form.password.second) }}</div>
{% endif %}
<label class="login-field-icon fui-lock" for="login-name"></label>
</div>
<button class="btn btn-primary btn-lg btn-block" type="submit">Submit</button>
<a class="login-link" href="{{ path('login') }}">Sign in</a>
</div>
</div>
{{ form_rest(form) }}
</form>
What you need are the following two
{{ form_widget(form.password.first, { 'attr': {'class': 'form-control', 'placeholder': 'Enter your password', 'value':''} }) }}
{{ form_widget(form.password.second, { 'attr': {'class': 'form-control', 'placeholder': 'Confirm your password', 'value':''} }) }}
Just assign them the class you want to assign them to make them look different.
Helo
'first_options' => array('label' => 'form.password','attr' => array('class' => 'mystyle'))
something like that in the formType, it add a class to your input element and let you customize.

custom form widget Symfony 2 but return An exception in the controller

I'm trying to custom my form in symfony2 using {{ form_widget(form) }}
so my buildForm is like this :
$builder
->add('Status', 'choice', array(
'choices' => array('Required' => 'Required', 'Free' => 'Free', 'OnArrival' => 'OnArrival', 'Refused' => 'Refused'),
'required' => true,
'label' => 'Visa required?'
))
->add('Length', null, array('required' => false, 'label' => 'Max Stay'))
->add('Description', 'textarea',array('required' => false, 'label' => 'Additional information'));
my twig html :
{% block choice_widget %}
<div class="row">
<div class="col-md-8 ">
<select class="selectpicker " data-style="btn-primary">
{% spaceless %}
{% for choice in choices %}
<option value="{{ choice.value }}">{{ choice.value }}</option>
{% endfor %}
{% endspaceless %}
</select>
</div>
</div>
{% endblock %}
{% block text_widget %}
<div class="row">
<div class="col-md-8 ">
<input id="id_max" type="text" placeholder=" x Month(s)" class="form-control">
</div>
</div>
{% endblock %}
{% block textarea_widget %}
<textarea id="id_desc" type="" placeholder="" class="form-control"></textarea>
{% endblock %}
it shows me well the new style applied but when I execute my form it return me an exception and said that values are null ie : Status=null , length=null, description=null
PS : when I retrieve the custom html it works well
EDIT : add the controller part
/**
* Creates a new TravelInfoCorrection entity.
*
* #Route("/correct/create", name="correct_create")
* #Method("POST")
* #Template("TechyVisaBundle:edit:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new TravelInfoCorrection();
$form = $this->createForm(new TravelInfoCorrectionType(), $entity);
$form->bind($request);
$entity->setCreatedAt(new \DateTime('now'));
$entity->setProcessedFlag('Pending');
if (! $form->isValid()) throw new \Exception('Form not valid');
$em = $this->getDoctrine()->getManager();
$orientity = $em->getRepository('TechyVisaBundle:TravelInfo')
->findOneBy(array( 'TravFrom' => $entity->getTravFrom(), 'TravTo' => $entity->getTravTo() ));
$isdiff = false;
$isdiff = $isdiff || ($entity->getStatus() != $orientity->getStatus());
$isdiff = $isdiff || ($entity->getLength() != $orientity->getLength());
$isdiff = $isdiff || ($entity->getDescription() != $orientity->getDescription());
if ($isdiff){
$em->persist($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('thanks'));
}
and the caller html :
{% form_theme form 'TechyVisaBundle:Form:fields.html.twig' %}
{% block content %}
<br/>
<div id="sign_up1">
<div class="container">
<h2>Edit information {{ from.getName }} to {{ to.getName }} travelling information</h2>
<b style="color: red;">Please verify your informations <a target="_blank" rel="nofollow" href="http://www.gulfair.com/English/info/prepare/Pages/VisaInformation.aspx">here</a> before posting it</b>
<br/>
<form action="{{ path('correct_create') }}" method="post" {{ form_enctype(form) }} class="form-inline">
{{ form_widget(form) }}
<button type="submit">Submit correction</button>
</form>
</div>
</div>
{% endblock %}

Categories