Remove elements from session array - php

I'm attempting to build a super simple shopping cart using symfony for my learning purposes. Currently I'm using sessions to store 'products' that a user has selected in an array. I have three questions that I want to ask...
I want a button that will remove a 'product' from the session array(The user is displayed a list of 'products' selected by them in a table. The user can then choose to remove a 'product' from the table and subsequently removing the 'product' from the session array). I'm a super beginner in jquery, however, I'm sure this can be accomplished using jquery. How can I do this? I researched splice, and remove functions but was unable to get things running. Could someone give me examples using my twig file so I can better understand the correct way to set things up?
cart.twig:
{% extends '::base.html.twig' %}
{% block body %}
<h1><u><i>Welcome to the Cart</i></u></h1>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price Per Unit</th>
<th>Remove From Cart</th>
</tr>
</thead>
<tbody>
{% for key, cartValue in cartArray %}
<tr>
<td>{{ cartValue[0] }}</td> <!--Product-->
<td>{{ cartValue[1] }}</td> <!--Quantity-->
<td>${{ cartValue[2] }}</td> <!--Price Per Unit-->
<td> <script type="text/javascript">
$(function() {(
cartArray.splice(cartArray.indexOf(0),1);
)};
</script>
<button type="button" class="btn btn-danger">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table> <!--top table-->
<div class="money-container">
<p class="text-right">Total Cost: ${{ totalCostOfAllProducts }}</p>
</div><!--moneyContainer-->
</div> <!--container-->
<ul>
<li>
<a href="{{ path('product_bought', {'id': entity.id }) }}">
Buy These Products
</a>
</li>
<li>
<a href="{{ path('product') }}">
Add More Products
</a>
</li>
<li>
<a href="{{ path('product_edit', { 'id': entity.id }) }}">
Edit
</a>
</li>
<li>{{ form(delete_form) }}</li>
</ul>
{% endblock %}
Again from more research I keep seeing that data manipulation should remain in the controller class. Would doing the above break that rule? If so, how should I go about accomplishing my task in my controller?
ProductController:
namespace PaT\ShopTestBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use PaT\ShopTestBundle\Entity\Product;
use PaT\ShopTestBundle\Form\ProductType;
/**
* Product controller.
*
* #Route("/product")
*/
class ProductController extends Controller
{
/**
* Lists all Product entities.
*
* #Route("/", name="product")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
//$entities = $em->getRepository('PaTShopTestBundle:Product')->findAll();
$categories = $em->getRepository('PaTShopTestBundle:Category')->findAll();
return array(
'categories' => $categories,
//'entities' => $entities,
);
}
/**
* Creates a new Product entity.
*
* #Route("/", name="product_create")
* #Method("POST")
* #Template("PaTShopTestBundle:Product:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Product();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('product_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Product entity.
*
* #param Product $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Product $entity)
{
$form = $this->createForm(new ProductType(), $entity, array(
'action' => $this->generateUrl('product_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Product entity.
*
* #Route("/new", name="product_new")
* #Method("GET")
* #Template()
*/
public function newAction()
{
$entity = new Product();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Product entity.
*
* #Route("/{id}", name="product_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Product entity.');
} else {
//dump($entity); die;
$descriptions = $entity->getDescriptions();
//dump($entity); die;
}
$deleteForm = $this->createDeleteForm($id);
return array(
'descriptions'=> $descriptions,
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Product entity.
*
* #Route("/{id}/edit", name="product_edit")
* #Method("GET")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Product entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Product entity.
*
* #param Product $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Product $entity)
{
$form = $this->createForm(new ProductType(), $entity, array(
'action' => $this->generateUrl('product_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Product entity.
*
* #Route("/{id}", name="product_update")
* #Method("PUT")
* #Template("PaTShopTestBundle:Product:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Product entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('product_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Product entity.
*
* #Route("/{id}", name="product_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Product entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('product'));
}
/**
* Creates a form to delete a Product entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('product_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
/**
* Creates the option to 'add product to cart'.
*
* #Route("/{id}/cart", name="product_cart")
* #Method("GET")
* #Template()
*/
public function cartAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);
$session = $request->getSession(); //session----------------
$deleteForm = $this->createDeleteForm($id);
$totalCostOfAllProducts = 0;
$cartArray = array();
if (is_null($cartArray) || !$entity) {
throw $this->createNotFoundException('Error: Nothin in Array/Entity');
} else {
$cartArray = $session->get('cartArray', []);
$cartArray[$entity->getId()] = [$entity->getName(), $entity->getQuantity(), $entity->getPrice()];
foreach ($cartArray as $key => $product) {
// dump($cartArray); die;
// dump($key); die;
$productEntity = $em->getRepository('PaTShopTestBundle:Product')->find($key);
$quantity = $productEntity->getQuantity();
$price = $productEntity->getPrice();
$totalCostOfAllProducts += $price * $quantity;
}
}
//$remove = unset($cartArray);
// if (isset($_POST['Button'])) {
// unset($cartArray[1]); //remove index
// }
//above did nothing
$session->set('cartArray', $cartArray); //session---------------
//var_dump($cartArray); die;
return array(
'price' => $price,
'quantity' => $quantity,
'totalCostOfAllProducts' => $totalCostOfAllProducts,
'cartArray' => $cartArray,
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays the products bought from products 'added to cart'
*
* #Route("/{id}/bought", name="product_bought")
* #Method("GET")
* #Template()
*/
public function boughtAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PaTShopTestBundle:Product')->find($id);
$session = $request->getSession(); //session----------------
$deleteForm = $this->createDeleteForm($id);
$totalCostOfAllProducts = 0;
$cartArray = array();
if (is_null($cartArray) || !$entity) {
throw $this->createNotFoundException('Error: Nothing Found In Entity/Array');
} else {
$cartArray = $session->get('cartArray', []);
$cartArray[$entity->getId()] = [$entity->getName()];
foreach ($cartArray as $key => $value) {
$prodEnt = $em->getRepository('PaTShopTestBundle:Product')->find($key);
$quantity = $prodEnt->getQuantity();
$price = $prodEnt->getPrice();
$totalCostOfAllProducts += $price * $quantity;
}
}
$session->set('cartArray', $cartArray); //session---------------
$request->getSession()->invalidate(1);
return array(
'price' => $price,
'quantity' => $quantity,
'totalCostOfAllProducts' => $totalCostOfAllProducts,
'cartArray' => $cartArray,
);
}
}
Finally, How can I do all of this WITHOUT using a session array logic like I'm doing now. People I've talked to have told me relying on sessions to create an array is bad practice. What's the better way to do what I'm doing. (If this last question is too broad or opinion based then either ignore it or leave some links/quick answers to help answer but please don't close this whole thing based on this one)
Any help is really appreciated, Thanks!!
EDIT: dump array:
array:3 [▼
1 => array:3 [▼
0 => "Water"
1 => 5
2 => 2.75
]
5 => array:3 [▼
0 => "Rooster"
1 => 1
2 => 105.0
]
6 => array:3 [▼
0 => "Apple Sauce"
1 => 1
2 => 9.25
]
]
Also here is my newest attempt: (still doing nothing/not working)
<script type="text/javascript">
$('#removeButton').click(function() {
cartArray.splice(indexOf(($this), 1);
});
</script>
(Since the quantity of 'products' can be more than 1, the second argument in splice may not work. So splice may not be the answer I need...Or not, I'm totally guessing here

First, you need the query target for your function and this will be the button if I understand you right. Give your button an id and reference that in the tag as such $( '#buttonid' ).click( function(){ #your code here }) Also jquery has a $(this) selector which allows to you to reference an element relative to the current context of what triggered the action. So in your case $(this).parent().parent() would refer to the <tr> containing the button that was clicked. Also for what it's worth you should probably put the script at the top or bottom of the page

Related

Displaying clicked items in session array

I'm learning MVC and Symfony2 (version 2.7) by creating a super simple shopping cart test (I know symfony has a doctrine for this but I just want to learn basics, so go easy on me ;) ).
All I want to be able to do is for each item they click, it appears next to the other items they clicked. This really isn't a MVC or Symfony2 problem as much as it is a php, twig coding problem that I'm flubbing on.
I have a form that users can click buy, on which users are redirected to another form that displays what they bought. Below that display are other items with the buy button option again. Once they click that button for an item, the new item should appear next to the previous one.
Instead the old item goes away and the new item appears.
How can I make the old ones stay along with the new ones?
Below is the controller class that renders the forms. Take a look at buyAction
It stores the items in cart, but only one at a time...How can I fix that?
//////////////////
<?php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\Item;
use AppBundle\Form\ItemType;
/**
* Item controller.
*
* #Route("/item")
*/
class ItemController extends Controller
{
/**
* Lists all Item entities.
*
* #Route("/", name="item")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AppBundle:Item')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new Item entity.
*
* #Route("/", name="item_create")
* #Method("POST")
* #Template("AppBundle:Item:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Item();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('item_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Item entity.
*
* #param Item $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Item $entity)
{
$form = $this->createForm(new ItemType(), $entity, array(
'action' => $this->generateUrl('item_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Item entity.
*
* #Route("/new", name="item_new")
* #Method("GET")
* #Template()
*/
public function newAction()
{
$entity = new Item();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Displays Bought Items
*
* #Route("/buy/{id}", name="item_buy")
* #Method("GET")
* #Template()
*/
public function buyAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Item')->find($id);
$entities = $em->getRepository('AppBundle:Item')->findAll();
$cart = [];
$session = $request->getSession();
$session->set('cart', $cart);
if (!$entity) {
throw $this->createNotFoundException('No Item ');
} else {
$cart[$entity->getId()] = $entity->getName();
}
$session->set('cart', $cart);
return array(
'cart' => $cart,
'entity' => $entity,
'entities' => $entities,
);
}
/**
* Finds and displays an Item entity.
*
* #Route("/show/{id}", name="item_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Item')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Item entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Item entity.
*
* #Route("/{id}/edit", name="item_edit")
* #Method("GET")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Item')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Item entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Item entity.
*
* #param Item $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Item $entity)
{
$form = $this->createForm(new ItemType(), $entity, array(
'action' => $this->generateUrl('item_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Item entity.
*
* #Route("/{id}", name="item_update")
* #Method("PUT")
* #Template("AppBundle:Item:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Item')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Item entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('item_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes an Item entity.
*
* #Route("/{id}", name="item_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Item')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Item entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('item'));
}
/**
* Creates a form to delete an Item entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('item_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
/////////////////
Below is the first form, where nothing is "bought" yet.
//////////////////
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Item list</h1>
<table class="records_list">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<td>{{ entity.id }}</td>
<td>{{ entity.name }}</td>
<td>
<ul>
<li>
Buy
</li>
<li>
show
</li>
<li>
edit
</li>
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<ul>
<li>
Create a new entry
</li>
{#<li>
Buy Item
</li>#}
</ul>
{% endblock %}
/////////////////////
Below is the form users are shown after they "bought" an item (where the "bought" item is displayed up top) and where they can choose to "buy" something else (where this new item should go next to the previous "bought" item).
////////////////////
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Items Bought...</h1>
<table class="record_properties">
<h3>You Bought...</h3>
{# {% if entity is defined %} #}
{% for entities in cart %}
<tr>
<td>{{ entity.name }}</td>
</tr>
{% endfor %}
{# {% endif %} #}
<tbody>
{% for entity in entities %}
<tr>
<td>{{ entity.id }}</td>
<td>{{ entity.name }}</td>
<td>
<ul>
<li>
Buy
</li>
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<ul class="record_actions">
<li>
<a href="{{ path('item') }}">
Back to the list
</a>
</li>
{% endblock %}
//////////////////////
I've been starring at this all day yesterday and I can't find my issue. So any help is appreciated, thanks.
ALSO
Any ideas how to make this better/things to help me learn MVC basics/Symfony2 stuff would be cool if you got some too. I've been using Lynda dot com, google, this site, the Symfony book/cookbook. Thanks!
The problem is that you have this in your last Twig file.
{% for entities in cart %}
You're placing in entities variable each iteration of cart, so you're losing all entities loaded in the controller.
Change this...
{% for entities in cart %}
<tr>
<td>{{ entity.name }}</td>
</tr>
{% endfor %}
to this...
{% for cartItem in cart %}
<tr>
<td>{{ cartItem.name }}</td>
</tr>
{% endfor %}
At least this part should be solved :)

Select from table where row equal to option symfony2

I have a table generated by a crud in symfony2. The entity is called "Voorraad"(=Stock) and is a table of 3 items: "aantal"(=number), "locatie_id"(location_id) and "product_id". Both the location id and product id are associations with another enitty (locatie entity and product entity). I try to order my stock by location but I cant get it right in symfony. I would like to have a option to select a location (id 1, id 2, id 3) and If a have selected a option it outputs the data of that location.
In mysql its the following query
SELECT * FROM `voorraad` WHERE `locatie_id` = 1
How can I achieve something like this in Symfony2/doctrine/twig?
My code:
View
{% extends '::base.html.twig' %}
{% block body -%}
<h1 class="hoofdtitel">Voorraad lijst</h1>
<table class="records_list">
<thead>
<tr>
<!-- <th>Id</th> -->
<th>Product</th>
<th>Type</th>
<th>Fabriek</th>
<th>Aantal</th>
<th>Inkoopprijs</th>
<th>Verkoopprijs
<th>Locatie</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<!-- <td>{{ entity.id }}</td> -->
<td>{{ entity.getProduct().getNaam() }}</td>
<td>{{ entity.getProduct().getType() }}</td>
<td>{{ entity.getProduct().getFabric().getFabrieknaam() }}</td>
<td>{{ entity.aantal }}</td>
<td>{{ entity.getProduct().getInkoopprijs() }}</td>
<td>{{ entity.getProduct().getVerkoopprijs() }}</td>
<td>{{ entity.getLocatie().getLocatienaam() }}</td>
<td>
Voorraad aanpassen
</td>
</tr>
{% if
entity.aantal == 1 %}
<div class="alert alert-info" role="alert"> <p>Let op, voorraad van {{ entity.getProduct().getNaam() }} is 1 of minder </p></div>
{% endif %}
{% if
entity.aantal <= 0 %}
<div class="alert alert-danger" role="alert"> <p>Let op, voorraad van {{ entity.getProduct().getNaam() }} is op </p></div>
{% endif %}
{% endfor %}
</tbody>
</table>
<br>
<a href="{{ path('voorraad_new') }}">
Nieuwe voorraad toevoegen
</a>
{% endblock %}
Controller
namespace ToolsForEver\VoorraadBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use ToolsForEver\VoorraadBundle\Entity\Voorraad;
use ToolsForEver\VoorraadBundle\Form\VoorraadType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
/**
* Voorraad controller.
*
* #Route("/voorraad")
*/
class VoorraadController extends Controller
{
/**
* Lists all Voorraad entities.
*
* #Route("/", name="voorraad")
* #Method("GET")
* #Template()
* #Security("has_role('ROLE_USER')")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->findBy(array(), array('locatie'=>'asc'));
return array(
'entities' => $entities,
);
}
/**
* Creates a new Voorraad entity.
*
* #Route("/", name="voorraad_create")
* #Method("POST")
* #Template("ToolsForEverVoorraadBundle:Voorraad:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Voorraad();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('voorraad_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Voorraad entity.
*
* #param Voorraad $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Voorraad $entity)
{
$form = $this->createForm(new VoorraadType(), $entity, array(
'action' => $this->generateUrl('voorraad_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Voorraad entity.
*
* #Route("/new", name="voorraad_new")
* #Method("GET")
* #Template()
* #Security("has_role('ROLE_USER')")
*/
public function newAction()
{
$entity = new Voorraad();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Voorraad entity.
*
* #Route("/{id}", name="voorraad_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Voorraad entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Voorraad entity.
*
* #Route("/{id}/edit", name="voorraad_edit")
* #Method("GET")
* #Template()
* #Security("has_role('ROLE_USER')")
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Voorraad entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Voorraad entity.
*
* #param Voorraad $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Voorraad $entity)
{
$form = $this->createForm(new VoorraadType(), $entity, array(
'action' => $this->generateUrl('voorraad_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Voorraad entity.
*
* #Route("/{id}", name="voorraad_update")
* #Method("PUT")
* #Template("ToolsForEverVoorraadBundle:Voorraad:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Voorraad entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('voorraad_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Voorraad entity.
*
* #Route("/{id}", name="voorraad_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Voorraad entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('voorraad'));
}
/**
* Creates a form to delete a Voorraad entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('voorraad_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Verwijder voorraad'))
->getForm()
;
}
}
You can use doctrine's findBy method :
$entities = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')
->findBy(['locatie'=>$locatieId]);
You can create a method in your controller for this goal.An approximate code is as follows (but it all depends on your mapping info and attributes names).
public function getVoorraadByLocatieId($locatieId)
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT v
FROM ToolsForEverVoorraadBundle:Voorraad v
WHERE v.locatie = :l_id'
)->setParameter('l_id', $locatieId);
$result = $query->getResult();
return $result;
}
And in your action, do:
$this->getVoorraadByLocatieId($locatieId);
There are different ways of achieving the same result, like creating a service and calling it from inside controller (fat services with thin controllers is a god practice), or creating a custom Repository Class, but the idea is the same (the use of entity manager and doctrine fetching ). The advantage of latter ways is code organization/readability.

how to use a selectbox to fetch data from database row symfony2

I am currently working with a small project in symfony2. I have made a simple table with crud command. I have a entity called "voorraad"(=stock) that has a association with entity "product" and the entity "Locatie"(=Location). How it works: I can add a product and location to my stock.
So my problem, is that I cant figure out how to display the products in my stock by location with a selectbox. The idea is to have a selectbox with the locations from my location entity, and If I select a option that it will only show the products of my option. Below my code:
Controller
<?php
namespace ToolsForEver\VoorraadBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use ToolsForEver\VoorraadBundle\Entity\Voorraad;
use ToolsForEver\VoorraadBundle\Form\VoorraadType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
/**
* Voorraad controller.
*
* #Route("/voorraad")
*/
class VoorraadController extends Controller
{
/**
* Lists all Voorraad entities.
*
* #Route("/", name="voorraad")
* #Method("GET")
* #Template()
* #Security("has_role('ROLE_USER')")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->findBy(array(), array('locatie'=>'asc'));
return array(
'entities' => $entities,
);
}
/**
* Creates a new Voorraad entity.
*
* #Route("/", name="voorraad_create")
* #Method("POST")
* #Template("ToolsForEverVoorraadBundle:Voorraad:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Voorraad();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('voorraad_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Voorraad entity.
*
* #param Voorraad $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Voorraad $entity)
{
$form = $this->createForm(new VoorraadType(), $entity, array(
'action' => $this->generateUrl('voorraad_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Voorraad entity.
*
* #Route("/new", name="voorraad_new")
* #Method("GET")
* #Template()
* #Security("has_role('ROLE_USER')")
*/
public function newAction()
{
$entity = new Voorraad();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Voorraad entity.
*
* #Route("/{id}", name="voorraad_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Voorraad entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Voorraad entity.
*
* #Route("/{id}/edit", name="voorraad_edit")
* #Method("GET")
* #Template()
* #Security("has_role('ROLE_USER')")
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Voorraad entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Voorraad entity.
*
* #param Voorraad $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Voorraad $entity)
{
$form = $this->createForm(new VoorraadType(), $entity, array(
'action' => $this->generateUrl('voorraad_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Voorraad entity.
*
* #Route("/{id}", name="voorraad_update")
* #Method("PUT")
* #Template("ToolsForEverVoorraadBundle:Voorraad:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Voorraad entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('voorraad_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Voorraad entity.
*
* #Route("/{id}", name="voorraad_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Voorraad entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('voorraad'));
}
/**
* Creates a form to delete a Voorraad entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('voorraad_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Verwijder voorraad'))
->getForm()
;
}
}
VoorraadType.php (form)
<?php
namespace ToolsForEver\VoorraadBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class VoorraadType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('aantal')
->add('locatie', 'entity', array (
'empty_data' => null,
'label' => 'Kies locatie',
'class' => 'ToolsForEver\VoorraadBundle\Entity\Locatie',
'choice_label' => function ($locatie) {
return $locatie->getLocatienaam();
}
))
->add('product', 'entity', array(
'empty_data' => null,
'label' => 'Kies product',
'class' => 'ToolsForEver\VoorraadBundle\Entity\Product',
'choice_label' => function ($product) {
return $product->getNaam();
}
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ToolsForEver\VoorraadBundle\Entity\Voorraad'
));
}
/**
* #return string
*/
public function getName()
{
return 'toolsforever_voorraadbundle_voorraad';
}
}
index.html.twig (view)
{% extends '::base.html.twig' %}
{% block body -%}
<h1 class="hoofdtitel">Voorraad lijst</h1>
<table class="records_list">
<thead>
<tr>
<!-- <th>Id</th> -->
<th>Product</th>
<th>Type</th>
<th>Fabriek</th>
<th>Aantal</th>
<th>Inkoopprijs</th>
<th>Verkoopprijs
<th>Locatie</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<!-- <td>{{ entity.id }}</td> -->
<td>{{ entity.getProduct().getNaam() }}</td>
<td>{{ entity.getProduct().getType() }}</td>
<td>{{ entity.getProduct().getFabriek() }}</td>
<td>{{ entity.aantal }}</td>
<td>{{ entity.getProduct().getInkoopprijs() }}</td>
<td>{{ entity.getProduct().getVerkoopprijs() }}</td>
<td>{{ entity.getLocatie().getLocatienaam() }}</td>
<td>
Voorraad aanpassen
</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<a href="{{ path('voorraad_new') }}">
Nieuwe voorraad toevoegen
</a>
{% endblock %}
So with a simple code in my controller I managed to get the products ordered by location.
So the last step for me is to use a select box to show the products by location and "remove" the products from the list with a other location. The image below is my result so far, and I want the selectbox above this list. Hope somebody can help me out..
You can use a call AJAX for calling anothers controller SF that filter your result and response with new JSON data.
If your response AJAX is correct you can move old result and add a new html code formatting with JS for viewing result select box.
AJAX + controller SF = change result webpage without reloaded this
The Symfony Cookbook provides an example of this: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms
Basically, you need to use the query_builder property of "entity" fields to restrain your Products based on Location. Then, when the User change the value of Location, create a JS script that will submit the form on an asynchronous side request, get the select box of Products in the response and replace it inside the page. You will need to use EventListeners in your form as well, to dynamically update your fields.
However, I find this solution pretty "heavy" in the end, because you have to go through a whole form submission process just to get your list of Products. To improve this, you may create a Controller Action that would return a list of Products based on Location, and call this route when Location is changed.
But in both cases, AJAX and Form EventListeners are mandatory.

Show only results equal to current user id in Symfony2

I have a Gecko bundle that in the index.html.twig file it loops through and shows all geckos in the database, which is working great, no problem.
What i want to do however, is ONLY show geckos that have the same user id linked to them that's equal to the current user's id.
The index file is as follows:
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Gecko list</h1>
<table class="records_list">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Aquisitiondate</th>
<th>Morph</th>
<th>Sex</th>
<th>Genetics</th>
<th>Bio</th>
<th>Bred</th>
<th>Hatchling</th>
<th>Clutch</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<td>{{ entity.name }}</td>
<td>{{ entity.name }}</td>
<td>{% if entity.aquisitionDate %}{{ entity.aquisitionDate|date('Y-m-d H:i:s') }}{% endif %}</td>
<td>{{ entity.morph }}</td>
<td>{{ entity.sex }}</td>
<td>{{ entity.genetics }}</td>
<td>{{ entity.bio }}</td>
<td>{{ entity.bred }}</td>
<td>{{ entity.hatchling }}</td>
<td>{{ entity.clutch }}</td>
<td>
<ul>
<li>
show
</li>
<li>
edit
</li>
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<ul>
<li>
<a href="{{ path('gecko_new') }}">
Create a new entry
</a>
</li>
</ul>
{% endblock %}
How do i go about limiting the view?
EDIT:
This is the Gecko controller:
<?php
namespace Breedr\GeckoBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Breedr\GeckoBundle\Entity\Gecko;
use Breedr\GeckoBundle\Form\GeckoType;
/**
* Gecko controller.
*
* #Route("/gecko")
*/
class GeckoController extends Controller
{
/**
* Lists all Gecko entities.
*
* #Route("/", name="gecko")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('BreedrGeckoBundle:Gecko')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new Gecko entity.
*
* #Route("/", name="gecko_create")
* #Method("POST")
* #Template("BreedrGeckoBundle:Gecko:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Gecko();
$entity->setUser($this->getUser());
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('gecko_show', array('name' => $entity->getName())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Gecko entity.
*
* #param Gecko $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Gecko $entity)
{
$form = $this->createForm(new GeckoType(), $entity, array(
'action' => $this->generateUrl('gecko_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Gecko entity.
*
* #Route("/new", name="gecko_new")
* #Method("GET")
* #Template()
*/
public function newAction()
{
$entity = new Gecko();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Gecko entity.
*
* #Route("/{name}", name="gecko_show")
* #Method("GET")
* #Template()
*/
public function showAction($name)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrGeckoBundle:Gecko')->findOneByName($name);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Gecko entity.');
}
$deleteForm = $this->createDeleteForm($name);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Gecko entity.
*
* #Route("/{name}/edit", name="gecko_edit")
* #Method("GET")
* #Template()
*/
public function editAction($name)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrGeckoBundle:Gecko')->findOneByName($name);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Gecko entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($name);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Gecko entity.
*
* #param Gecko $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Gecko $entity)
{
$form = $this->createForm(new GeckoType(), $entity, array(
'action' => $this->generateUrl('gecko_update', array('name' => $entity->getName())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Gecko entity.
*
* #Route("/{name}", name="gecko_update")
* #Method("PUT")
* #Template("BreedrGeckoBundle:Gecko:edit.html.twig")
*/
public function updateAction(Request $request, $name)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrGeckoBundle:Gecko')->findOneByName($name);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Gecko entity.');
}
$deleteForm = $this->createDeleteForm($name);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('gecko_edit', array('name' => $name)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Gecko entity.
*
* #Route("/{name}", name="gecko_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $name)
{
$form = $this->createDeleteForm($name);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrGeckoBundle:Gecko')->findOneByName($name);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Gecko entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('gecko'));
}
/**
* Creates a form to delete a Gecko entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($name)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('gecko_delete', array('name' => $name)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
EDIT 2:
This is from the Gecko entity:
/**
* #ORM\ManyToOne(targetEntity="Breedr\UserBundle\Entity\User", inversedBy="geckos")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
class GeckoController extends Controller
{
/**
* Lists all Gecko entities.
*
* #Route("/", name="gecko")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$entities = $em->getRepository('BreedrGeckoBundle:Gecko')->findBy('user' => $user->getId());
return array(
'entities' => $entities,
);
}
We have to get user before View, so we can get it by
$user = $this->getUser();
Described here
Getting the user id from logged in user in FOSUserBundle
Next step is to get data from repository by user object
By user object i preffer
$entities = $em
->getRepository('BreedrGeckoBundle:Gecko')
->findBy(array('user' => $user), array()
);
I think it should work.

getId returns empty string in Symfony2

I have made a CRUD for my question object. An error occurred once I tested it.
It seems that the getId() is returning an empty string of some sort.
The default behavior of the autogenerated CRUD is to redirect the user to the view page after successfully creating the entity. But in this case, it returns an error
"Parameter "id" for route "question_show" must match "[^/]++" ("" given) to generate a corresponding URL."
Here is my controller code:
/**
* Creates a new Question entity.
*
* #Route("/ask", name="question_create")
* #Method("POST")
* #Template("VerySoftAskMeBundle:Question:ask.html.twig")
*/
public function createAction(Request $request) {
$entity = new Question();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('question_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
Here is the view action:
/**
* Finds and displays a Question entity.
*
* #Route("/{id}", name="question_show")
* #Method("GET")
* #Template()
*/
public function showAction($id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('VerySoftAskMeBundle:Question')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Question entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to create a Question entity.
*
* #param Question $entity The entity
*
* #return Form The form
*/
private function createCreateForm(Question $entity) {
$form = $this->createForm(new QuestionType(), $entity, array(
'action' => $this->generateUrl('question_create'),
'method' => 'POST',
'em' => $this->getDoctrine()->getEntityManager()
));
$form->add('submit', 'submit', array('label' => 'Ask'));
return $form;
}
How can I fix this?
It seems that your entity is not persisted in the database. Could you check it?
Also, it seems to be a typo in your code your wrote "$form = $this->createCreateForm($entity);", instead of $this->createForm
Otherwise I have used the code below (similar to yours) with no problem
/**
* #Route("/new", name="item_new")
* #Template()
*
* #return array
*/
public function newAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$item = new Item();
$form = $this->createForm(new ItemType(), $item, array(
'action' => $this->generateUrl('item_new'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($item);
$em->flush();
return $this->redirect($this->generateUrl('item_list'));
}
return array('form' => $form->createView());
}
Fixed it. I was inheriting a class named Post which has an $id variable. Turns out that I forgot to delete the $id variable in my Question class which is why Symfony gets confused on what id to return.

Categories