2

How can I know if a product is configurable (color, size, shape) or can be added directly to the cart (it is unique without configuration possible) programmatically?

For example: I have a shirt without attributes, then my method canBeAddedDirectly($product) should return true.

However, another shirt has 3 colors then, my method canBeAddedDirectly($product) should return false, because I need to choose a color (or other attributes) before.

1
  • can you brief given your questions? what your expecting? Jun 26, 2017 at 18:03

4 Answers 4

7

Check if it's configurable and if it doesn't have any custom options (since simple products can have custom options those can require modification as well). Something like this might get you started:

/**
 * @param \Magento\Catalog\Api\Data\ProductInterface $product
 * @return bool
 */
public function canBeAddedDirectly(\Magento\Catalog\Api\Data\ProductInterface $product) {
    return $product->getTypeId() === 'configurable' && !empty($product->getOptions());
}
6

see what $product->getTypeId() returns.
if it returns configurable it is configurable.

2

Magento\Catalog\Api\Data\ProductInterface inject in your file and check

check condition $product->getTypeId() == 'configurable'

1

In Magento 2 any simple product can become a configurable product. It is considered a configurable product if it has been configured with a set of child products. It will then show as 'Configurable' in your admin products list.

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.