How to do error messages in symfony - php

I have used CRUD to generate actions for an entity. However, I would like to modify the edit action; for instance, a user select 'inactive' represented by 1 for State then they will be shown an error message otherwise they can proceed to updating that row. Within the entity these are the variables state, paypid, startDate, endDate.
This is what the edit action currently looks like.
public function editAction($Paypid)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')
->findBy(['paypid' => $Paypid, 'state' => 0]);
if (!$entity) {
$this->addFlash(
'notice',
'You cannot edit an inactive Payroll Period'
);
return $this->redirectToRoute('/payrollperiod');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($Paypid);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
And this method in the repository entity.
public function findByPaypidAndActiveState($Paypid)
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM comtwclagripayrollBundle:Payrollperiod
WHERE paypid = :paypid AND state = :state'
)
->setParameter('paypid', $Paypid)
->setParameter('state', 0)
->getResult();
}

Maybe add to view something like this(only for twig template):
{% for type, flash_messages in app.session.flashBag.all %}
{% for flash_message in flash_messages %}
{{ flash_message }}
{% endfor %}
{% endfor %}
I recomended right bechind <body> tag.

Related

Add dropdown to symfony 3 form

I want to add a dropdow field for category in my form in symfony version 3, I have tried to solutions but each one have their own problem
First got all categories and pass them to my view and show them:
Action:
/**
* Creates a new News entity.
*
* #Route("/new", name="news_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$news = new News();
$form = $this->createForm('AppBundle\Form\NewsType', $news);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($news);
$em->flush();
return $this->redirectToRoute('news_show', array('id' => $news->getId()));
}
$em = $this->getDoctrine()->getManager();
$categories = $em->getRepository('AppBundle:Category')->findAll();
return $this->render('news/new.html.twig', array(
'news' => $news,
'form' => $form->createView(),
'categories' => $categories,
));
}
View:
{% extends 'base.html.twig' %}
{% block body %}
<h1>News creation</h1>
{{ form_start(form) }}
<label for="news_content" class="required">Category</label>
<select name="news[categoryId]">
{% for category in categories %}
<option value="{{ category.id }}">{{ category.title }}</option>
{% endfor %}
</select>
{{ form_widget(form) }}
<input class="btn btn-sm btn-success" type="submit" value="Create" />
{{ form_end(form) }}
<ul>
<li>
<a class="label label-sm label-info" href="{{ path('news_index') }}">Back to the list</a>
</li>
</ul>
{% endblock %}
The form is created as I expected but when i want to submit it, it show an validation error as bellow:
This form should not contain extra fields.
second solution that I have tried is to generate the dropdown from my Type, so in NewsType I changed the buildForm function as bellow:
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('categoryId', EntityType::class, [
'class' => 'AppBundle:Category',
'choice_label' => 'title',
])
->add('title')
->add('content')
;
}
It this way, the form also have been created nicely but after submit, an database exception returned and said:
An exception occurred while executing 'INSERT INTO news (category_id, title, content) VALUES (?, ?, ?)' with params [{}, "asdf", "asdf"]:
Catchable Fatal Error: Object of class AppBundle\Entity\Category could not be converted to string
It mean that my category_id passed as an object !
What should I do?
BTW, my english is a little weak, please do not put and minus on my post, I had been ban multiple times.
Thanks in advance.
all symfony is trying to do is to find a string representation of the Category object, so it can populate the option fields.
you can solve this in a couple of ways:
In the Category object, you can make a __toString method.
public function __toString() {
return $this->name; // or whatever field you want displayed
}
or
you can tell symfony which field to use as the label for the field. From docs
$builder->add('attending', ChoiceType::class, array(
'choices' => array(
new Status(Status::YES),
new Status(Status::NO),
new Status(Status::MAYBE),
),
'choice_label' => 'displayName', // <-- where this is getDisplayName() on the object.
));

symfony2 edit more entities in same page

How can edit more products entities in same page (no 1 to many).
In My editaction :
$entities=$em->getRepository('MyBundle:Product')->findAll();
$editForm=array();
$deleteForm=array();
foreach ($entities as $product )
{
$editForm [$port->getId()]= $this->createEditForm($product);
$deleteForm[$port->getId()] = $this->createDeleteForm($product->getId());
}
return $this->render('MyBundle:Product:edit.html.twig', array(
'entities' => $entities,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
I have this error :
Error: Call to a member function createView() on a non-object
And how update the edit.thml.twig to show all form update as table with only one submit ?
This is not about Symfony2, but about PHP, you are calling a method onto an array...
Consider something like this :
$entities = $em->getRepository('MyBundle:Product')->findAll();
$editForms = array();
$deleteForms = array();
foreach ($entities as $product)
{
$editForms[$port->getId()] = $this->createEditForm($product)
->createView();
$deleteForms[$port->getId()] = $this->createDeleteForm($product->getId())
->createView();
}
return $this->render('MyBundle:Product:edit.html.twig', array(
'entities' => $entities,
'edit_forms' => $editForms,
'delete_forms' => $deleteForms,
));
With a template like this one :
{% for form in edit_foms %}
{{ form(form) }}
{% endfor %}
{% for form in delete_foms %}
{{ form(form) }}
{% endfor %}
I have fix this :
change the name of form:
public $name;
/**
* #return string
*/
public function getName()
{
return (string)'port_'.$this->name;
}
public function __construct($name=0) {
$this->name=$name;
}
and in my controller
editAction :
$entities = $em->getRepository('InfraProductBundle:InfraPortDdf')->findAll();
foreach ($entities as $port )
{
$editForm [$port->getId()]= $this->createEditForm($port);
$edit_view[$port->getId()]=$editForm[$port->getId()]->createView();
}
return $this->render('......:edit.html.twig', array(
'entities' => $entities,
'edit_form' => $edit_view,
));
in update action
foreach ($array_id as $key=>$id){
if(!is_numeric(str_replace('port_','',$id)))
continue;
$entity = $em->getRepository('InfraProductBundle:InfraPortDdf')->find(str_replace('port_','',$id));
if (!$entity) {
throw $this->createNotFoundException('Unable to find InfraPortDdf entity.');
}
$editForm = $this->createEditForm($entity);
if($editForm->submit($request->request->get($id)))
$em->flush();
}
in my edit.html.twig:
{% for key, edit in edit_form %}
...
{{form_widget(edit.description,{name:'['~key~'][description]', 'attr': { 'name' : '['~key~'][description]' } } ) }}
....
{%endfor%}

How to passa data from the controller to the database for a list

I made a web-application with symfony2, where a registrated user can query for a file and visualize it. I'm trying to pass the information from the controller to the template.
When I pass the information of a single object, it works properly. You can see the controller here:
public function showAction($id)
{
$product = $this->getDoctrine()
->getRepository('AcmeBundle:Product')
->find($id);
if (!$product) {
throw $this->createNotFoundException(
'Nessun prodotto trovato per l\'id '.$id
);
}
return $this->render('AcmeGroundStationBundle::showdata.html.twig', array('Id' => $product->getId(), 'Name' => $product->getName(), 'UploadTime'=> $product- >getUploadTime()));
}
But what can I do if I want to display the whole list?
If I change the
->find($id);
with
->findAll();
of course I get error.
( Call to a member function getId() on a non-object).
How can I display the whole list?
Thank you for your help
First pass all the products data to your twig view
public function showAction()
{
$products = $this->getDoctrine()
->getRepository('AcmeBundle:Product')
->findAll();
if (empty($products)) {
throw $this->createNotFoundException(
'No products found'
);
}
return $this->render('AcmeGroundStationBundle::showdata.html.twig',
array('products' => $products));
}
Then in your view you can list products with their information as
{% if products is defined and products is not empty %}
{% for p in products %}
id : {{ p.getId() }} <br>
Name: {{ p.getName() }} <br>
Upload Time: {{ p.getUploadTime() }} <br>
{% endfor %}
{% endif %}
EDIT
findAll() will give all the results to get the latest 10 you need use findBy
findBy(
array(), // $where
array('id' => 'DESC'), // $orderBy
10, // $limit
0 // $offset
);

Symfony 2.1 app.session.flashbag.get('something') returns empty value

I have a trouble with using app.session.flashbag.get('notice').
In the controller I make
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SomeBundle:SomeEntity')->find($id);
$editForm = $this->createForm(new SomeEntityType(), $entity);
$editForm->bind($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
$flash = $this->get('translator')->trans('Some Entity was successfully updated');
$this->get('session')->getFlashBag()->add('notice', $flash);
return $this->redirect($this->generateUrl('some_entity_edit', array('id' => $id)));
}
In editAction I'm getting information from the session:
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$flashes = $this->get('session')->getFlashBag()->get('notice', array());
//...
//...
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'flashes' => $flashes
);
}
And i'm trying in the TWIG get information from the session :
TWIG: {% for flashMessage in app.session.flashbag.get('notice') %}{{ flashMessage }}{% endfor %}
PHP: {% for flashMessage2 in flashes %}{{ flashMessage2 }}{% endfor %}
The app.session.flashbag.get('notice') is empty, the flashes has a value.
Do you have any ideas, why I can't get data from the app.session.flashbag.get('notice')?
Its normal behavior. You access flash in controller first, so it is returned and unset then. When you access it again then key does not exists in flashbag that way is empty.
See FlashBag::get at github
There is an easy way to handle (add/display) Symfony flash messages with FlashAlertBundle, it is standalone Symfony2 bundle implemented with pure JavaScript, so you don't have to worry about using JS libraries.
You just need the following code to render flash messages on your twig template:
{{ render_flash_alerts() }}
Available through
https://github.com/rasanga/FlashAlertBundle
https://packagist.org/packages/ras/flash-alert-bundle

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