getId returns empty string in Symfony2 - php

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.

Related

How to reduce code without inheriting on Symfony, php and html

I am wondering if there is a way I can reduce my code without inheriting.
And what would be the best practice?
I am working with Symfony. I have old code and I need to do some forms.
Most of them are quite similar.
I have many controllers, and forms and only few differences among them.
Here is an example of a controller.
Only (NAMETOBECHANGED) changes among the controllers.
<?php
namespace Data\LiveBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Data\LiveBundle\Entity\DataAPatient;
use Data\LiveBundle\Entity\DataDNaMETOBECHANGED;
/**
* DataDNaMETOBECHANGED controller.
*
*/
class DataDNaMETOBECHANGEDController extends Controller
{
/**
* Lists all DataDNaMETOBECHANGED entities.
*
*/
public function indexAction(Request $request, $limit, $offset)
{
$repo = $this->getDoctrine()->getManager()->getRepository('DataLiveBundle:DataDNaMETOBECHANGED');
$qb = $repo->getDefaultQuery();
return $this->renderIndex($repo, $qb, $limit, $offset, 'default');
}
/**
* Lists all DataDNaMETOBECHANGED entities sorted by a chosen column.
*
*/
public function indexSortAction(Request $request, $limit, $offset, $column){
$repo = $this->getDoctrine()->getManager()->getRepository('DataLiveBundle:DataDNaMETOBECHANGED');
$qb = $repo->getDefaultQueryOrdered($column);
return $this->renderIndex($repo, $qb, $limit, $offset, $column);
}
/**
* Renders the index page
*
*/
private function renderIndex($repo, $qb, $limit, $offset, $column)
{
//TODO: Add Access-Control
if (!$this->isAdmin()) {
throw new AccessDeniedException();
}
//model taken from Events
//$queryHelper = $this->get('general_commonbundle.util.queryhelper');
//$qb = $queryHelper->addProjectFilter($qb);
//if(!$this->isAdmin()){
//$qb = $queryHelper->addAccessControl($qb);
//}
$total = $repo->countQueryResults($qb);
$qb = $repo->addLimitToQuery($qb, $limit, $offset);
$paginationOptions = array(
'total' => $total,
'limit' => $limit,
'offset' => $offset
);
$entities = $repo->getResults($qb);
//TODO: lock dataset if 180 days passed.
$editable = array();
foreach($entities as $entity){
$this->isAdmin(); // TODO: owner check: $editable[$entity->getPKpPatientid()] = $this->isOwner($entity->getPKpPatientid())
}
// Disable softdelete filter, such that view can access all foreign keys.
// View needs to distinguish between still existent foreign keys and deleted ones.
$em = $this->getDoctrine()->getManager();
if (array_key_exists('softdeleteable', $em->getFilters()->getEnabledFilters())) {
$em->getFilters()->disable('softdeleteable');
}
return $this->render('DataLiveBundle:DataDNaMETOBECHANGED:index.html.twig', array(
'entities' => $entities,
'editable' => $editable,
'paginationOptions' => $paginationOptions,
'orderColumn' => $column,
'parentRoute' => $this->generateUrl('datadnaMeTOBECHANGED')
));
}
/**
* Finds and displays an DataDNaMETOBECHANGED entity.
*
*/
public function showAction($pKpPatientid)
{
if (!$this->isAdmin()) {
throw new AccessDeniedException();
}
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('DataLiveBundle:DataDNaMETOBECHANGED')->find($pKpPatientid);
if (!$entity) {
throw $this->createNotFoundException('Unable to find DataDNaMETOBECHANGED entity.');
}
// Access control
if($this->isAdmin() // || $this->isOwner($pKpPatientid)
) {
// allow access
}
else {
throw new AccessDeniedException();
}
// Disable softdelete filter, such that view can access all foreign keys.
// View needs to distinguish between still existent foreign keys and deleted ones.
if (array_key_exists('softdeleteable', $em->getFilters()->getEnabledFilters())) {
$em->getFilters()->disable('softdeleteable');
}
$editable = $this->isAdmin(); //$this->isOwner($entity->getPKpPatientid())
$print = $this->getRequest()->get('print') == '1';
return $this->render('DataLiveBundle:DataDNaMETOBECHANGED:show.html.twig', array(
'entity' => $entity,
'editable' => $editable,
'isPreview' => false,
'print' => $print,
));
}
/**
* Redirects to preview a new DataAPatient entity.
*
*/
public function newAction(Request $request)
{
if (!$this->isAdmin()) {
throw new AccessDeniedException();
}
$entity = new DataAPatient();
$em = $this->getDoctrine()->getManager();
$entity->setPDateOfBirth(new \DateTime('now'));
// $entity->setTimeStart(new \DateTime('now'));
// $entity->setTimeEnd(new \DateTime('now'));
$newForm = $this->createNewForm($entity);
$entity->setDatetimeCreated( new \DateTime('now') );
$entity->setDatetimeChanged (new \DateTime ('now'));
//TODO: set SNNID
$newForm->handleRequest($request);
if ($newForm->isValid()) {
if($newForm->get('submit')->isClicked()){//Save
$pKpPatientid = $this->storeNewDataAPatient($entity);
return $this->redirect($this->generateUrl('dataapatient_sendMessage', array("pKpPatientid" => $pKpPatientid)));
}
}
return $this->render('DataLiveBundle:DataDNaMETOBECHANGED:form.html.twig', array(
'entity' => $entity,
'form' => $newForm->createView(),
'isNew'=> true,
));
}
/**
* Creates a form to create a new DataAPatient entity.
*
* #param DataAPatient $entity The entity
*
* #return \Symfony\Component\Form\Form
*
*/
private function createNewForm(DataAPatient $entity)
{
$form = $this->createForm($this->get('data_livebundle.form.dataapatienttype'), $entity, array(
'action' => $this->generateUrl('dataapatient_new'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Redirects to preview changes made to an existing DataDNaMETOBECHANGED entity.
*
*/
public function editAction(Request $request, $pKpPatientid)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('DataLiveBundle:DataDNaMETOBECHANGED')->find($pKpPatientid);
if (!$entity) {
throw $this->createNotFoundException('Unable to find DataDNaMETOBECHANGED entity.');
}
//Access control
if (!$this->isAdmin() //&& !$this->isOwner($pKpPatientid)
) {
throw new AccessDeniedException();
}
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
//Refresh Changed-Date
$entity->setDatetimeChanged( new \DateTime('now') );
//Set naMeTOBECHANGEDAgeRef in DataDNaMETOBECHANGED
$entity->getDNaMETOBECHANGED()->setNaMETOBECHANGEDAgeRef (round($entity->getDNaMETOBECHANGED()->getNaMETOBECHANGEDAgeCalc(),0));
if($editForm->get('submit')->isClicked()){//Save
$em->persist($entity);
//Store changes
$pKpPatientid = $this->storeEditedDataDNaMETOBECHANGED($entity);
//TODO: log changes in history
if($editForm->get('submit')->isClicked()){
return $this->redirect($this->generateUrl('datadnaMeTOBECHANGED_show', array('pKpPatientid' => $pKpPatientid)));
}
}
}
return $this->render('DataLiveBundle:DataDNaMETOBECHANGED:form.html.twig', array(
'entity' => $entity,
'form' => $editForm->createView(),
'isNew' => false,
));
}
/**
* Creates a form to edit a DataDNaMETOBECHANGED entity.
*
* #param DataDNaMETOBECHANGED $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(DataDNaMETOBECHANGED $entity)
{
$form = $this->createForm($this->get('data_livebundle.form.datadnaMeTOBECHANGEDtype'), $entity, array(
'action' => $this->generateUrl('datadnaMeTOBECHANGED_edit', array('pKpPatientid' => $entity->getPKpPatientid())),
'method' => 'POST'
));
$form->add('submit', 'submit', array('label' => 'Save Changes'));
return $form;
}
/**
* Persists changes made to an existing DataDNaMETOBECHANGED entity to the database
*
*/
private function storeEditedDataDNaMETOBECHANGED($entity)
{
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
if (!$entity) {
throw $this->createNotFoundException('Unable to find DataDNaMETOBECHANGED entity.');
}
$pSnnid = $entity->getPSnnid();
$em->persist($entity);
$em->flush();
$session->getFlashBag()->add(
'notice',
'Your changes to the DataDNaMETOBECHANGED of ID: "'.$pSnnid. '" was saved!'
);
return $entity->getPKpPatientid();
}
/**
* Persists a new DataDNaMETOBECHANGED entity to the database
*
*/
private function storeNewDataDNaMETOBECHANGED($entity)
{
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
if (!$entity) {
throw $this->createNotFoundException('Unable to find DataDNaMETOBECHANGED entity.');
}
$pSnnid = $entity->getPSnnid();
$em->persist($entity);
$em->flush();
$session->getFlashBag()->add(
'notice', 'The new DataDNaMETOBECHANGED for "'.$pSnnid. '" was saved!'
);
return $entity->getPKpPatientid();
}
/**
* Removes hospital entity from the database by pKpPatientid
*
*/
public function deleteAction(Request $request, $pKpPatientid)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('DataLiveBundle:DataDNaMETOBECHANGED')->find($pKpPatientid);
if (!$entity) {
throw $this->createNotFoundException('Unable to find DataDNaMETOBECHANGED entity.');
}
//Access control
if (!$this->isAdmin()) {
throw new AccessDeniedException();
}
$pSnnid = $entity -> getPSnnid();
$em->remove($entity);
$em->flush();
$this->getRequest()->getSession()->getFlashBag()->add(
'notice',
'The DataDNaMETOBECHANGED for "'.$pSnnid.'" was deleted successfully!'
);
return $this->redirect($this->generateUrl('datadnaMeTOBECHANGED'));
}
/**
* Returns whether current user has role ROLE_ADMIN
*
* #return boolean
*/
private function isAdmin()
{
return $this->get('security.context')->isGranted('ROLE_ADMIN');
}
/**
* Returns whether current user has ID '$pKpPatientid'
*
* #param mixed $pKpPatientid The entity id which current user wants to edit
*
* #return boolean
*/
private function isOwner($pKpPatientid)
{
$em = $this->getDoctrine()->getManager();
// Disable softdeletable filter (only if it's not already inactive)
if (array_key_exists('softdeleteable', $em->getFilters()->getEnabledFilters())) {
$em->getFilters()->disable('softdeleteable');
}
$entity = $em->getRepository('DataLiveBundle:DataDNaMETOBECHANGED')->find($pKpPatientid);
$result = $entity->getFKOwner()->getPKpPatientid() == $this->get('security.context')->getToken()->getUser()->getPKpPatientid();
// Enable softdeletable filter before returning
$em->getFilters()->enable('softdeleteable');
return $result;
}
}
And for HTML, here is an example:
<div class='col-xs-4'>
<div class='col-xs-7'>{{ form_label(form.dFu2.fu2MdiRaw, 'Cognitive RAW score:', {'label_attr':{'style':'margin-top:3px'}})}}</div>
<div class='col-xs-2'>{{ form_widget(form.dFu2.fu2MdiRaw, {'attr':{'style':'width:50px'}})}}</div>
</div>
This kind of piece of code repeats itself a lot among the forms. And in each for most of the time only fu1, fu2, fu3, ... change.
Thank your for your advice!

How to - Symfony 2 Perform CRUD without passing ID to url

After long time of lerking on these boards I have finally decided to make my first post. I have recently started to play around with Symfony (2.4, don't yell at me please :) ). Using doctrine's terminal commands I generated CRUD events. Now, that is great and all, except that you have to pass the ID in the url, for example: www.mydomain.com/account/16/. This will pre-fill the form with the data from a row that has id 16 in mysql. My question is, how do I manipulate the pre-made CRUD (only interested in the update) so that I don't have to pass the id to the url, but rather, it renders the form based on the id the logged in user has associated with their account?
Here is my code:
class AccountController extends Controller
{
/**
* Displays a form to edit an existing Event entity.
* #Route("/account/{id}", name="post_login_account_edit")
* #PreAuthorize("isFullyAuthenticated()")
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('UserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Event entity.');
}
$editForm = $this->createEditForm($entity);
return $this->render('UserBundle:Account:account.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView()
));
}
/**
* Creates a form to edit a Event entity.
*
* #param User $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(User $entity)
{
$form = $this->createForm(new UserType(), $entity, array(
'action' => $this->generateUrl('post_login_account_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing User entity.
* #Route("/account/{id}/update", name="post_login_account_update")
* #PreAuthorize("isFullyAuthenticated()")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('UserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Event entity.');
}
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('post_login_account'));
}
return $this->render('UserBundle:Account:account.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView()
));
}
}
Simply get logged in user in controller:
$entity = $this->get('security.context')->getToken()->getUser();

Remove elements from session array

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

Different type expected in Symfony

I am trying to create a form using Symfony and Doctrine.
I created a Job class, and a table in mysql which relates to it, using Doctrine. It also made the JobType and JobController, and Routing facility.
I can access the index page, where the jobs are listed, but can't access the new entry page.
Here are the files used for creating the forms.
JobController.php
<?php
namespace AppBundle\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 AppBundle\Entity\Job;
use AppBundle\Form\JobType;
/**
* Job controller.
*
* #Route("/job")
*/
class JobController extends Controller
{
/**
* Lists all Job entities.
*
* #Route("/", name="job_index")
* #Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$jobs = $em->getRepository('AppBundle:Job')->findAll();
return $this->render('job/index.html.twig', array(
'jobs' => $jobs,
));
}
/**
* Creates a new Job entity.
*
* #Route("/new", name="job_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$job = new Job();
$jobType = new JobType();
$form = $this->createForm($jobType, $job);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($job);
$em->flush();
return $this->redirectToRoute('job_show', array('id' => $job->getId()));
}
return $this->render('job/new.html.twig', array(
'job' => $job,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Job entity.
*
* #Route("/{id}", name="job_show")
* #Method("GET")
*/
public function showAction(Job $job)
{
$deleteForm = $this->createDeleteForm($job);
return $this->render('job/show.html.twig', array(
'job' => $job,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing Job entity.
*
* #Route("/{id}/edit", name="job_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Job $job)
{
$deleteForm = $this->createDeleteForm($job);
$editForm = $this->createForm(new JobType(), $job);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($job);
$em->flush();
return $this->redirectToRoute('job_edit', array('id' => $job->getId()));
}
return $this->render('job/edit.html.twig', array(
'job' => $job,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Job entity.
*
* #Route("/{id}", name="job_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, Job $job)
{
$form = $this->createDeleteForm($job);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($job);
$em->flush();
}
return $this->redirectToRoute('job_index');
}
/**
* Creates a form to delete a Job entity.
*
* #param Job $job The Job entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Job $job)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('job_delete', array('id' => $job->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
JobType.php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class JobType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', 'string')
->add('type', 'string')
->add('company', 'string')
->add('logo', 'string')
->add('url', 'string')
->add('position', 'string')
->add('location', 'string')
->add('desciption', 'text')
->add('how_to_apply', 'text')
->add('token', 'string')
->add('is_public', 'boolean')
->add('is_activated', 'boolean')
->add('email', 'string')
->add('expires_at', 'datetime')
->add('created_at', 'datetime')
->add('updated_at', 'datetime')
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Job'
));
}
/**
* Mandatory in Symfony2
* Gets the unique name of this form.
* #return string
*/
public function getName()
{
return 'add_job';
}
}
This is the error I receive
Thanks!
EDIT:
The content of app/config/services.yml
parameters:
# parameter_name: value
services:
# service_name:
# class: AppBundle\Directory\ClassName
# arguments: ["#another_service_name", "plain_value", "%parameter_name%"]
$editForm = $this->createForm(new JobType(), $job);
This is no longer possible in Symfony 3. In Symfony 3, you always have to pass the fully-qualified class name for form types:
$editForm = $this->createForm(JobType::class, $job);
Also, in your form type you're passing the type name instead of the FQCN of the type classes.
Symfony 3 has just released its first BETA, which means it's very bleeding edge. Also, there are almost zero tutorials for Symfony 3 yet (as it's so extremely bleeding edge). You're reading a Symfony 2 tutorial, so I recommend you to install Symfony 2 instead of 3.

Symfony 2 UniqueEntity repositoryMethod fails on Update Entity

I'm working on some simple script, but can't wrap my head around this problem.
So here it is.
/**
* Booking
* #ORM\Table()
* #ORM\Entity(repositoryClass="Tons\BookingBundle\Entity\BookingRepository")
* #UniqueEntity(fields={"room", "since", "till"}, repositoryMethod="getInterferingRoomBookings")
* #Assert\Callback(methods={"isSinceLessThanTill"}, groups={"search","default"})
*/
class Booking
and repository Method
/**
* Get room state for a certain time period
*
* #param array $criteria
* #return array
*/
public function getInterferingRoomBookings(array $criteria)
{
/** #var $room Room */
$room = $criteria['room'];
$builder = $this->getQueryForRoomsBooked($criteria);
$builder->andWhere("ira.room = :room")->setParameter("room", $room);
return $builder->getQuery()->getArrayResult();
}
The problem is that this works on create methods like it should,
but when updating existing entity - it violates this constrain.
I tried to add Id constrain, but when creating entities, id is null, so repository Method don't even starts.
Also i tried to remove Entity and then recreate it. like
$em->remove($entity);
$em->flush();
//-----------
$em->persist($entity);
$em->flush();
but this also does not work.
Create Action
/**
* Creates a new Booking entity.
*
* #Route("/create", name="booking_create")
* #Method("POST")
* #Template("TonsBookingBundle:Booking:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Booking();
$form = $this->createForm(new BookingType(), $entity);
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$room = $entity->getRoom();
if($room->getLocked() && $room->getLockedBy()->getId() === $this->getUser()->getId())
{
$entity->setCreatedAt(new \DateTime());
$entity->setUpdatedAt(new \DateTime());
$entity->setManager($this->getUser());
$em->persist($entity);
$room->setLocked(false);
$room->setLockedBy(null);
$room->setLockedAt(null);
$em->persist($room);
$em->flush();
return $this->redirect($this->generateUrl('booking_show', array('id' => $entity->getId())));
}
else
{
$form->addError(new FormError("Номер в текущий момент не заблокирован или заблокирован другим менеджером"));
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
Update Action
/**
* Edits an existing Booking entity.
*
* #Route("/edit/{id}/save", name="booking_update")
* #Method("PUT")
* #Template("TonsBookingBundle:Booking:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
/** #var $em EntityManager */
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('TonsBookingBundle:Booking')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Booking entity.');
}
$editForm = $this->createForm(new BookingType(), $entity);
$editForm->bind($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('booking_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'form' => $editForm->createView(),
);
}
I got this!
I changed annotation to this
/**
* Booking
* #ORM\Table()
* #ORM\Entity(repositoryClass="Tons\BookingBundle\Entity\BookingRepository")
* #UniqueEntity(fields={"id","room", "since", "till"}, repositoryMethod="getInterferingRoomBookings")
* #UniqueEntity(fields={"room", "since", "till"}, repositoryMethod="getInterferingRoomBookings",groups={"create"})
* #Assert\Callback(methods={"isSinceLessThanTill"}, groups={"search","default"})
*/
class Booking
Copy BookingType to BookingTypeCreate And added
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Tons\BookingBundle\Entity\Booking',
'validation_groups' => array('create'),
));
}
To form defaults. So now parameters are different when passing entity to validation method.
I think it's still a workaround method.
Short answer: You're not getting the form data into the entity, so you are working with a new entity that does not know its room has been set in the form.
Long answer: Getting the form data and putting it into the entity allows you to manipulate the data before update. See modified controller below. Key line is
$entity = form->getData(); Which then allows you to $room=$entity->getRoom();
/**
* Creates a new Booking entity.
*
* #Route("/create", name="booking_create")
* #Method("POST")
* #Template("TonsBookingBundle:Booking:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Booking();
$form = $this->createForm(new BookingType(), $entity);
$form->bind($request);
$entity = $form->getData(); // Lighthart's addition
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$room = $entity->getRoom();
if($room->getLocked() && $room->getLockedBy()->getId() === $this->getUser()->getId())
{
$entity->setCreatedAt(new \DateTime());
$entity->setUpdatedAt(new \DateTime());
$entity->setManager($this->getUser());
$em->persist($entity);
$room->setLocked(false);
$room->setLockedBy(null);
$room->setLockedAt(null);
$em->persist($room);
$em->flush();
return $this->redirect($this->generateUrl('booking_show', array('id' => $entity->getId())));
}
else
{
$form->addError(new FormError("Номер в текущий момент не заблокирован или заблокирован другим менеджером"));
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
Pass an additional identifier (maybe a token) to the unique check field (for example loginName) (fields={"token", "loginName"}), to the repositoryMethod. The id itself is not working, it is null on object creation and the repositoryMethod is not executed. I create the token in the constructor Method. The token is needed to identify the entity on creation or update action.
/**
* #ORM\Table(name="anbieterregistrierung")
* #ORM\Entity(repositoryClass="AnbieterRegistrierungRepository")
* #UniqueEntity(
* fields={"token", "loginName"},
* repositoryMethod="findUniqueEntity"
* )
*/
then in repository class you edit the WHERE DQL:
public function findUniqueEntity(array $parameter)
{
$loginName = $parameter['loginName'];
$token = $parameter['token'];
.
.
.
. . . WHERE anbieterregistrierung.loginName = :loginName AND anbieterregistrierung.token <> :token
.
.
.
}

Categories