Get default datetime form on Symfony 2 twig - php

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")}) }}

Related

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

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

symfony- update entity and changed fields

I try editAction in symfony but I have error when if not change input file it update field file in database to null ... how to not update field file if not changed value in update action
code action:
/**
* #Route("/babysitter/update/{id}", name="update_babysitter_by_admin")
*
* #param Request $request
* #param BabySitter $babySitter
* #ParamConverter("id", options={"id": "id"})
*
* #return mixed
*/
public function updateBabySitterAction(BabySitter $babySitter, Request $request){
$em= $this->getDoctrine()->getManager();
$form= $this->createForm(BabySitterType::class, $babySitter,['requiredFile'=> false]);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
if($babySitter->getPicture()->getDocument()){
$this->uploadDocument->upload($babySitter->getPicture(), $this->getParameter('pictures_directory'));
}
if($babySitter->getCriminalRecord()->getDocument()){
$this->uploadDocument->upload($babySitter->getCriminalRecord(), $this->getParameter('criminalRecord_director_babySitter'));
}
if($babySitter->getIdCards()){
$this->uploadDocument->uploadIdCard($babySitter->getIdCards(), $babySitter,$this->getParameter('idCard_directory'));
}
$em->persist($babySitter);
$em->flush();
$url = $this->generateUrl('info_babySitter',['id'=> $babySitter->getId()]);
$response = new RedirectResponse($url);
return $response;
}
return $this->render('admin/registerBabySitter.html.twig',[
'form'=> $form->createView()
]);
}
code twig:
{% trans_default_domain 'FOSUserBundle' %}
<div class="register-box" style="width:460px">
<div class="register-box-body">
<p class="login-box-msg">Register a new BabySitter</p>
{{ form_start(form, {'method':'post', 'attr': {'class': 'fos_user_registration_register', 'novalidate': 'novalidate'}}) }}
<div class="form-group has-feedback">
{{ form_widget(form.email,{'attr': {'class': 'form-control', 'placeholder': 'Email'}}) }}
{{ form_errors(form.email) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.firstName,{'attr': {'class': 'form-control', 'placeholder': 'FirstName'}}) }}
{{ form_errors(form.firstName) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.lastName,{'attr': {'class': 'form-control', 'placeholder': 'LastName'}}) }}
{{ form_errors(form.lastName) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.plainPassword.first,{'attr': {'class': 'form-control', 'placeholder': 'Password'}}) }}
{{ form_errors(form.plainPassword.first) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.plainPassword.second,{'attr': {'class': 'form-control', 'placeholder': 'Repeat Password'}}) }}
{{ form_errors(form.plainPassword.second) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.genre,{'attr': {'class': 'form-control', 'placeholder': 'Genre'}}) }}
{{ form_errors(form.genre) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.dateBirth,{'attr': {'class': 'form-control', 'placeholder': 'date Birthday'}}) }}
{{ form_errors(form.dateBirth) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.linkVideo,{'attr': {'class': 'form-control', 'placeholder': 'link Video'}}) }}
{{ form_errors(form.linkVideo) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.criminalRecord) }}
{{ form_errors(form.criminalRecord) }}
</div>
<div class="form-group has-feedback">
<ul id="idCard-fields-list"
data-prototype="{{ form_widget(form.idCards.vars.prototype)|e }}"
data-widget-tags="{{ '<li></li>'|e }}">
{{ form_row(form.idCards) }}
{% for idCardField in form.idCards %}
<li>
{{ form_errors(idCardField) }}
{{ form_widget(idCardField) }}
</li>
{% endfor %}
</ul>
<div class="row">
<button type="button"
class="add-another-collection-widget-idCard btn btn-primary btn-flat"
data-list="#idCard-fields-list">Add another idCard</button>
</div>
</div>
<div class="form-group has-feedback">
{{ form_widget(form.nbrYears,{'attr': {'class': 'form-control', 'placeholder': 'Number Years'}}) }}
{{ form_errors(form.nbrYears) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.rib,{'attr': {'class': 'form-control', 'placeholder': ' rib'}}) }}
{{ form_errors(form.rib) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.presentation,{'attr': {'class': 'form-control', 'placeholder': 'presentation'}}) }}
{{ form_errors(form.presentation) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.adress) }}
{{ form_errors(form.adress) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.availability) }}
{{ form_errors(form.availability) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.assignement) }}
{{ form_errors(form.assignement) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.qualification) }}
{{ form_errors(form.qualification) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.picture) }}
{{ form_errors(form.picture) }}
</div>
<div class="form-group has-feedback">
<ul id="language-fields-list"
data-prototype="{{ form_widget(form.languages.vars.prototype)|e }}"
data-widget-tags="{{ '<li></li>'|e }}">
{{ form_widget(form.languages) }}
{% for languageField in form.languages %}
<li>
{{ form_errors(languageField) }}
{{ form_widget(languageField) }}
</li>
{% endfor %}
</ul>
<div class="row">
<button type="button"
class="add-another-collection-widget btn btn-primary btn-flat"
data-list="#language-fields-list">Add another language</button>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="{{ 'registration.submit'|trans }}">
</div>
<!-- /.col -->
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
<!-- /.form-box -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('.add-another-collection-widget').click(function (e) {
var list = jQuery(jQuery(this).attr('data-list'));
// 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);
addTagFormDeleteLink(newElem);
});
function addTagFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<button class="btn btn-danger btn-flat" style="margin-top:2%;margin-left:50%" type="button">Delete this Language</button>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
jQuery('.add-another-collection-widget-idCard').click(function (e) {
var list = jQuery(jQuery(this).attr('data-list'));
// 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);
if(counter <= 3){ newElem.appendTo(list); }
});
function addIdCardFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<button class="btn btn-danger btn-flat" style="margin-top:2%;margin-left:50%" type="button">Delete this idCard</button>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
});
</script>
when i update entity and i not update field file i have field file in database null ... how to update entity without changed in input file

Symfony - How to format an entity field in a form (to display more fields than just title)?

I have a form where user can submit a new Mandate. Every Mandate can have multiple Profiles linked to it.
Here is how the form looks like at this moment:
The Profiles field is added to the form like that (from MandateController):
$form = $this->createFormBuilder($mandate)
->add('content')
->add('name')
->add('company_name')
->add('budget')
->add('phone')
->add('email')
->add('description')
->add('profiles', EntityType::class, array(
'multiple' => true,
'expanded' => true,
'class' => 'KrownDashboardBundle:Profile',
'choice_label' => 'title',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('p')
->orderBy('p.title', 'ASC');
},
))
->getForm();
And the view is handled this way:
{{ form_start(form) }}
{{ form_errors(form) }}
<div>
<div class="col_full">
<label for="" class="control-label">{{ form_label(form.content) }}</label>
{{ form_widget(form.content, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.content) }}
</div>
<div class="col_full">
<label for="" class="control-label">Prénom et nom</label>
{{ form_widget(form.name, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.name) }}
</div>
<div class="col_full">
<label for="" class="control-label">Nom de lentreprise</label>
{{ form_widget(form.company_name, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.company_name) }}
</div>
<div class="col_full">
<label for="" class="control-label">Budget</label>
{{ form_widget(form.budget, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.budget) }}
</div>
<div class="col_full">
<label for="" class="control-label">Numéro de téléphone</label>
{{ form_widget(form.phone, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.phone) }}
</div>
<div class="col_full">
<label for="" class="control-label">E-mail</label>
{{ form_widget(form.email, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.email) }}
</div>
<div class="col_full">
<label for="" class="control-label">Description</label>
{{ form_widget(form.description, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.description) }}
</div>
<div class="col_full">
<label for="" class="control-label">Profiles</label>
{{ form_widget(form.profiles) }}
{{ form_errors(form.profiles) }}
</div>
</div>
<button id="login-form-submit" class="button button-3d button-black nomargin" value="Log in" name="login-form-submit">Ok</button>
{{ form_end(form) }}
I want to modify the Profiles listing, so they look like this (all these fields are saved into the Profile entity):
Instead:
How can I achieve that? What's the best way to do it?

Twig shows extra fields

I have a simple form which looks like this
.......
$builder
->add('name', 'text')
->add('email', 'text'
->add('save', 'submit')
->getForm();
What I want is to render only the name field
{{ form_start(form, {'attr': {'role': 'form', 'novalidate' : 'novalidate'} }) }}
{{ form_label(form.name) }}
{{ form_widget(form.name, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors(name.name, { 'attr': {'class': 'form-control'} }) }}
{{ form_end(form)
As result I get the page rendered with both name and email fields. What I'm doing wrong and how to prevent rendering of email field?
In according with the doc, if you don't want to render unrendered fields, you can use:
{{ form_end(form, {'render_rest': false}) }}
Hope this help
If your field is not required, you can do :
{{ form_label(form.email, null, {'label_attr': {'class':'hidden'}}) }}
{{ form_widget(form.email, { 'attr': {'class': 'form-control hidden'} }) }}
{{ form_errors(name.email, { 'attr': {'class': 'form-control hidden'} }) }}
Hope this helps.

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.

Categories