我正在学习使用 Symfony2 的方式,同时为一家家族经营的 Wine 进口商构建一个小型电子商务网站。慢慢地,我开始理解 Symfony2 的概念,但在继续构建购物车 bundle 时,我不太确定什么是正确的(至少根据 Sf2 标准)实现它的方法。
我根据 session 制作了简单的购物车包。
我的问题是,当我在购物车中添加产品时,它会一直工作,直到产品 ID 为 0 到 9,并且产品数量会自动增加,但是在产品 ID 为 10 之后,它的数量等于产品 ID,而它应该是一个。也是错误的当我们要获取产品信息时,产品信息就来了。
我希望这不是一个太广泛的问题。我很清楚,真正强大的购物车实现并非易事。
<?php
namespace Webmuch\CartBundle\Controller;
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 Symfony\Component\HttpFoundation\Response;
use Webmuch\ProductBundle\Entity\Product;
/**
* @Route("/cart")
*/
class CartController extends Controller
{
/**
* @Route("/", name="cart")
*/
public function indexAction()
{
// get the cart from the session
$session = $this->getRequest()->getSession();
// $cart = $session->set('cart', '');
$cart = $session->get('cart', array());
// $cart = array_keys($cart);
// print_r($cart); die;
// fetch the information using query and ids in the cart
if( $cart != '' ) {
foreach( $cart as $id => $quantity ) {
$productIds[] = $id;
}
if( isset( $productIds ) )
{
$em = $this->getDoctrine()->getEntityManager();
$product = $em->getRepository('WebmuchProductBundle:Product')->findById( $productIds );
} else {
return $this->render('WebmuchCartBundle:Cart:index.html.twig', array(
'empty' => true,
));
}
return $this->render('WebmuchCartBundle:Cart:index.html.twig', array(
'product' => $product,
));
} else {
return $this->render('WebmuchCartBundle:Cart:index.html.twig', array(
'empty' => true,
));
}
}
/**
* @Route("/add/{id}", name="cart_add")
*/
public function addAction($id)
{
// fetch the cart
$em = $this->getDoctrine()->getEntityManager();
$product = $em->getRepository('WebmuchProductBundle:Product')->find($id);
//print_r($product->getId()); die;
$session = $this->getRequest()->getSession();
$cart = $session->get('cart', array());
// check if the $id already exists in it.
if ( $product == NULL ) {
$this->get('session')->setFlash('notice', 'This product is not available in Stores');
return $this->redirect($this->generateUrl('cart'));
} else {
if( isset($cart[$id]) ) {
$qtyAvailable = $product->getQuantity();
if( $qtyAvailable >= $cart[$id]['quantity'] + 1 ) {
$cart[$id]['quantity'] = $cart[$id]['quantity'] + 1;
} else {
$this->get('session')->setFlash('notice', 'Quantity exceeds the available stock');
return $this->redirect($this->generateUrl('cart'));
}
} else {
// if it doesnt make it 1
$cart = $session->get('cart', array());
$cart[$id] = $id;
$cart[$id]['quantity'] = 1;
}
$session->set('cart', $cart);
return $this->redirect($this->generateUrl('cart'));
}
}
/**
* @Route("/remove/{id}", name="cart_remove")
*/
public function removeAction($id)
{
// check the cart
$session = $this->getRequest()->getSession();
$cart = $session->get('cart', array());
// if it doesn't exist redirect to cart index page. end
if(!$cart) { $this->redirect( $this->generateUrl('cart') ); }
// check if the $id already exists in it.
if( isset($cart[$id]) ) {
// if it does ++ the quantity
$cart[$id]['quantity'] = '0';
unset($cart[$id]);
//echo $cart[$id]['quantity']; die();
} else {
$this->get('session')->setFlash('notice', 'Go to hell');
return $this->redirect( $this->generateUrl('cart') );
}
$session->set('cart', $cart);
// redirect(index page)
$this->get('session')->setFlash('notice', 'This product is Remove');
return $this->redirect( $this->generateUrl('cart') );
}
}
{% block body %}
<h1>"FLAIRBAG" SHOPPING-CART</h1>
<ul class="thumbnails">
{% if empty %}
<h5>Your shopping cart is empty.</h5>
{% endif %}
{% set cart = app.session.get('cart') %}
{% if product %}
<ul class="thumbnails">
{% if app.session.hasFlash('notice') %}
<divclass="flash-notice">
{{app.session.flash('notice') }}
{{ app.session.removeFlash('notice') }}
</div>
{% endif %}
{% for key, item in cart %}
<p>ID:{{ key }}</p>
<p>Quantity:{{ item }}</p>
<button class="btn btn-primary"><a href="{{ path('cart_remove', {'id': key}) }}">Remove</a></button>
{% for item in product %}
<p>{{ item.title }}</p>
<p>{{ item.preview }}</p>
{% endfor %}
{% endfor %}
</ul>
{% endif %}
</ul>
<a href="{{ path('products') }}">Products</a>
{% endblock %}
请帮我解决这个问题。
谢谢!感谢您的帮助。
最佳答案
问题出在您的购物车数组中。根据您的模板,您希望有一个具有这种结构的数组:
cart {
id => quantity
}
即,数组的键是产品的 ID,值是数量
但随后在您的 Controller 中您会:
$cart[$id] = $id;
$cart[$id]['quantity'] = 1;
这是一个非常不同的事情。你应该这样做:
$cart[$id] = 1;
在 Controller 中使用 $cart[$id]['quantity'] 的所有其他地方,请改用 $cart[$id]。例如:
$cart[$id] = $cart[$id] + 1;
编辑:
在你的 Controller 中做:
$em = $this->getDoctrine()->getEntityManager();
foreach( $cart as $id => $quantity ) {
$product[] = $em->getRepository('WebmuchProductBundle:Product')->findById($id)
}
if( !isset( $product ) )
{
return $this->render('WebmuchCartBundle:Cart:index.html.twig', array(
'empty' => true,
));
}
关于php - 带有 Symfony2 的购物车 bundle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12243230/
我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="
使用rspec-rails3.0+,测试设置分为spec_helper和rails_helper我注意到生成的spec_helper不需要'rspec/rails'。这会导致zeus崩溃:spec_helper.rb:5:in`':undefinedmethod`configure'forRSpec:Module(NoMethodError)对thisissue最常见的回应是需要'rspec/rails'。但这是否会破坏仅使用spec_helper拆分rails规范和PORO规范的全部目的?或者这无关紧要,因为Zeus无论如何都会预加载Rails?我应该在我的spec_helper中做
假设我有一个类A,里面有一些方法。假设stringmethodName是这些方法之一,我已经知道我想给它什么参数。它们在散列中{'param1'=>value1,'param2'=>value2}所以我有:params={'param1'=>value1,'param2'=>value2}a=A.new()a.send(methodName,value1,value2)#callmethodnamewithbothparams我希望能够通过传递我的哈希以某种方式调用该方法。这可能吗? 最佳答案 确保methodName是一个符号,而
当我进入Rails控制台时,我已将pry设置为加载代替irb。我找不到该页面或不记得如何将其恢复为默认行为,因为它似乎干扰了我的Rubymine调试器。有什么建议吗? 最佳答案 我刚发现问题,pry-railsgem。忘记了它的目的是让“railsconsole”打开pry。 关于ruby-on-rails-带有Pry的Rails控制台,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/question
我了解instance_eval和class_eval之间的基本区别。我在玩弄时发现的是一些涉及attr_accessor的奇怪东西。这是一个例子:A=Class.newA.class_eval{attr_accessor:x}a=A.newa.x="x"a.x=>"x"#...expectedA.instance_eval{attr_accessor:y}A.y="y"=>NoMethodError:undefinedmethod`y='forA:Classa.y="y"=>"y"#WHATTT?这是怎么回事:instance_eval没有访问我们的A类(对象)然后它实际上将它添加到
为了在我的mac上为一个rails项目安装mysql,我遵循了安装Homebrew软件和删除mac端口的在线建议。这是问题开始的地方。rails项目不会构建,我得到这个:[rake--prereqs]rakeaborted!dlopen(/Users/Parker/.rvm/gems/ruby-1.9.3-p448/gems/nokogiri-1.6.0/lib/nokogiri/nokogiri.bundle,9):Librarynotloaded:/opt/local/lib/libiconv.2.dylibReferencedfrom:/Users/Parker/.rvm/gem
我在一个简单的RailsAPI中有以下Controller代码:classApi::V1::AccountsControllerehead:not_foundendendend问题在于,生成的json具有以下格式:{id:2,name:'Simpleaccount',cash_flows:[{id:1,amount:34.3,description:'simpledescription'},{id:2,amount:1.12,description:'otherdescription'}]}我需要我生成的json是camelCase('cashFlows'而不是'cash_flows'
在Ruby(或Rails)中,我们可以做到new_params=params.merge({:order=>'asc'})现在new_params是一个带有添加键:order的散列。但是是否有一行可以返回带有已删除key的散列?线路new_params=params.delete(:order)不会工作,因为delete方法返回值,仅此而已。我们必须分3步完成吗?tmp_params=paramstmp_params.delete(:order)returntmp_params有没有更好的方法?因为我想做一个new_params=(params[:order].blank?||para
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我来自C、php和bash背景,很容易学习,因为它们都有相同的C结构,我可以将其与我已经知道的联系起来。然后2年前我学了Python并且学得很好,Python对我来说比Ruby更容易学。然后从去年开始,我一直在尝试学习Ruby,然后是Rails,我承认,直到现在我还是学不会,讽刺的是那些打着简单易学的烙印,但是对于我这样一个老练的程序员来说,我只是无法将它
如何使用rubyonrails获取网络上某处其他网站的页面数据? 最佳答案 您可以使用httparty只是获取数据示例代码(来自example):requireFile.join(dir,'httparty')require'pp'classGoogleincludeHTTPartyformat:htmlend#google.comredirectstowww.google.comsothisislivetestforredirectionppGoogle.get('http://google.com')puts'','*'*7