Symfony forms problem- Variable form does not exist - php

I am building a crud app using symfony 4. Here is the controller code:
<?php
namespace App\Controller;
use App\Entity\Taskslist;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class TodoController extends Controller{
/**
* #Route("/",name="todo_list")
*/
public function listAction(){
$todos=$this->getDoctrine()->getRepository('App:Taskslist')->findAll();
return $this->render('todo/index.html.twig',array('todos' => $todos));
}
/**
* #Route("/todo/create",name="todo_create")
*/
public function createAction(Request $request){
$todo = new Taskslist;
$form = $this->createFormBuilder($todo)
->add('id', TextType::class)
->add('title', TextType::class)
->add('description', TextareaType::class)
// ->add('priority', ChoiceType::class, array('choices' => array('Low' => 'Low', 'Normal' => 'Normal', 'High'=>'High'), 'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
// ->add('status', BooleanType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('Save', SubmitType::class, array('label'=> 'Create Todo'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$name = $form['id']->getData();
$category = $form['title']->getData();
$description = $form['description']->getData();
//$due_date = $form['status']->getData();
//$name = $form['name']->getData();
//$now = new\DateTime('now');
$todo->setId($name);
$todo->setTitle($category);
$todo->setDescription($description);
$sn = $this->getDoctrine()->getManager();
$sn -> persist($todo);
$sn -> flush();
return $this->redirectToRoute('todo_list');
}
return $this->render('todos/create.html.twig', array(
'form' => $form->createView()
));
}
/**
* #Route("/todo/edit/{id}",name="todo_edit")
*/
public function editAction($id,Request $request){
return $this->render('todo/edit.html.twig');
}
/**
* #Route("/todo/details/{id}",name="todo_details")
*/
public function detailsAction($id){
return $this->render('todo/details.html.twig');
}
}
And here is the edit.html.twig:
{% extends 'base.html.twig' %}
{% if form is defined %}
{% block body %}
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}
{% endif %}
I followed all the tutorials but got this error when i click the edit button :
variable form does not exist.
Although my code steps into the if statement.
Can you please help me?Thanks in advance.i couldn't find any working solution

I think the issue is here:
{% extends 'base.html.twig' %}
{% if form is defined %}
{% block body %}
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}
{% endif %}
use this instead:
{% extends 'base.html.twig' %}
{% block body %}
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}

Related

How display image in edit form Symfony 5

I have form where i upload files - it work so good, i put image name into database, showing it on main page. But if i want to go to edit information about this image e.g name or description form row with image i have empty and once again i need to upload the same photo:
edit form
Project Entity:
/**
* #ORM\Column(type="string", length=255)
*/
private $page_path;
public function getPhotoPath(): ?string
{
return $this->photo_path;
}
public function setPhotoPath(string $photo_path): self
{
$this->photo_path = $photo_path;
return $this;
}
ProjectFormType:
<?php
namespace App\Form;
use App\Entity\Projects;
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\FileType;
class ProjectsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [])
->add('page_path', TextType::class, [])
->add('description', TextType::class, [])
->add('photo_path', FileType::class, [
'data_class' => null,
'label' => 'Zdjęcie',
'constraints' => [
'maxSize' => '5M',
'mimeTypes' => [
'image/*'
],
'mimeTypesMessage' => 'Obsługiwany format pliku musi być obrazem'
]
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Projects::class,
]);
}
}
View:
{% extends 'baseAdmin.html.twig' %}
{% block title %}{{ parent() }}New/Edit
{% endblock %}
{% block body %}
<div class="card-body">
{% form_theme projectsForm 'bootstrap_4_layout.html.twig' %}
{{ form_start(projectsForm) }}
{{ form_row(projectsForm.name) }}
{{ form_row(projectsForm.page_path) }}
{{ form_row(projectsForm.description) }}
{{ form_row(projectsForm.photo_path) }}
<button type="submit" class="btn btn-primary mb-5">Submit</button>
{{ form_end(projectsForm) }}
</div>
{% endblock %}
File input should be empty when edit your entity and this is the default behavior. to make it required false in edit you can use add this simple solution.
'required'=> is_null($builder->getData()->getId())
if you upload a new image, it should replace the old one, otherwise do nothing.
if you want to show the image, you can do it directly in the twig with <img> tag

Adding a custom action to Sonata Admin

I have created a custom action that renders a small form at the bottom of my show template for orders. The form is a basic checkbox and a select field to with tow buttons. It works perfectly but the rendering is not right.
I know the way I render the show template is not 100% correct, because when it renders, the left hand side menu doesn't work anymore.
Here is my custom controller with action;
namespace Qi\Bss\FrontendBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Qi\Bss\FrontendBundle\Crud\Crud;
use Qi\Bss\BaseBundle\Entity\Business\PmodOrder;
use Symfony\Component\HttpFoundation\RedirectResponse;
class PmodOrderController extends Controller
{
/**
* #Route("/{id}/approve", name = "order_approve")
* #Security("is_granted('IS_AUTHENTICATED_FULLY')")
* #Method({"GET", "POST"})
*/
public function approveAction(Request $request, $id){
$em = $this->getDoctrine()->getManager();
$order = $em->getRepository('QiBssBaseBundle:PmodOrder')->find($id);
$approveForm = $this->createFormBuilder($order)
->add('requireApproval', 'checkbox', array('label' => 'Require second Approval', 'required' => false, 'mapped' => false))
->add('secondApprover', 'choice', array('choices' => Crud::enumStatus(), 'label' => 'User', 'required' => false))
->getForm();
$approveForm->handleRequest($request);
if ($approveForm->isSubmitted() && $approveForm->isValid()) {
$secondApproval = $request->request->get('form');
$approval = $approveForm->getData();
if (isset($secondApproval['requireApproval'])) {
$approval->setStatus(PmodOrder::STATUS_PARTLY_APPROVED);
$em->persist($approval);
$em->flush();
return new RedirectResponse($this->container->get('router')->generate('admin_bss_base_business_pmodorder_show', array('id' => $order->getId())));
} else {
$approval->setSecondApprover(NULL);
$approval->setStatus(PmodOrder::STATUS_APPROVED);
$em->persist($approval);
$em->flush();
return new RedirectResponse($this->container->get('router')->generate('admin_bss_base_business_pmodorder_show', array('id' => $order->getId())));
}
}
return $this->render('QiBssFrontendBundle:PmodOrder:order_approve.html.twig', array(
'order' => $order,
'form' => $approveForm->createView(),
));
}
}
What bothers me is the fact that I'm actually suppose to extend from Sonata's CRUDController. And when I do that I get an error;
An exception has been thrown during the rendering of a template
("There is no _sonata_admin defined for the controller
Path\To\Controller\PmodOrderController and the current
route ``")
And I am also aware that I'm actually suppose to use a return like return new RedirectResponse($this->admin->generateUrl('show'));
At this point I don't know what to do anymore. If somebody can please guide me how to extend correctly from CRUDController in my scenario, it would be really appreciated
Here an example, I don't know if it's the best solution but I hope that can help you :
1- Create a custom CRUDcontroller :
# CustomCRUDcontroller.php :
class CustomCRUDDController extends Controller
{
/**
* Show action.
*
* #param int|string|null $id
* #param Request $request
*
* #return Response
*
* #throws NotFoundHttpException If the object does not exist
* #throws AccessDeniedException If access is not granted
*/
public function showAction($id = null)
{
$request = $this->getRequest();
// DO YOUR LOGIC IN THE METHOD, for example :
if(isset($request->get('yourFormParam'))){
$this->doTheJob();
}
$id = $request->get($this->admin->getIdParameter());
$object = $this->admin->getObject($id);
if (!$object) {
throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
}
$this->admin->checkAccess('show', $object);
$preResponse = $this->preShow($request, $object);
if ($preResponse !== null) {
return $preResponse;
}
$this->admin->setSubject($object);
return $this->render($this->admin->getTemplate('show'), array(
'action' => 'show',
'object' => $object,
'elements' => $this->admin->getShow(),
), null);
}
}
2- Register it in admin.yml :
# admin.yml :
x.admin.x:
class: Namespace\YourAdminClass
arguments: [~, Namespace\Entity, Namespace:CustomCRUD]
tags:
- {name: sonata.admin, manager_type: orm, group: X, label: X}
3- Create your own custom_show.html.twig (just a copy and paste of the original template base_show.html.twig located in the sonata-admin folder), here you can display extra elements to the view :
# custom_show.html.twig :
{% extends base_template %}
{% import 'SonataAdminBundle:CRUD:base_show_macro.html.twig' as show_helper %}
{% block actions %}
{% include 'SonataAdminBundle:CRUD:action_buttons.html.twig' %}
{% endblock %}
{% block tab_menu %}
{{ knp_menu_render(admin.sidemenu(action), {
'currentClass' : 'active',
'template': sonata_admin.adminPool.getTemplate('tab_menu_template')
}, 'twig') }}
{% endblock %}
{% block show %}
<div class="sonata-ba-view">
{{ sonata_block_render_event('sonata.admin.show.top', { 'admin': admin, 'object': object }) }}
{% set has_tab = (admin.showtabs|length == 1 and admin.showtabs|keys[0] != 'default') or admin.showtabs|length > 1 %}
{% if has_tab %}
<div class="nav-tabs-custom">
<ul class="nav nav-tabs" role="tablist">
{% for name, show_tab in admin.showtabs %}
<li{% if loop.first %} class="active"{% endif %}>
<a href="#tab_{{ admin.uniqid }}_{{ loop.index }}" data-toggle="tab">
<i class="fa fa-exclamation-circle has-errors hide"></i>
{{ admin.trans(name, {}, show_tab.translation_domain) }}
</a>
</li>
{% endfor %}
</ul>
<div class="tab-content">
{% for code, show_tab in admin.showtabs %}
<div
class="tab-pane fade{% if loop.first %} in active{% endif %}"
id="tab_{{ admin.uniqid }}_{{ loop.index }}"
>
<div class="box-body container-fluid">
<div class="sonata-ba-collapsed-fields">
{% if show_tab.description != false %}
<p>{{ show_tab.description|raw }}</p>
{% endif %}
{{ show_helper.render_groups(admin, object, elements, show_tab.groups, has_tab) }}
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% elseif admin.showtabs is iterable %}
{{ show_helper.render_groups(admin, object, elements, admin.showtabs.default.groups, has_tab) }}
{% endif %}
</div>
{{ sonata_block_render_event('sonata.admin.show.bottom', { 'admin': admin, 'object': object }) }}
{% endblock %}
4- Then indicate to your adminController to display your custom_show template when the current route is "show" (instead of the default template base_show.html.twig) :
# YourEntityAdminController.php :
class YourEntityAdminController extends Controller
{
// allows you to chose your custom showAction template :
public function getTemplate($name){
if ( $name == "show" )
return 'YourBundle:Admin:custom_show.html.twig' ;
return parent::getTemplate($name);
}
}

Accesing button in nested form symfony (child of a child) in symfony

This is form i use:
$form = $this->createForm(new NewsType(), $news)
->add('edit', SubmitType::class, array('label' => 'edit'))
->add('delete', SubmitType::class, array('label' => 'delete'))
->add('comments', CollectionType::class, array('entry_type' => CommentType::class));
CommentType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('author', TextType::class)
->add('text', TextType::class)
->add('remove', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Comment'));
}
Is it possible to access remove button from CommentType so when its clicked to delete comment entry. Everything is mapped properly, i can see comment objects displayed on my page, but when i use $form->get('remove') i get "Child "remove" does not exist." Is it even possible to do this way?
You need to access a grand grand child doing:
foreach ($form->get('comments') as $entry) {
$toRemove = $entry->get('remove')-isClicked();
// handle it ...
}
But to submit it separately you must ensure that your building the "complete" child form in your view:
{{ form_start(form) }}
{% for child in form %}
{% if 'news_comments' == child.vars['full_name'] %}
{{ form_start(child) }}
{{ form_row(child) }}
{{ form_end(child) }}
{% else %}
{{ form_row(child) }}
{% endif %}
{% endfor %}
{{ form_end(form) %}
Aside note:
be careful, you seem to use symfony 2.8 and to have updated the FQCN for the form types, but it's needed too for creating the form:
$form = $this->createForm(NewsType::class, $news)

How to display the current picture above the upload field in SonataAdminBundle?

I am using SonataAdminBundle (with Doctrine2 ORM) and I have successfully added a file upload feature to my Picture model.
I would like, on the Show and Edit pages, to display a simple <img src="{{ picture.url }} alt="{{ picture.title }} /> tag just above the relevant form field (provided that the Picture being edited is not new, of course), so that the user may see the current photo, and decide whether to change it or not.
After hours of research, I've been unable to figure out how to do it. I suppose I need to override some template, but I'm a bit lost...
Can somebody give me a hint?
Thank you!
Here is the relevant section of my PictureAdmin class.
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('category', NULL, ['label' => 'Catégorie'])
->add('title', NULL, ['label' => 'Titre'])
->add('file', 'file', ['required' => false, 'label' => 'Fichier']) // Add picture near this field
->add('creation_date', NULL, ['label' => 'Date d\'ajout'])
->add('visible', NULL, ['required' => false, 'label' => 'Visible'])
->add('position', NULL, ['label' => 'Position']);
}
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('id', NULL, ['label' => 'ID'])
->add('category', NULL, ['label' => 'Catégorie'])
->add('title', NULL, ['label' => 'Titre'])
->add('slug', NULL, ['label' => 'Titre (URL)'])
->add('creation_date', NULL, ['label' => 'Date d\'ajout'])
->add('visible', NULL, ['label' => 'Visible'])
->add('position', NULL, ['label' => 'Position']);
// Add picture somewhere
}
I have managed to put the image above the field in the edit form. But my solution is a little bit specific, because I use Vich Uploader Bundle to handle uploads, so the generation of the image url was a little bit easier thanks to bundle helpers.
Let's look at my example, a film poster field in a film entity.
This is part of my admin class:
//MyCompany/MyBundle/Admin/FilmAdmin.php
class FilmAdmin extends Admin {
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title')
....
->add('poster', 'mybundle_admin_image', array(
'required' => false,
))
}
mybundle_admin_image is handled by a custom field type, that is just a child of file type by setting it's getParent method: (don't forget to register your type class as a service)
//MyCompany/MyBundle/Form/Type/MyBundleAdminImageType.php
public function getParent()
{
return 'file';
}
Then I have a template that extends Sonata's default styling, and I have it included in the admin class:
//MyCompany/MyBundle/Admin/FilmAdmin.php
public function getFormTheme() {
return array('MyCompanyMyBundle:Form:mycompany_admin_fields.html.twig');
}
And finally I have a block for my custom image type that extends the basic file type:
//MyCompany/MyBundle/Resources/views/Form/mycompany_admin_fields.html.twig
{% block mybundle_admin_image_widget %}
{% spaceless %}
{% set subject = form.parent.vars.value %}
{% if subject.id and attribute(subject, name) %}
<a href="{{ asset(vich_uploader_asset(subject, name)) }}" target="_blank">
<img src="{{ asset(vich_uploader_asset(subject, name)) }}" width="200" />
</a><br/>
{% endif %}
{% set type = type|default('file') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endspaceless %}
{% endblock %}
This causes that a 200px wide preview of image (if exists) is shown above the upload field, linked to it's full size version opening in new tab. You can customize it as you want, e.g. adding a lightbox plugin.
you can easily do this on edit page by helpers(FormMapper->setHelps) or option "help" pass on FormMapper
protected function configureFormFields(FormMapper $formMapper) {
$options = array('required' => false);
if (($subject = $this->getSubject()) && $subject->getPhoto()) {
$path = $subject->getPhotoWebPath();
$options['help'] = '<img src="' . $path . '" />';
}
$formMapper
->add('title')
->add('description')
->add('createdAt', null, array('data' => new \DateTime()))
->add('photoFile', 'file', $options)
;
}
You can easily do this on show page
by template attribute pass on $showmapper
->add('picture', NULL, array(
'template' => 'MyProjectBundle:Project:mytemplate.html.twig'
);
and inside your template you get current object so u can call get method and pull image path
<th>{% block name %}{{ admin.trans(field_description.label) }}{% endblock %}</th>
<td>
<img src="{{ object.getFile }}" title="{{ object.getTitle }}" />
</br>
{% block field %}{{ value|nl2br }}{% endblock %}
</td>
To show image in edit mode you have to override fileType or you have to create your own customType on top of fileType
There is also some bundle which is having this kind of functionality
check out this GenemuFormBundle
Solution for Symfony3
The answer from #kkochanski is the cleanest way I found so far. Here a version ported to Symfony3. I also fixed some bugs.
Create a new template image.html.twig for your new form type (full path: src/AppBundle/Resources/views/Form/image.html.twig):
{% block image_widget %}
{% spaceless %}
{% set type = type|default('file') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% if image_web_path is not empty %}
<img src="{{ image_web_path }}" alt="image_photo"/>
{% endif %}
{% endspaceless %}
{% endblock %}
Register the new form type template in your config.yml:
twig:
form_themes:
- AppBundle::Form/image.html.twig
Create a new form type and save it as ImageType.php (full path: src/AppBundle/Form/Type/ImageType.php):
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class ImageType
*
* #package AppBundle\Form\Type
*/
class ImageType extends AbstractType
{
/**
* #return string
*/
public function getParent()
{
return 'file';
}
/**
* #return string
*/
public function getName()
{
return 'image';
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'image_web_path' => ''
));
}
/**
* #param FormView $view
* #param FormInterface $form
* #param array $options
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['image_web_path'] = $options['image_web_path'];
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAttribute('image_web_path', $options['image_web_path'])
;
}
}
If you have done this. You can just import the new ImageType in your entity admin class:
use AppBundle\Form\Type\ImageType
And then, finally use the new form type without any inline-html or boilerplate code in configureFormFields:
$formMapper
->add('imageFile', ImageType::class, ['image_web_path' => $image->getImagePath()])
;
Instead of $image->getImagePath() you have to call your own method that returns the url to your image.
Screenshots
Creating a new image entity using sonata admin:
Editing a image entity using sonata admin:
You can simple do by this way
$image = $this->getSubject();
$imageSmall = '';
if($image){
$container = $this->getConfigurationPool()->getContainer();
$media = $container->get('sonata.media.twig.extension');
$format = 'small';
if($webPath = $image->getImageSmall()){
$imageSmall = '<img src="'.$media->path($image->getImageSmall(), $format).'" class="admin-preview" />';
}
}
$formMapper->add('imageSmall', 'sonata_media_type', array(
'provider' => 'sonata.media.provider.image',
'context' => 'default',
'help' => $imageSmall
));
Teo.sk wrote the method of showing images using VichUploader. I found an option which allow you to show images without this bundle.
First we need to create our form_type. There is tutorial: symfony_tutorial
In main Admin class:
namespace Your\Bundle;
//.....//
class ApplicationsAdmin extends Admin {
//...//
public function getFormTheme() {
return array_merge(
parent::getFormTheme(),
array('YourBundle:Form:image_type.html.twig') //your path to form_type template
);
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('file_photo', 'image', array(
'data_class' => 'Symfony\Component\HttpFoundation\File\File',
'label' => 'Photo',
'image_web_path' => $this->getRequest()->getBasePath().'/'.$subject->getWebPathPhoto()// it's a my name of common getWebPath method
))
//....//
;
}
}
Next part is a code from ImageType class.
namespace Your\Bundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
class ImageType extends AbstractType
{
public function getParent()
{
return 'file';
}
public function getName()
{
return 'image';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'image_web_path' => ''
));
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['image_web_path'] = $options['image_web_path'];
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAttribute('image_web_path', $options['image_web_path'])
;
}
}
And on the end time for image_type twig template.
{% block image_widget %}
{% spaceless %}
{% set type = type|default('file') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
<img src="{{ image_web_path }}" alt="image_photo"/>
{% endspaceless %}
{% endblock %}
For me it's working! I'm also using avalanche bundle to resize images.
There is an easy way - but you will see the picture below the upload button.
SonataAdmin lets put raw HTML into the ‘help’ option for any given form field. You can use this functionality to embed an image tag:
protected function configureFormFields(FormMapper $formMapper) {
$object = $this->getSubject();
$container = $this->getConfigurationPool()->getContainer();
$fullPath = $container->get('request')->getBasePath().'/'.$object->getWebPath();
$formMapper->add('file', 'file', array('help' => is_file($object->getAbsolutePath() . $object->getPlanPath()) ? '<img src="' . $fullPath . $object->getPlanPath() . '" class="admin-preview" />' : 'Picture is not avialable')
}

symfony form : how to show the parameter in the view, "variable does not exist..."

I'm using a form with 2 classes ("ArticleType" and "ArticleHandler") for my class Article.
I would like to send the id of the article I've just created, but I can't manage to show this id parameter in the view :
In the controller, I send my article's id :
$handler = new ArticleHandler($form, $request, $em);
if ($handler->process()){
return $this->redirect($this->generateUrl('myproject_show', array('id' => $article->getId())) );
}
and in the view, I've got an error with :
{% block body %}
<p>the id :</p>
{{ id }}
{% endblock %}
or entity.id (as in the CRUD) :
Variable "id" does not exist...
Variable "entity.id" does not exist...
Do you know how to fix this?
Thanks
EDIT :
here's my method :
public function addAction()
{
$article = new Article();
$form = $this->createForm(new ArticleType(), $article);
$request = $this->getRequest();
$em = $this->getDoctrine()->getEntityManager();
$handler = new ArticleHandler($form, $request, $em);
if ($handler->process()){
return $this->redirect($this->generateUrl('myproject_show', array('id' => $article->getId())) );
}
return $this->render('ProjBlogBundle:Blog:add.html.twig', array(
'form' => $form->createView(),
));
}
and here's the view :
{% extends "ProjBlogBundle::layout.html.twig" %}
{% block title %}
the title - {{ parent() }}
{% endblock %}
{% block sousbody %}
<p>here's the article i've just created :</p>
{{ id }}
{% endblock %}
EDIT N°2 :
myproject_show:
pattern: /show/{id}
defaults: { _controller: ProjBlogBundle:Blog:show, id:5 }
To use a variable in a template you need to pass it when you render your template:
//ProjBlogBundle:Blog:show
public function showAction($id)
{
return $this->render('ProjBlogBundle:Blog:show.html.twig', array(
'id' => $id
));
}
$this->redirect($this->generateUrl('myproject_show', array('id' => $article->getId())) ); returns only HTTP 302-response without rendering a template, and the browser is redirected to the generated url...

Categories