1

I have a slightly unusual use case in that I want to allow authenticated users to order multiple products and use the shopping cart but I want to limit anonymous users to purchasing products individually (no changing quantities, no adding multiple products to the cart).

I am using Commerce and Rules on Drupal 7. Because I do not want anonymous users to access the cart, I want to redirect them to the checkout page if they attempt to access the cart (I know this is not the most foolproof method, but it is sufficient for my purposes).

I tried creating a rule triggered on the event Content is viewed with the condition Path has URL alias of cart. However, this rule is not triggered; when I add a Path redirect action and then visit the cart path, I am not redirected. What event should I use in Rules to do the redirect? Or is there some better way to do this?

1 Answer 1

5

These rules can be used to restrict number and quantity of products available by role.

They can be imported in Rules admin.

Restrict to single product:

Basically, before adding to cart, if anonymous, remove existing products from cart. The effect is only the latest product is added to the cart.

{ "rules_single_product_order" : {
    "LABEL" : "Single product order",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : [ "commerce_cart_product_prepare" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }
}

Restrict quantity to 1:

On order presave, if anonymous, loop over the line items and set quantity to 1

{ "rules_restrict_quantity_to_1" : {
    "LABEL" : "Restrict quantity to 1",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : [ "commerce_order_presave" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [ { "data_set" : { "data" : [ "list-item:quantity" ], "value" : "1" } } ]
        }
      }
    ]
  }
}

Anon can still view the cart, but they will be restricted to one product and quantity of 1 - a preferable solution here. You could also show a message about the benefits of registering, if required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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