Magento 2: 10% off on first purchase but only for one productApply “Maximum Qty Discount is Applied to” to whole order instead of order lineCoupon code - Buy one of some products, get one different product free onceAdapting Shopping Cart Price Rules Magento CE 1.7BOGOF not working on magento storespecific category discountMagento 2 - discount depend on Payment Method does not workMagento Shopping Cart Price Rules Wrong CalculationMagento 2: Multiple Cart rules not working at a timeCan't get Buy X get Y Free for a categoryfree shipping applied for all products instead of products in condition

To string or not to string

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

Email Account under attack (really) - anything I can do?

Why Is Death Allowed In the Matrix?

What are these boxed doors outside store fronts in New York?

What defenses are there against being summoned by the Gate spell?

Today is the Center

Languages that we cannot (dis)prove to be Context-Free

How can bays and straits be determined in a procedurally generated map?

Why do I get two different answers for this counting problem?

How to format long polynomial?

Why was the small council so happy for Tyrion to become the Master of Coin?

Why doesn't H₄O²⁺ exist?

Windows 98 hangs after entering password on fresh install

Adding span tags within wp_list_pages list items

Dragon forelimb placement

Minkowski space

Prove that NP is closed under karp reduction?

How do I create uniquely male characters?

Why does Kotter return in Welcome Back Kotter?

A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?

Why, historically, did Gödel think CH was false?

How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?

"You are your self first supporter", a more proper way to say it



Magento 2: 10% off on first purchase but only for one product


Apply “Maximum Qty Discount is Applied to” to whole order instead of order lineCoupon code - Buy one of some products, get one different product free onceAdapting Shopping Cart Price Rules Magento CE 1.7BOGOF not working on magento storespecific category discountMagento 2 - discount depend on Payment Method does not workMagento Shopping Cart Price Rules Wrong CalculationMagento 2: Multiple Cart rules not working at a timeCan't get Buy X get Y Free for a categoryfree shipping applied for all products instead of products in condition






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















We're using Magento CE v2.2.3 and we're selling a single product (with multiple options) which at the moment only has two prices.



I need to set a promotion where a customer can get a discount of 10% of their first purchase but only to one product even if there are multiple products in cart. I also need to exclude gift cards from discounts.



On my first attempt, I have set a rule that applies a discount to entire cart, which does not work as desired:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Percent of product price discount
- Discount Amount 10
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes


My second attempt was in hope that I could set two rules that would apply either one or second to entire cart, but when adding two products with different prices to cart, both rules are applied, which again is not correct:



Rule 1:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Fixed amount discount for whole cart
- Discount Amount 36.5
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes
Apply the rule:
- If ALL of these conditions are TRUE:
- Price in cart is 365.00


Rule 2:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Fixed amount discount for whole cart
- Discount Amount 42.5
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes
Apply the rule:
- If ALL of these conditions are TRUE:
- Price in cart is 425.00


Is it even possible to do the above with default Magento or do we need an extension for that?










share|improve this question






















  • Sir did you solve this problem??? If yes can you please share the code with me?

    – Asad Khan
    2 days ago











  • Nope, sorry didn't solve this one ...

    – Kristjan O.
    2 days ago











  • I can give you the code if you still need it... I just solved it last night

    – Asad Khan
    yesterday











  • Would appreciate it.

    – Kristjan O.
    yesterday

















0















We're using Magento CE v2.2.3 and we're selling a single product (with multiple options) which at the moment only has two prices.



I need to set a promotion where a customer can get a discount of 10% of their first purchase but only to one product even if there are multiple products in cart. I also need to exclude gift cards from discounts.



On my first attempt, I have set a rule that applies a discount to entire cart, which does not work as desired:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Percent of product price discount
- Discount Amount 10
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes


My second attempt was in hope that I could set two rules that would apply either one or second to entire cart, but when adding two products with different prices to cart, both rules are applied, which again is not correct:



Rule 1:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Fixed amount discount for whole cart
- Discount Amount 36.5
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes
Apply the rule:
- If ALL of these conditions are TRUE:
- Price in cart is 365.00


Rule 2:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Fixed amount discount for whole cart
- Discount Amount 42.5
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes
Apply the rule:
- If ALL of these conditions are TRUE:
- Price in cart is 425.00


Is it even possible to do the above with default Magento or do we need an extension for that?










share|improve this question






















  • Sir did you solve this problem??? If yes can you please share the code with me?

    – Asad Khan
    2 days ago











  • Nope, sorry didn't solve this one ...

    – Kristjan O.
    2 days ago











  • I can give you the code if you still need it... I just solved it last night

    – Asad Khan
    yesterday











  • Would appreciate it.

    – Kristjan O.
    yesterday













0












0








0








We're using Magento CE v2.2.3 and we're selling a single product (with multiple options) which at the moment only has two prices.



I need to set a promotion where a customer can get a discount of 10% of their first purchase but only to one product even if there are multiple products in cart. I also need to exclude gift cards from discounts.



On my first attempt, I have set a rule that applies a discount to entire cart, which does not work as desired:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Percent of product price discount
- Discount Amount 10
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes


My second attempt was in hope that I could set two rules that would apply either one or second to entire cart, but when adding two products with different prices to cart, both rules are applied, which again is not correct:



Rule 1:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Fixed amount discount for whole cart
- Discount Amount 36.5
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes
Apply the rule:
- If ALL of these conditions are TRUE:
- Price in cart is 365.00


Rule 2:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Fixed amount discount for whole cart
- Discount Amount 42.5
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes
Apply the rule:
- If ALL of these conditions are TRUE:
- Price in cart is 425.00


Is it even possible to do the above with default Magento or do we need an extension for that?










share|improve this question














We're using Magento CE v2.2.3 and we're selling a single product (with multiple options) which at the moment only has two prices.



I need to set a promotion where a customer can get a discount of 10% of their first purchase but only to one product even if there are multiple products in cart. I also need to exclude gift cards from discounts.



On my first attempt, I have set a rule that applies a discount to entire cart, which does not work as desired:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Percent of product price discount
- Discount Amount 10
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes


My second attempt was in hope that I could set two rules that would apply either one or second to entire cart, but when adding two products with different prices to cart, both rules are applied, which again is not correct:



Rule 1:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Fixed amount discount for whole cart
- Discount Amount 36.5
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes
Apply the rule:
- If ALL of these conditions are TRUE:
- Price in cart is 365.00


Rule 2:



Coupon: No Coupon
Uses per Customer: 1
Conditions:
- If ALL of these conditions are TRUE:
- If an item is NOT FOUND in the cart with ANY of these conditions true:
- SKU IS Gift Card
Actions:
- Apply Fixed amount discount for whole cart
- Discount Amount 42.5
- Maximum Qty Discount is Applied To 1
- Discount Qty Step 0
- Apply to Shipping Amount No
- Discard subsequent rules Yes
Apply the rule:
- If ALL of these conditions are TRUE:
- Price in cart is 425.00


Is it even possible to do the above with default Magento or do we need an extension for that?







magento2 shopping-cart-price-rules






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 12 '18 at 10:32









Kristjan O.Kristjan O.

1208




1208












  • Sir did you solve this problem??? If yes can you please share the code with me?

    – Asad Khan
    2 days ago











  • Nope, sorry didn't solve this one ...

    – Kristjan O.
    2 days ago











  • I can give you the code if you still need it... I just solved it last night

    – Asad Khan
    yesterday











  • Would appreciate it.

    – Kristjan O.
    yesterday

















  • Sir did you solve this problem??? If yes can you please share the code with me?

    – Asad Khan
    2 days ago











  • Nope, sorry didn't solve this one ...

    – Kristjan O.
    2 days ago











  • I can give you the code if you still need it... I just solved it last night

    – Asad Khan
    yesterday











  • Would appreciate it.

    – Kristjan O.
    yesterday
















Sir did you solve this problem??? If yes can you please share the code with me?

– Asad Khan
2 days ago





Sir did you solve this problem??? If yes can you please share the code with me?

– Asad Khan
2 days ago













Nope, sorry didn't solve this one ...

– Kristjan O.
2 days ago





Nope, sorry didn't solve this one ...

– Kristjan O.
2 days ago













I can give you the code if you still need it... I just solved it last night

– Asad Khan
yesterday





I can give you the code if you still need it... I just solved it last night

– Asad Khan
yesterday













Would appreciate it.

– Kristjan O.
yesterday





Would appreciate it.

– Kristjan O.
yesterday










1 Answer
1






active

oldest

votes


















0














So I fix it for my specific data you can fix it for yours



public function setCoupon()

// // $this->_state->setAreaCode('adminhtml');
// // $this->_state->setAreaCode('frontend');


$coupon['name'] = 'Sheikh The Power';
$coupon['desc'] = 'Discount for vip signup coupon.';
$coupon['start'] = date('Y-m-d');
$coupon['end'] = '';
$coupon['max_redemptions'] = 1;
$coupon['discount_type'] ='by_fixed';
$coupon['discount_amount'] = 15;
$coupon['flag_is_free_shipping'] = 'no';
$coupon['redemptions'] = 1;
// $coupon['produtIds'] = array(1 ,2,3);
$coupon['produtIds'] = 1;
$coupon['code'] ='Code-'.uniqid(); //this code will normally be autogenerated but i am hard coding for testing purposes

$this->_rule->setName($coupon['name'])
->setDescription($coupon['desc'])
->setFromDate($coupon['start'])
->setToDate($coupon['end'])
->setUsesPerCustomer($coupon['max_redemptions'])
->setCustomerGroupIds(array('0','1','2','3',))
->setIsActive(1)
->setSimpleAction($coupon['discount_type'])
->setDiscountAmount($coupon['discount_amount'])
->setDiscountQty(1)
->setApplyToShipping($coupon['flag_is_free_shipping'])
->setTimesUsed($coupon['redemptions'])
->setWebsiteIds(array('1'))
->setCouponType(2)
// ->setProductIds($this->getSKUU())
->setProductIds(NULL)
->setCouponCode($coupon['code'])
->setUsesPerCoupon(NULL);

$conditions = array();
$conditions["1"] = array
(
"type" => "MagentoSalesRuleModelRuleConditionCombine",
"aggregator" => "all",
"attribute" => null,
"operator" => null,
"value" => 1,
"is_value_processed" => null,
);
$conditions["1--1"] = array
(
"type" => "MagentoSalesRuleModelRuleConditionProductFound",
"attribute" => null,
"operator" => null,
"value" => 1,
"is_value_processed" => null,
"aggregator" => "all",
);
$conditions["1--1--1"] = array
(
"type" => "MagentoSalesRuleModelRuleConditionProduct",
"attribute" => "sku",
"operator" => "==",
// "operator" => "()",
// "value" => $couponData['general']['product_id']
"value" => $this->getSKUU(),
);
$conditions["1--1--1-1"] = array
(
"type" => "MagentoSalesRuleModelRuleConditionProduct",
// "attribute" => "quote_item_row_total",
"attribute" => "quote_item_qty",
"operator" => "==",
"value" => 1
);

$actions = array(
"1" => array(
"type" => "MagentoSalesRuleModelRuleConditionProduct",
"aggregator" => "all",
"value" => "1",
"new_child" => false
),
"1--1" => array(
"type" => "MagentoSalesRuleModelRuleConditionProduct",
"attribute" => "sku",
'operator' => '==',
'value' => $this->getSKUU()
)
);

$this->_rule->setData('conditions', $conditions);
$this->_rule->setData("actions",$actions);

$validateResult = $this->_rule->validateData(new MagentoFrameworkDataObject($this->_rule->getData()));
if ($validateResult !== true)
foreach ($validateResult as $errorMessage)
echo $errorMessage;

return;


try
$this->_rule->loadPost($this->_rule->getData());
$this->_rule->save();

// $ruleJob = $obj->get('MagentoCatalogRuleModelRuleJob');
// $ruleJob->applyAll();
// echo "rule created";
catch (Exception $e)
echo $e->getMessage();


$this->_rule->save();



where my di is



public function __construct(

MagentoSalesRuleModelRule $rule,
MagentoFrameworkAppState $state,
)
$this->_state = $state;
$this->_rule = $rule;



I wish next time this code will help you






share|improve this answer























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f249710%2fmagento-2-10-off-on-first-purchase-but-only-for-one-product%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    So I fix it for my specific data you can fix it for yours



    public function setCoupon()

    // // $this->_state->setAreaCode('adminhtml');
    // // $this->_state->setAreaCode('frontend');


    $coupon['name'] = 'Sheikh The Power';
    $coupon['desc'] = 'Discount for vip signup coupon.';
    $coupon['start'] = date('Y-m-d');
    $coupon['end'] = '';
    $coupon['max_redemptions'] = 1;
    $coupon['discount_type'] ='by_fixed';
    $coupon['discount_amount'] = 15;
    $coupon['flag_is_free_shipping'] = 'no';
    $coupon['redemptions'] = 1;
    // $coupon['produtIds'] = array(1 ,2,3);
    $coupon['produtIds'] = 1;
    $coupon['code'] ='Code-'.uniqid(); //this code will normally be autogenerated but i am hard coding for testing purposes

    $this->_rule->setName($coupon['name'])
    ->setDescription($coupon['desc'])
    ->setFromDate($coupon['start'])
    ->setToDate($coupon['end'])
    ->setUsesPerCustomer($coupon['max_redemptions'])
    ->setCustomerGroupIds(array('0','1','2','3',))
    ->setIsActive(1)
    ->setSimpleAction($coupon['discount_type'])
    ->setDiscountAmount($coupon['discount_amount'])
    ->setDiscountQty(1)
    ->setApplyToShipping($coupon['flag_is_free_shipping'])
    ->setTimesUsed($coupon['redemptions'])
    ->setWebsiteIds(array('1'))
    ->setCouponType(2)
    // ->setProductIds($this->getSKUU())
    ->setProductIds(NULL)
    ->setCouponCode($coupon['code'])
    ->setUsesPerCoupon(NULL);

    $conditions = array();
    $conditions["1"] = array
    (
    "type" => "MagentoSalesRuleModelRuleConditionCombine",
    "aggregator" => "all",
    "attribute" => null,
    "operator" => null,
    "value" => 1,
    "is_value_processed" => null,
    );
    $conditions["1--1"] = array
    (
    "type" => "MagentoSalesRuleModelRuleConditionProductFound",
    "attribute" => null,
    "operator" => null,
    "value" => 1,
    "is_value_processed" => null,
    "aggregator" => "all",
    );
    $conditions["1--1--1"] = array
    (
    "type" => "MagentoSalesRuleModelRuleConditionProduct",
    "attribute" => "sku",
    "operator" => "==",
    // "operator" => "()",
    // "value" => $couponData['general']['product_id']
    "value" => $this->getSKUU(),
    );
    $conditions["1--1--1-1"] = array
    (
    "type" => "MagentoSalesRuleModelRuleConditionProduct",
    // "attribute" => "quote_item_row_total",
    "attribute" => "quote_item_qty",
    "operator" => "==",
    "value" => 1
    );

    $actions = array(
    "1" => array(
    "type" => "MagentoSalesRuleModelRuleConditionProduct",
    "aggregator" => "all",
    "value" => "1",
    "new_child" => false
    ),
    "1--1" => array(
    "type" => "MagentoSalesRuleModelRuleConditionProduct",
    "attribute" => "sku",
    'operator' => '==',
    'value' => $this->getSKUU()
    )
    );

    $this->_rule->setData('conditions', $conditions);
    $this->_rule->setData("actions",$actions);

    $validateResult = $this->_rule->validateData(new MagentoFrameworkDataObject($this->_rule->getData()));
    if ($validateResult !== true)
    foreach ($validateResult as $errorMessage)
    echo $errorMessage;

    return;


    try
    $this->_rule->loadPost($this->_rule->getData());
    $this->_rule->save();

    // $ruleJob = $obj->get('MagentoCatalogRuleModelRuleJob');
    // $ruleJob->applyAll();
    // echo "rule created";
    catch (Exception $e)
    echo $e->getMessage();


    $this->_rule->save();



    where my di is



    public function __construct(

    MagentoSalesRuleModelRule $rule,
    MagentoFrameworkAppState $state,
    )
    $this->_state = $state;
    $this->_rule = $rule;



    I wish next time this code will help you






    share|improve this answer



























      0














      So I fix it for my specific data you can fix it for yours



      public function setCoupon()

      // // $this->_state->setAreaCode('adminhtml');
      // // $this->_state->setAreaCode('frontend');


      $coupon['name'] = 'Sheikh The Power';
      $coupon['desc'] = 'Discount for vip signup coupon.';
      $coupon['start'] = date('Y-m-d');
      $coupon['end'] = '';
      $coupon['max_redemptions'] = 1;
      $coupon['discount_type'] ='by_fixed';
      $coupon['discount_amount'] = 15;
      $coupon['flag_is_free_shipping'] = 'no';
      $coupon['redemptions'] = 1;
      // $coupon['produtIds'] = array(1 ,2,3);
      $coupon['produtIds'] = 1;
      $coupon['code'] ='Code-'.uniqid(); //this code will normally be autogenerated but i am hard coding for testing purposes

      $this->_rule->setName($coupon['name'])
      ->setDescription($coupon['desc'])
      ->setFromDate($coupon['start'])
      ->setToDate($coupon['end'])
      ->setUsesPerCustomer($coupon['max_redemptions'])
      ->setCustomerGroupIds(array('0','1','2','3',))
      ->setIsActive(1)
      ->setSimpleAction($coupon['discount_type'])
      ->setDiscountAmount($coupon['discount_amount'])
      ->setDiscountQty(1)
      ->setApplyToShipping($coupon['flag_is_free_shipping'])
      ->setTimesUsed($coupon['redemptions'])
      ->setWebsiteIds(array('1'))
      ->setCouponType(2)
      // ->setProductIds($this->getSKUU())
      ->setProductIds(NULL)
      ->setCouponCode($coupon['code'])
      ->setUsesPerCoupon(NULL);

      $conditions = array();
      $conditions["1"] = array
      (
      "type" => "MagentoSalesRuleModelRuleConditionCombine",
      "aggregator" => "all",
      "attribute" => null,
      "operator" => null,
      "value" => 1,
      "is_value_processed" => null,
      );
      $conditions["1--1"] = array
      (
      "type" => "MagentoSalesRuleModelRuleConditionProductFound",
      "attribute" => null,
      "operator" => null,
      "value" => 1,
      "is_value_processed" => null,
      "aggregator" => "all",
      );
      $conditions["1--1--1"] = array
      (
      "type" => "MagentoSalesRuleModelRuleConditionProduct",
      "attribute" => "sku",
      "operator" => "==",
      // "operator" => "()",
      // "value" => $couponData['general']['product_id']
      "value" => $this->getSKUU(),
      );
      $conditions["1--1--1-1"] = array
      (
      "type" => "MagentoSalesRuleModelRuleConditionProduct",
      // "attribute" => "quote_item_row_total",
      "attribute" => "quote_item_qty",
      "operator" => "==",
      "value" => 1
      );

      $actions = array(
      "1" => array(
      "type" => "MagentoSalesRuleModelRuleConditionProduct",
      "aggregator" => "all",
      "value" => "1",
      "new_child" => false
      ),
      "1--1" => array(
      "type" => "MagentoSalesRuleModelRuleConditionProduct",
      "attribute" => "sku",
      'operator' => '==',
      'value' => $this->getSKUU()
      )
      );

      $this->_rule->setData('conditions', $conditions);
      $this->_rule->setData("actions",$actions);

      $validateResult = $this->_rule->validateData(new MagentoFrameworkDataObject($this->_rule->getData()));
      if ($validateResult !== true)
      foreach ($validateResult as $errorMessage)
      echo $errorMessage;

      return;


      try
      $this->_rule->loadPost($this->_rule->getData());
      $this->_rule->save();

      // $ruleJob = $obj->get('MagentoCatalogRuleModelRuleJob');
      // $ruleJob->applyAll();
      // echo "rule created";
      catch (Exception $e)
      echo $e->getMessage();


      $this->_rule->save();



      where my di is



      public function __construct(

      MagentoSalesRuleModelRule $rule,
      MagentoFrameworkAppState $state,
      )
      $this->_state = $state;
      $this->_rule = $rule;



      I wish next time this code will help you






      share|improve this answer

























        0












        0








        0







        So I fix it for my specific data you can fix it for yours



        public function setCoupon()

        // // $this->_state->setAreaCode('adminhtml');
        // // $this->_state->setAreaCode('frontend');


        $coupon['name'] = 'Sheikh The Power';
        $coupon['desc'] = 'Discount for vip signup coupon.';
        $coupon['start'] = date('Y-m-d');
        $coupon['end'] = '';
        $coupon['max_redemptions'] = 1;
        $coupon['discount_type'] ='by_fixed';
        $coupon['discount_amount'] = 15;
        $coupon['flag_is_free_shipping'] = 'no';
        $coupon['redemptions'] = 1;
        // $coupon['produtIds'] = array(1 ,2,3);
        $coupon['produtIds'] = 1;
        $coupon['code'] ='Code-'.uniqid(); //this code will normally be autogenerated but i am hard coding for testing purposes

        $this->_rule->setName($coupon['name'])
        ->setDescription($coupon['desc'])
        ->setFromDate($coupon['start'])
        ->setToDate($coupon['end'])
        ->setUsesPerCustomer($coupon['max_redemptions'])
        ->setCustomerGroupIds(array('0','1','2','3',))
        ->setIsActive(1)
        ->setSimpleAction($coupon['discount_type'])
        ->setDiscountAmount($coupon['discount_amount'])
        ->setDiscountQty(1)
        ->setApplyToShipping($coupon['flag_is_free_shipping'])
        ->setTimesUsed($coupon['redemptions'])
        ->setWebsiteIds(array('1'))
        ->setCouponType(2)
        // ->setProductIds($this->getSKUU())
        ->setProductIds(NULL)
        ->setCouponCode($coupon['code'])
        ->setUsesPerCoupon(NULL);

        $conditions = array();
        $conditions["1"] = array
        (
        "type" => "MagentoSalesRuleModelRuleConditionCombine",
        "aggregator" => "all",
        "attribute" => null,
        "operator" => null,
        "value" => 1,
        "is_value_processed" => null,
        );
        $conditions["1--1"] = array
        (
        "type" => "MagentoSalesRuleModelRuleConditionProductFound",
        "attribute" => null,
        "operator" => null,
        "value" => 1,
        "is_value_processed" => null,
        "aggregator" => "all",
        );
        $conditions["1--1--1"] = array
        (
        "type" => "MagentoSalesRuleModelRuleConditionProduct",
        "attribute" => "sku",
        "operator" => "==",
        // "operator" => "()",
        // "value" => $couponData['general']['product_id']
        "value" => $this->getSKUU(),
        );
        $conditions["1--1--1-1"] = array
        (
        "type" => "MagentoSalesRuleModelRuleConditionProduct",
        // "attribute" => "quote_item_row_total",
        "attribute" => "quote_item_qty",
        "operator" => "==",
        "value" => 1
        );

        $actions = array(
        "1" => array(
        "type" => "MagentoSalesRuleModelRuleConditionProduct",
        "aggregator" => "all",
        "value" => "1",
        "new_child" => false
        ),
        "1--1" => array(
        "type" => "MagentoSalesRuleModelRuleConditionProduct",
        "attribute" => "sku",
        'operator' => '==',
        'value' => $this->getSKUU()
        )
        );

        $this->_rule->setData('conditions', $conditions);
        $this->_rule->setData("actions",$actions);

        $validateResult = $this->_rule->validateData(new MagentoFrameworkDataObject($this->_rule->getData()));
        if ($validateResult !== true)
        foreach ($validateResult as $errorMessage)
        echo $errorMessage;

        return;


        try
        $this->_rule->loadPost($this->_rule->getData());
        $this->_rule->save();

        // $ruleJob = $obj->get('MagentoCatalogRuleModelRuleJob');
        // $ruleJob->applyAll();
        // echo "rule created";
        catch (Exception $e)
        echo $e->getMessage();


        $this->_rule->save();



        where my di is



        public function __construct(

        MagentoSalesRuleModelRule $rule,
        MagentoFrameworkAppState $state,
        )
        $this->_state = $state;
        $this->_rule = $rule;



        I wish next time this code will help you






        share|improve this answer













        So I fix it for my specific data you can fix it for yours



        public function setCoupon()

        // // $this->_state->setAreaCode('adminhtml');
        // // $this->_state->setAreaCode('frontend');


        $coupon['name'] = 'Sheikh The Power';
        $coupon['desc'] = 'Discount for vip signup coupon.';
        $coupon['start'] = date('Y-m-d');
        $coupon['end'] = '';
        $coupon['max_redemptions'] = 1;
        $coupon['discount_type'] ='by_fixed';
        $coupon['discount_amount'] = 15;
        $coupon['flag_is_free_shipping'] = 'no';
        $coupon['redemptions'] = 1;
        // $coupon['produtIds'] = array(1 ,2,3);
        $coupon['produtIds'] = 1;
        $coupon['code'] ='Code-'.uniqid(); //this code will normally be autogenerated but i am hard coding for testing purposes

        $this->_rule->setName($coupon['name'])
        ->setDescription($coupon['desc'])
        ->setFromDate($coupon['start'])
        ->setToDate($coupon['end'])
        ->setUsesPerCustomer($coupon['max_redemptions'])
        ->setCustomerGroupIds(array('0','1','2','3',))
        ->setIsActive(1)
        ->setSimpleAction($coupon['discount_type'])
        ->setDiscountAmount($coupon['discount_amount'])
        ->setDiscountQty(1)
        ->setApplyToShipping($coupon['flag_is_free_shipping'])
        ->setTimesUsed($coupon['redemptions'])
        ->setWebsiteIds(array('1'))
        ->setCouponType(2)
        // ->setProductIds($this->getSKUU())
        ->setProductIds(NULL)
        ->setCouponCode($coupon['code'])
        ->setUsesPerCoupon(NULL);

        $conditions = array();
        $conditions["1"] = array
        (
        "type" => "MagentoSalesRuleModelRuleConditionCombine",
        "aggregator" => "all",
        "attribute" => null,
        "operator" => null,
        "value" => 1,
        "is_value_processed" => null,
        );
        $conditions["1--1"] = array
        (
        "type" => "MagentoSalesRuleModelRuleConditionProductFound",
        "attribute" => null,
        "operator" => null,
        "value" => 1,
        "is_value_processed" => null,
        "aggregator" => "all",
        );
        $conditions["1--1--1"] = array
        (
        "type" => "MagentoSalesRuleModelRuleConditionProduct",
        "attribute" => "sku",
        "operator" => "==",
        // "operator" => "()",
        // "value" => $couponData['general']['product_id']
        "value" => $this->getSKUU(),
        );
        $conditions["1--1--1-1"] = array
        (
        "type" => "MagentoSalesRuleModelRuleConditionProduct",
        // "attribute" => "quote_item_row_total",
        "attribute" => "quote_item_qty",
        "operator" => "==",
        "value" => 1
        );

        $actions = array(
        "1" => array(
        "type" => "MagentoSalesRuleModelRuleConditionProduct",
        "aggregator" => "all",
        "value" => "1",
        "new_child" => false
        ),
        "1--1" => array(
        "type" => "MagentoSalesRuleModelRuleConditionProduct",
        "attribute" => "sku",
        'operator' => '==',
        'value' => $this->getSKUU()
        )
        );

        $this->_rule->setData('conditions', $conditions);
        $this->_rule->setData("actions",$actions);

        $validateResult = $this->_rule->validateData(new MagentoFrameworkDataObject($this->_rule->getData()));
        if ($validateResult !== true)
        foreach ($validateResult as $errorMessage)
        echo $errorMessage;

        return;


        try
        $this->_rule->loadPost($this->_rule->getData());
        $this->_rule->save();

        // $ruleJob = $obj->get('MagentoCatalogRuleModelRuleJob');
        // $ruleJob->applyAll();
        // echo "rule created";
        catch (Exception $e)
        echo $e->getMessage();


        $this->_rule->save();



        where my di is



        public function __construct(

        MagentoSalesRuleModelRule $rule,
        MagentoFrameworkAppState $state,
        )
        $this->_state = $state;
        $this->_rule = $rule;



        I wish next time this code will help you







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        Asad KhanAsad Khan

        1698




        1698



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f249710%2fmagento-2-10-off-on-first-purchase-but-only-for-one-product%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form