我是MVC的新手,正在尝试通过分配来学习它。
以下是我要做的事情: 我希望用户与表单进行互动,该表单可以选择将项目添加到"购物车"' (是的,我知道在Symfony2中有一个学说,但我不想使用它,我只是想在这里真正理解MVC框架并构建一些简单的东西)。一旦用户将所有项目添加到"购物车"他们可以点击一个说买的按钮。一旦他们点击该按钮,就会显示一个新页面,显示他们在" cart"中添加的所有项目。
这是什么工作: 表单会显示'项目'从另一个表格输入。 CRUD功能正常,用户可以从此显示的表单中编辑或删除项目。
什么不起作用是我添加到"购物车"方面。一旦用户点击添加到购物车,我如何从数据库中获取项目并进入数组?
我认为我需要做的事情: 我知道我需要一个控制器方法来获取从数据库中选择的项目并将它们存储在数组中,或类似的东西。但我迷失了如何做到这一点。在寻找答案时,它们比我需要的更复杂,而且symfony book / cookbook也对我没有帮助。我也使用symfony2的2.7版本。
下面是我的控制器类,以及我的实体文件(我也有相应的存储库文件)。如果需要其他任何东西,请告诉我。
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Item
*
* @ORM\Table(name="items")
* @ORM\Entity(repositoryClass="AppBundle\Entity\ItemRepository")
*/
class Item
{
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="Description", mappedBy="item")
*/
private $descriptions;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
public function __construct() {
$this->descriptions = new ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Item
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Add descriptions
*
* @param \AppBundle\Entity\Description $descriptions
* @return Item
*/
public function addDescription(\AppBundle\Entity\Description $descriptions)
{
$this->descriptions[] = $descriptions;
return $this;
}
/**
* Remove descriptions
*
* @param \AppBundle\Entity\Description $descriptions
*/
public function removeDescription(\AppBundle\Entity\Description $descriptions)
{
$this->descriptions->removeElement($descriptions);
}
/**
* Get descriptions
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getDescriptions()
{
return $this->descriptions;
}
/**
* Render a Item as a string
*
* @return string
*/
public function __toString() {
return $this->getName();
}
}
/////////////////////
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collection\ArrayCollection;
/**
* Description
*
* @ORM\Table(name="descriptions")
* @ORM\Entity(repositoryClass="AppBundle\Entity\DescriptionRepository")
*/
class Description
{
/**
* @var Item
*
* @ORM\ManyToOne(targetEntity="Item", inversedBy="descriptions")
* @ORM\JoinColumn(name="item_id", referencedColumnName="id", onDelete="cascade")
*/
private $item;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var integer
*
* @ORM\Column(name="price", type="integer")
* @Assert\Range(
* min = 1,
* minMessage = "Price needs to be 1 or higher."
* )
*/
private $price;
/**
* @var string
*
* @ORM\Column(name="info", type="string", length=255)
*/
private $info;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set price
*
* @param integer $price
* @return Description
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* @return integer
*/
public function getPrice()
{
return $this->price;
}
/**
* Set info
*
* @param string $info
* @return Description
*/
public function setInfo($info)
{
$this->info = $info;
return $this;
}
/**
* Get info
*
* @return string
*/
public function getInfo()
{
return $this->info;
}
/**
* Set item
*
* @param \AppBundle\Entity\Item $item
* @return Description
*/
public function setItem(\AppBundle\Entity\Item $item = null)
{
$this->item = $item;
return $this;
}
/**
* Get item
*
* @return \AppBundle\Entity\Item
*/
public function getItem()
{
return $this->item;
}
}
/////////////////////// 请看下面的addAction函数.... ////////////////
<?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 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(),
);
}
/**
* Adds Corresponding Item to Cart
*
* @Route("addAction")
* @Method("GET")
* @Template()
*/
public function addAction($id) {
//this method should just take item out of db and list and add the item to cart
//buy button should be at very bottom of item list form and then use items from add button and
//form should be rendered saying all items (list them out) have been bought.
$em = $this->getDoctrine()->getManager();
$entity = $this->getDoctrine()->getRepository('AppBundle:Item')->find($id);
if (!$item) {
throw $this->createNotFoundException('No Item ');
}
$query = $em->createQuery(
'SELECT items as $id
FROM AppBundle:Item'
);
}
/**
* Creates a form for buying items
*
* @param Item $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
public function createBuyForm(Item $entity) {
$form = $this->createForm(new ItemType(), $entity, array(
'action' => $this->generateUrl('item_buy', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Buy'));
return $form;
}
/**
* Finds and displays an Item entity.
*
* @Route("/{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 a 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 a 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()
;
}
}
//////////////////////////
<?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 Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\Description;
use AppBundle\Form\DescriptionType;
/**
* Description controller.
*
* @Route("/description")
*/
class DescriptionController extends Controller
{
/**
* Lists all Description entities.
*
* @Route("/", name="description")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AppBundle:Description')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new Description entity.
*
* @Route("/", name="description_create")
* @Method("POST")
* @Template("AppBundle:Description:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Description();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('description_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Description entity.
*
* @param Description $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Description $entity)
{
$form = $this->createForm(new DescriptionType(), $entity, array(
'action' => $this->generateUrl('description_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Description entity.
*
* @Route("/new", name="description_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$entity = new Description();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Description entity.
*
* @Route("/{id}", name="description_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Description')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Description entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Description entity.
*
* @Route("/{id}/edit", name="description_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Description')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Description 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 Description entity.
*
* @param Description $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Description $entity)
{
$form = $this->createForm(new DescriptionType(), $entity, array(
'action' => $this->generateUrl('description_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Description entity.
*
* @Route("/{id}", name="description_update")
* @Method("PUT")
* @Template("AppBundle:Description:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:Description')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Description entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('description_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Description entity.
*
* @Route("/{id}", name="description_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:Description')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Description entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('description'));
}
/**
* Creates a form to delete a Description 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('description_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
答案 0 :(得分:0)
有几种方法可以将产品添加到数组中。
一种方法是将产品保存在会话中。这样您就可以在应用程序的任何部分访问它们。http://symfony.com/doc/current/components/http_foundation/sessions.html
您可以创建如下会话:
$cart = []; // your currently empty cart array;
$session = $request->getSession();
$session->set('cart', $cart); // assign the cart array to the new session;
正如我可以看到你的addAction方法,你已经得到了产品。
$entity = $this->getDoctrine()->getRepository('AppBundle:Item')->find($id);
$ entity是您根据传递的变量$ id找到的对象(或产品)。
当您拥有该产品时,您只需按照您想要的方式将其插入阵列
例如:
$cart[$entity->getId()] = $entity->getName();
Whitch创建一个这样的数组:
Array
(
[1] => ProductName
[2] => ProductName2
)
在添加或删除以下内容后,请不要忘记更新会话:
$session->set('cart', $cart);
所以你的最终方法看起来像这样:
public function addAction($id) {
$em = $this->getDoctrine()->getManager();
$cart = []; // your currently empty cart array;
$session = $request->getSession();
$session->set('cart', $cart); // assign the cart array to the new session;
$entity = $this->getDoctrine()->getRepository('AppBundle:Item')->find($id);
if (!$item) {
throw $this->createNotFoundException('No Item ');
} else {
$cart[$entity->getId()] = $entity->getName();
}
$session->set('cart', $cart);
}