0

I used the following code to implement "add to cart" in my tpl.php file, and it works fine:

$product=commerce_product_load($node->field_product['und'][0]['product_id']);
$line_item = commerce_product_line_item_new($product,1);
$line_item->data['context']['product_ids'] = array($product->product_id);
$show_quantity = TRUE;

$form = drupal_get_form('commerce_cart_add_to_cart_form', $line_item,$show_quantity);
print render($form);

Right now, it can only use its original price. However, I want to add this product with a special price to the cart and use this special price to checkout.

I have already created a "Price" field named "field_special_price", and if I use print_r($product), I can see its value and can use the value by $product->field_special_price['und'][0]['amount']

1

You need to use a rule that acts on the "Calculating the sales price of an item" and then set the price using that rule. Here is an example: https://drupalcommerce.org/user-guide/sell-price-calculation

| improve this answer | |
  • But I just have the special price for some of the products. Different price for different product. Do you have any idea about this? – jmu Jun 23 '16 at 13:45
  • Sure. You can test for the value of the field and use it if is is there—otherwise don't touch the price. – nvahalik Jun 23 '16 at 15:38
0

Thank you @nvahalik!

Based on @nvahalik answer, I create a new rule. I created a new field because I have so many different products and each product has its own special price. Here are the steps:

  1. create a new price field named "field_special_price"
  2. create a new pricing rule (event:Calculating the sell price of a product) (you can find the steps in the link from @nvahalik answer)
  3. Add first condition : Entity has Field (the image is my first condition) enter image description here

  4. Add second condition: Entity has Field

Entity-Data selector: "commerce-line-item:commerce-product"(based on first condition)

Field-Value: "field_special_price"

5.Add third condition: Data value is empty

Data to check: commerce-line-item:commerce-product:field_special_price(based on second condition)

Select "Negate"

  1. Add first action:Calculate a value

Hint: Mix "commerce-line-item:commerce-product:field_special_price:amount" & "commerce-line-item:commerce-product:commerce-price:amount"

  1. Add second action: Set the unit price to a specific amount

Hint: Amount- Data selector: "(the variable name from first action)"

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.