在非商店页面上将产品添加到购物车

Add product to cart on a non shop page

我们使用的是企业版Odoo 12软件。

我们想复制产品页面上添加到购物车按钮的行为。 所以我们想在不同的页面上添加一个按钮,当您单击该按钮时,您将产品添加到您的购物车并被重定向到您的购物车。 该产品已硬编码到该按钮。

这是产品页面模板上使用的表单:

       <form t-if="product._is_add_to_cart_possible()" action="/shop/cart/update" method="POST">
          <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
          <div class="js_product js_main_product">
            <t t-placeholder="select">
              <input type="hidden" class="product_id" name="product_id" t-att-value="product_variant.id"/>
              <input type="hidden" class="product_template_id" name="product_template_id" t-att-value="product.id"/>
              <t t-if="first_possible_combination" t-call="sale.variants">
                <t t-set="ul_class" t-value="'flex-column'"/>
                <t t-set="parent_combination" t-value="None"/>
              </t>
              <t t-else="">
                <ul class="d-none js_add_cart_variants" t-att-data-attribute_exclusions="{'exclusions: []'}"/>
              </t>
            </t>
            <t t-call="website_sale.product_price"/>
            <p t-if="True" class="css_not_available_msg alert alert-warning">This combination does not exist.</p>
            <a role="button" id="add_to_cart" class="btn btn-primary btn-lg mt8 js_check_product a-submit" href="#">Add to Cart</a>
          </div>
        </form>

我们产品的信息:product.id = 135product_template.id = 83

我发现负责添加到购物车的 javascript 调用使用:/web/content/.../.../web.assets_frontend.js。这是一个非常大的文件,但您可以在此处查看示例:file.

我应该在我的自定义页面上添加哪个 qweb/form/js/... 以将产品添加到我的购物车?

感谢您的帮助,我已经坚持了很长时间!

编辑: 正如@Philippe Pageau 指出的那样,我已经可以使用一些代码来获得正确的产品。我已经尝试使用此代码(我能想到的最简单版本的表单)通过表单实现它:

      <t t-set="products" t-value="request.env['product.product'].search([['id', '=', 135]])"/>
        <t t-foreach="products" t-as="product">
          <form action="/shop/cart/update" method="POST">
             <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
             <input type="hidden" class="product_id" name="product_id" value="135"/>
             <input type="hidden" class="product_template_id" name="product_template_id" value="83"/>
             <a role="button" id="add_to_cart" class="btn btn-primary btn-lg mt8 js_check_product a-submit" href="#">Add to Cart</a>
          </form>
      </t>

但这没有任何作用,我错过了什么?

编辑2:

感谢@Adan Cortes,我们现在更进一步了,但还有 1 个问题。

现在,当用户点击按钮时,产品会以特定数量添加到购物车。

现在这是我的代码:

<t t-set="products" t-value="request.env['product.product'].search([['id', '=', 135]])"/>
      <t t-foreach="products" t-as="product">
        <div id="product_detail" class="oe_website_sale">
          <form action="/shop/cart/update" method="POST">
              <h4 t-esc="product.name"/>
              <h6 t-esc="product.price"/>
              <input class="form-control" data-min="1" name="add_qty" value="1"/>
              <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
              <input type="hidden" class="product_id" name="product_id" value="135"/>
              <a role="button" id="add_to_cart" class="btn btn-primary btn-lg mt8 js_check_product a-submit" href="#">Add to Cart</a>
          </form>
        </div>
      </t> 

但这些是我最后的问题:

据我了解,您需要请求产品,因为它不仅需要产品,还需要模板。

我为我的采购订单页面获取我所有的产品。 因此,这就是我创建产品变量的方法。

<t t-set="products" t-value="request.env['product.product'].search([])/>
<t t-foreach="products" t-as="product">
<!-- your code here -->
</t>

搜索特定产品

.search(['id', '=', yourId])

请注意,它会 return 你一个数组,即使有指定的 id

以下代码有效:

<div id="product_detail" class="oe_website_sale">
    <form action="/shop/cart/update" method="POST">
        <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
        <input type="hidden" class="product_id" name="product_id" value="135"/>
        <a role="button" id="add_to_cart" class="btn btn-primary btn-lg mt8 js_check_product a-submit" href="#">Add to Cart</a>
    </form>
</div>

但请注意,使用数据库 ID 会使您的模块在其他地方无法使用。你最好使用 xmlids。

您丢失的相关 JavaScript 位于:

<path_to_v12>/addons/website_sale/static/src/js/website_sale.js

135 sAnimations.registry.WebsiteSale = sAnimations.Class.extend(ProductConfiguratorMixin, {
136     selector: '.oe_website_sale',
137     read_events: {
138         'change form .js_product:first input[name="add_qty"]': '_onChangeAddQuantity',
139         'mouseup .js_publish': '_onMouseupPublish',
140         'touchend .js_publish': '_onMouseupPublish',
141         'change .oe_cart input.js_quantity[data-product-id]': '_onChangeCartQuantity',
142         'click .oe_cart a.js_add_suggested_products': '_onClickSuggestedProduct',
143         'click a.js_add_cart_json': '_onClickAddCartJSON',
144         'click .a-submit': '_onClickSubmit',
145         'change form.js_attributes input, form.js_attributes select': '_onChangeAttribute',
146         'mouseup form.js_add_cart_json label': '_onMouseupAddCartLabel',
147         'touchend form.js_add_cart_json label': '_onMouseupAddCartLabel',
148         'click .show_coupon': '_onClickShowCoupon',
149         'submit .o_website_sale_search': '_onSubmitSaleSearch',
150         'change select[name="country_id"]': '_onChangeCountry',
151         'change #shipping_use_same': '_onChangeShippingUseSame',
152         'click .toggle_summary': '_onToggleSummary',
153         'click input.js_product_change': 'onChangeVariant',
154         'change .js_main_product [data-attribute_exclusions]': 'onChangeVariant',
155     },

<path_to_v12>/addons/website_sale/static/src/js/website_sale_tracking.js

  5 sAnimations.registry.websiteSaleTracking = sAnimations.Class.extend({
  6     selector: '.oe_website_sale',
  7     read_events: {
  8         'click form[action="/shop/cart/update"] a.a-submit': '_onAddProductIntoCart',
  9         'click a[href="/shop/checkout"]': '_onCheckoutStart',
 10         'click div.oe_cart a[href^="/web?redirect"][href$="/shop/checkout"]': '_onCustomerSignin',
 11         'click form[action="/shop/confirm_order"] a.a-submit': '_onOrder',
 12         'click form[target="_self"] button[type=submit]': '_onOrderPayment',
 13     },

编辑添加

表单数据由以下控制器处理和调度:

<path_to_v12>/addons/website_sale/controllers/main.py

414     @http.route(['/shop/cart/update'], type='http', auth="public", methods=['POST'], website=True, csrf=False)
415     def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):
416         """This route is called when adding a product to cart (no options)."""
418         sale_order = request.website.sale_get_order(force_create=True)
419         if sale_order.state != 'draft':
420             request.session['sale_order_id'] = None
421             sale_order = request.website.sale_get_order(force_create=True)
422 
423         product_custom_attribute_values = None
424         if kw.get('product_custom_attribute_values'):
425             product_custom_attribute_values = json.loads(kw.get('product_custom_attribute_values'))
426 
427         no_variant_attribute_values = None
428         if kw.get('no_variant_attribute_values'):
429             no_variant_attribute_values = json.loads(kw.get('no_variant_attribute_values'))
430 
431         sale_order._cart_update(
432             product_id=int(product_id),
433             add_qty=add_qty,
434             set_qty=set_qty,
435             product_custom_attribute_values=product_custom_attribute_values,
436             no_variant_attribute_values=no_variant_attribute_values
437         )
438         return request.redirect("/shop/cart")