I have simple edit form where the user will have to fill up required fields. The problem is the validation of required fields doesn't show, and also the fields or data don't change.
UPDATE I var_dump the $form->isSubmitted() and it shows bool(false)
Here's my controller:
public function editAction(Request $request, $id) {
$company = $this->getDoctrine()
->getRepository('SwipeBundle:Company')
->find($id);
if(!$company) {
throw $this->createNotFoundException(
'No Company found for id '.$id
);
}
$form = $this->createForm(CompanyType::class, $company, array(
'action'=>$this->generateUrl('swipe_backend_company_edit', array('id'=>$company->getId())),
'method'=>'PUT'
));
if ($request->getMethod() == "POST") {
if ($form->isSubmitted()) {
// $em->persist($company);
// $em->flush();
echo "Update";
}
}
return $this->render('Backend/Company/edit.html.twig', array(
'form'=>$form->createView(),
'company'=>$company
));
}
And here's my twig template:
{% extends '::Backend/base.html.twig' %}
{% block body %}
<!-- Section -->
<section class="sections">
<!-- Side Bar -->
{% include '::Backend/side_menu_bar.html.twig' %}
<!-- Wrapper -->
<div id="administrator" class="wrapper">
<div class="mt40 pt30"> <!-- Container -->
<h1 class="mb10 bold">Edit Company</h1>
<p class="mb30">Fill up all the required fields for Company.</p>
{% if not form.vars.valid %}
<p class="alert note-error">
There are errors in your form. Please check the fields marked in red.
</p>
{% endif %}
<div class="alert note-error">
<p>Fields with asterisk (*) are required</p>
</div>
{% set url = path('swipe_backend_company_edit', { 'id': company.id }) %}
<form novalidate method="post" action="{{ url }}" class="p20 card mb30">
<div class="sections pb30 pt10">
<fieldset class="col span6">
{% set attr = {} %}
{% if form_errors(form.name) is not empty %}
{% set attr = attr|merge({ 'class': 'alert error'}) %}
{% endif %}
<label for="" class="input-required">
<strong>Company Name<span class="highlight-red">*</span>
</strong>
</label>
{{ form_widget(form.name, { 'attr': attr } ) }}
{% if not form.name.vars.valid %}
<p class="mt10" style="color: #DC2B1B;">
{{ form.name.vars.errors[0].message }}
</p>
{% endif %}
</fieldset>
<fieldset class="col span6">
<strong>
{{ form_label(form.website) }}
</strong>
{{ form_widget(form.website) }}
</fieldset>
</div>
<div class="sections pb30 pt10">
{% set attr = {} %}
{% if form_errors(form.email_address) is not empty %}
{% set attr = attr|merge({ 'class': 'alert error'}) %}
{% endif %}
<label for="" class="input-required">
<strong>Company Email Address<span class="highlight-red">*</span>
</strong>
</label>
{{ form_widget(form.email_address, { 'attr': attr } ) }}
{% if not form.email_address.vars.valid %}
<p class="mt10" style="color: #DC2B1B;">
{{ form.email_address.vars.errors[0].message }}
</p>
{% endif %}
</div>
<div class="sections pb30 pt10">
<fieldset class="col span6">
<strong>
{{ form_label(form.telephone_no) }}
</strong>
{{ form_widget(form.telephone_no) }}
</fieldset>
<fieldset class="col span6">
<strong>
{{ form_label(form.mobile_no) }}
</strong>
{{ form_widget(form.mobile_no) }}
</fieldset>
</div>
<div class="sections pb30 pt10">
{% set attr = {} %}
{% if form_errors(form.address) is not empty %}
{% set attr = attr|merge({ 'class': 'alert error'}) %}
{% endif %}
<label for="" class="input-required">
<strong>Company Address<span class="highlight-red">*</span>
</strong>
</label>
{{ form_widget(form.address, { 'attr': attr } ) }}
{% if not form.address.vars.valid %}
<p class="mt10" style="color: #DC2B1B;">
{{ form.address.vars.errors[0].message }}
</p>
{% endif %}
</div>
<div class="text-right mt20 mb10">
<button class="btn btn-positive mt10 mr5">Update Company</button>
<button class="btn btn-positive mt10 mr5">Cancel</button>
</div>
{{ form_rest(form) }}
</form>
</div> <!-- Container End -->
</div> <!-- Wrapper End -->
</section> <!-- Section End -->
{% endblock %}
Only one action for edit / Update the record
public function editAction($id) {
$em = $this->getDoctrine()->getManager();
$company = $em
->getRepository('SwipeBundle:Company')
->find($id);
if(!$company) {
throw $this->createNotFoundException(
'No Company found for id '.$id
);
}
$form = $this->createForm(CompanyType::class, $company, array(
'action'=>$this->generateUrl('swipe_backend_company_update', array('id'=>$company->getId())),
'method'=>'PUT'
));
if ($request->getMethod() == "POST") {
if ($form->isValid()) {
$em->persist($company);
$em->flush();
}
}
return $this->render('Backend/Company/edit.html.twig', array(
'form'=>$form->createView(),
'company'=>$company
));
}
and also Change the form action in twig same a edit action
Make sure this is useful to you.
Related
The following error occurred in Symfony4.
There are many posts with the same error, but I couldn't find the one in this case.
When I deleted the //Error part in the Twig file, the error disappeared, so I know it's the cause, but I don't know how to fix it.
What are your good ideas?
However, deleteAction is not used in //Error part and is incomprehensible.
The CSRF token is invalid. Please try to resubmit the form.
Article.php
protected function deleteAction(Request $request, $ids)
{
$token = $request->request->get('_csrf_token');
$csrf_token = new CsrfToken('authenticate', $token);
if (!$this->get("security.csrf.token_manager")->isTokenValid($csrf_token)) {
//Error code
throw new HttpException("400", "The CSRF token is invalid. Please try to resubmit the form.");
}
}
index.html.twig
{{ form_start(form) }}
<div class="formGroup trendTags"
data-prototype="{{ macros.trendTagForm(form.trendTags.vars.prototype)|e }}"
data-index="{{ ec_tag_contents|length }}">
<label>Tag</label>
<button type="button" class="add btn">Add</button>
<ul class="trend-tag-list2" {% if not ec_tag_contents|default %} style="display:none"{% endif %} id="trendTagsWrap">
{% for tag in ec_tag_contents|default %}
<li>
<div class="tagForm">
<div class="input-trendtag-display-name"> {{ tag.name }}</div>
<div class="input-trendtag-display-term">({{ tag.str_tag_display }} {{ tag.str_term }})</div>
<br>
{% for category in tag.categories|split(',') %}
<div class="tag-form__category-sticker" name="{{ category }}">{{ category }}</div>
{% endfor %}
<button class="removeTrendTag"><i class="icon-remove"></i></button>
</div>
<div id="brandevent_trendTags_{{ loop.index0 }}">
<input type="hidden" id="brandevent_trendTags_{{ loop.index0 }}_trendTagId" name="brandevent[trendTags][{{ loop.index0 }}][trendTagId]" required="required" value="{{ tag.tag_id }}">
</div>
</li>
{% endfor %}
{% do form.trendTags.setRendered(true) %}
</ul>
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
{% set url = path("app_hq_article_index", {"articleType": "article", "num": 5, "modal": true}) %}
<div id="relatedArticleDialog" title="Article Selection" data-url="{{ url }}">
</div>
//Error part
{% set q = app.request.query.get("q")|default({}) %}
{% set trendTagUrl = path("app_hq_article_trendtag", {"q[sex]": q.sex|default(0), "q[brand_id]": q.brand_id|default(), "q[del_flg]": 0}) %}
<div id="trendTagDialog" title="Tag Selection" data-url="{{ trendTagUrl }}">
</div>
trendTag.html.twig
<div class="search">
{% include '#AppBundle/Shop/Article/trendTagForm.html.twig' %}
</div>
trendTagForm.html.twig
<form id="frm-trend-tag-search" name="frm-trend-tag-search" method="get" action="{{path('app_hq_article_trendtag')}}">
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
...
</form>
Add the {{form_widget(form._token)}} hidden field to the main form
or
Disable the CSRF token in form config:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'csrf_protection' => false,
]);
}
Now i hav this. How do I group by the field hotel.name?
And yes, I saw this post, but it does not work.
Twig Loop Grouping
{% for item in pagination.items %} <!-- Вывод результатов по отелям -->
<div class="row">
<div class="col-lg-1">{{ loop.index }}</div>
<div class="col-lg-6">
<span class="text-capitalize">{{ item.hotel.name }}</span>
<span class="text-primary">{{ item.roomName }}</span>
{% if(item.mealName) %}
<span class="text-muted">({{ item.mealName }})</span>
{% endif %}
</div>
<div class="col-lg-2">{{ item.price }} {{ item.currency }}</div>
</div>
{% endfor %}
I need get this:
We were advised to use the groop_by, but I do not understand how.
{% for item,
group in pagination|group_by(=>_.hotel.name)
%} <!-- Вывод результатов по отелям -->
<div class="row">
<div class="col-lg-1">{{ loop.index }}</div>
<div class="col-lg-6">
<span class="text-capitalize">{{ item.hotel.name }}</span>
<span class="text-primary">{{ item.roomName }}</span>
{% if(item.mealName) %}
<span class="text-muted">({{ item.mealName }})</span>
{% endif %}
</div>
<div class="col-lg-2">{{ item.price }} {{ item.currency }}</div>
</div>
{% endfor %}
Controller:
public function resultsAction($searchId, $page)
{
$em = $this->getDoctrine()->getManager();
$objSearchRequest = $em->find('UtsHotelBundle:SearchRequest', $searchId);
if(!$objSearchRequest){
$this->createNotFoundException();
}
$objSearchForm = $this->createForm('uts_hotel_search_request', $objSearchRequest);
$templateVars = array(
'searchForm' => $objSearchForm->createView(),
'request' => $objSearchRequest
);
if($objSearchRequest->isComplete() || $objSearchRequest->isOld()){
$repository = $em->getRepository('UtsHotelBundle:SearchResult');
$query = $repository->createQueryForPagination($searchId);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($query, $page, 50);
$templateVars['pagination'] = $pagination;
}
return $this->render('UtsHotelBundle:Default:results.html.twig', $templateVars);
}
Answer:
{% set date = null %}
{% set otelindex=0 %}
{% for item in pagination.items %} <!-- Вывод результатов по отелям -->
{% if date != item.hotel.name %}
{% set date = item.hotel.name %}
{% set otelindex=otelindex+1 %}
<div class="row">
<div class="col-lg-6">
<h4>{{ otelindex }}{{ ". " }}{{item.hotel.name}}</h4>
</div>
<div class="col-lg-2">
<h4> {{ item.mealName }}{{ item.price }} {{ item.currency }}</h4>
</div>
</div>
{% endif %}
<div class="row">
<div class="col-lg-6">
<span class="text-primary">{{ item.roomName }}</span>
{% if(item.mealName) %}
<span class="text-muted">({{ item.mealName }})</span>
{% endif %}
</div>
<div class="col-lg-2">{{ item.price }} {{ item.currency }}</div>
</div>
{% endfor %}
I have 3 entities: User (part of FOSUserBundle), Comment, Article.
I'd like to display a comment form on the article only of the visitor is logged in. It was displaying for everybody just fine.
My code doesn't work and also seems like very bad practice. I get "Variable "form" does not exist." because I'm stopping the form from getting passed to the view. Is the necessary if I put an if in the view? I'd appreciate any suggestions on how I can accomplish this!
Thanks a bunch.
My comment.html.twig
{% extends 'base.html.twig' %}
{% block body %}
{% form_theme form 'form/fields.html.twig' %}
{% if is_granted('ROLE_USER') -%}
<div class="form-group">{{ form_start(form) }}</div>
<div class="form-group">{{ form_row(form.comment.title) }}</div>
<div class="form-group">{{ form_row(form.comment.rating) }}</div>
<div class="form-group">{{ form_row(form.comment.comment) }}</div>
<div class="form-group">{{ form_row(form.comment.user.firstName) }}</div>
<div class="form-group">{{ form_row(form.comment.user.lastName) }}</div>
<div class="form-group">{{ form_row(form.comment.user.email) }}</div>
<input class="btn btn-default" type="submit" value="Create" />
{{ form_end(form) }}
{% else %}
<p>Please log in to post a comment!</p>
{% endif %}
{% endblock %}
My show.html.twig (for articles)
{% extends 'base.html.twig' %}
{% block body_id 'articlepage' %}
{% block body %}
<h1>Article: {{ article.name }}</h1>
<div class="well"><div class="media">
<div class="media-left media-top">
<img class="media-object" src="{{ article.thumbnail }}">
</div>
<div class="media-body">
<h4 class="media-heading">{{ article.name }}</h4>
<p>{{ article.description }}</p>
</div>
</div></div>
<h2>Article Comments:</h2>
{{ render(controller('AppBundle:Comment:index', {'article_id': article.id})) }}
<h2>Submit a new comment:</h2>
{{ render(controller('AppBundle:Article:comment', {'id': article.id})) }}
{% endblock %}
commentAction within ArticleController.php (a controller that gets embedded in the show.html.twig)
public function commentAction(Request $request, Article $article)
{
$auth_checker = $this->get('security.userization_checker');
$token = $this->get('security.token_storage')->getToken();
$user = $token->getUser();
$isRoleUser = $auth_checker->isGranted('ROLE_USER');
if($isRoleUser){
$comment = new Comment();
//Build the comment form.
$commentForm = $this->createFormBuilder($comment)
->add('comment', CommentType::class, array("label" => FALSE))
->setAction($this->generateUrl('article_comment', array('id' =>$article->getId())))
->getForm();
$commentForm->handleRequest($request);
if ($commentForm->isSubmitted() && $commentForm->isValid()) {
//Update existing user or create new
$em = $this->getDoctrine()->getManager();
$comment = $commentForm->getData()->getComment();
$user = $this->getUser($comment->getUser());
//Update the existing comment or get a new one
$user = $this->getUser($comment->getUser());
$comment = $this->getComment($user, $article, $comment);
//Set the user and article for the comment.
$comment->setUser($user);
$comment->setArticle($article);
$em->persist($comment);
$em->flush($comment);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('article_show', array('id' => $article->getId()));
}
return $this->render('article/comment.html.twig', array(
'form' => $commentForm->createView(),
));
} else {
return $this->render('article/comment.html.twig');
}
}
If you want to check whether user logged in or not in your Twig templates, you could use app.user variable:
{% if app.user %}
{{ render(controller('AppBundle:Comment:index', {'article_id': article.id})) }}
{% endif %}
I have a controller that does this
/**
* #Route("/AjaxAddQuestionForm/{section}")
* #ParamConverter("section", class="AppBundle:Section")
*/
public function ajaxAddQuestionFormAction(Request $request, $section)
{
$question = new Question();
$addQuestionForm = $this->createForm(new AddQuestionType(), $question);
return $this->render('AppBundle:Form:ajaxAddQuestionForm.html.twig', array(
'section' => $section,
'addAjaxQuestionForm' => $addQuestionForm->createView(),
));
}
The ajaxAddQuestionForm.html.twig file looks like this
{% embed 'modal.html.twig' %}
{% block labelledby %}addnewquestion{% endblock %}
{% block modalId %}addnewquestion{% endblock %}
{% block modalHead %}
{{ 'client.modal.head'| trans }}
{% endblock %}
{% block modalBody %}
{{form_start(addAjaxQuestionForm)}}
<div>
{{form_widget(addAjaxQuestionForm.section, {value: section.id})}}
</div>
<div class="form-group">
{{form_label(addAjaxQuestionForm.name, null, {'label_attr': {'class': 'form-label'}}) }}
<span class="help"></span>
<div class="controls">
{{form_widget(addAjaxQuestionForm.name, {'attr':{'class':'form-control'}})}}
</div>
</div>
<div class="form-group">
{{form_label(addAjaxQuestionForm.category, null, {'label_attr': {'class': 'form-label'}}) }}
<span class="help"></span>
<div class="controls">
{{form_widget(addAjaxQuestionForm.category, {'attr':{'width':'100%'}})}}
</div>
</div>
{% endblock %}
{% block modalFooter %}
<button class="btn btn-default" data-dismiss="modal" type="button">{{'client.form.cancel'| trans}}</button>
<input class="btn btn-primary create" type="submit" value="{{'client.form.add.client'| trans}}">
{{form_end(addAjaxQuestionForm)}}
{% endblock %}
{% endembed %}
And finally I have an edit.html.twig that looks like this
<div aria-hidden="true" aria-labelledby="{% block labelledby %}{% endblock %}" class="modal fade" id="{% block modalId %}{% endblock %}" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">×</button>
<h4 class="modal-title" id="myModalLabel">{% block modalHead %}{% endblock %}</h4>
</div>
<div class="modal-body">
{% block modalBody %}
{% endblock %}
</div>
<div class="modal-footer">
{% block modalFooter %}
{% endblock %}
</div>
</div>
</div>
</div>
{% include 'AppBundle:Form:ajaxAddQuestionForm.html.twig' %}
Now I get the following error:
Variable "addAjaxQuestionForm" does not exist in src/AppBundle/Resources/views/Form/ajaxAddQuestionForm.html.twig at line 9
Any idea what is wrong with my code?
In your edit.html.twig (assuming your addAjaxQuestionForm variable exists in it), you need to pass it on to the included twig.
{% include 'AppBundle:Form:ajaxAddQuestionForm.html.twig' with {'addAjaxQuestionForm': addAjaxQuestionForm} %}
Try to use
{{ render(controller('AppBundle:Section:ajaxAddQuestionFormAction',{'section':section})) }}
Instead of Include and you must add "section" parameter to ajaxAddQuestionFormAction.
We can help you more than that if you don't publish us all the code that concern the part of your problem.
I hope that helps
You should use render controller method instead of include
{{ render(controller(
'AppBundle:Form:ajaxAddQuestionForm',
{ 'section': section }
)) }}
read more about it here: http://symfony.com/doc/current/book/templating.html#embedding-controllers
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 %}