Magento 2 - Generate customization image in product page and add it to product options in cart












7














I need to let users create a customization image in product page and than attach that image to product when users add product in cart.



Create a custom product option type seems to be very tricky.



I think that the simpliest solution is to customize product template adding the image builder and then add generated image in product options through an observer that take the image from request and put it in product options.



I'm new in magento, it could be the right solution?
How can I implement?
I'm able to create a module.










share|improve this question






















  • Did you find any solution ?
    – Amit Singh
    Nov 26 '16 at 5:54
















7














I need to let users create a customization image in product page and than attach that image to product when users add product in cart.



Create a custom product option type seems to be very tricky.



I think that the simpliest solution is to customize product template adding the image builder and then add generated image in product options through an observer that take the image from request and put it in product options.



I'm new in magento, it could be the right solution?
How can I implement?
I'm able to create a module.










share|improve this question






















  • Did you find any solution ?
    – Amit Singh
    Nov 26 '16 at 5:54














7












7








7


2





I need to let users create a customization image in product page and than attach that image to product when users add product in cart.



Create a custom product option type seems to be very tricky.



I think that the simpliest solution is to customize product template adding the image builder and then add generated image in product options through an observer that take the image from request and put it in product options.



I'm new in magento, it could be the right solution?
How can I implement?
I'm able to create a module.










share|improve this question













I need to let users create a customization image in product page and than attach that image to product when users add product in cart.



Create a custom product option type seems to be very tricky.



I think that the simpliest solution is to customize product template adding the image builder and then add generated image in product options through an observer that take the image from request and put it in product options.



I'm new in magento, it could be the right solution?
How can I implement?
I'm able to create a module.







magento2 cart custom-options addtocart attachment






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 1 '16 at 9:59









Alessandro PaternoAlessandro Paterno

463




463












  • Did you find any solution ?
    – Amit Singh
    Nov 26 '16 at 5:54


















  • Did you find any solution ?
    – Amit Singh
    Nov 26 '16 at 5:54
















Did you find any solution ?
– Amit Singh
Nov 26 '16 at 5:54




Did you find any solution ?
– Amit Singh
Nov 26 '16 at 5:54










2 Answers
2






active

oldest

votes


















1














You can use the event checkout_cart_product_add_after to modify the product image information.



Firstly in your product detail page you need to add a hidden field in the add to cart form something like:



<input type="hidden" name="[option][front_designurl]" id="front_designurl"/>


And using javascript add the value to the field for the generated image url by the user, this value gets saved in the info_buyRequest of the quote item options



We have to create the file app/code/Foo/CustomImage/etc/events.xml to attach observers to the events:





  1. checkout_cart_product_add_after: Event is fired on Add to Cart


  2. checkout_cart_product_update_after: Event is fired on Cart Update (For add to cart from cart edit page)




<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_product_add_after">
<observer name="foo_customimage_observer_set_price_for_item_add" instance="FooCustomImageModelObserverSetImageForItem"/>
</event>
<event name="checkout_cart_product_update_after">
<observer name="foo_customimage_observer_set_price_for_item_update" instance="FooCustomImageModelObserverSetImageForItem"/>
</event>
</config>


Now for the observer logic we create a file at app/code/Foo/CustomImage/Model/Observer/SetImageForItem.php



<?php

namespace FooCustomImageModelObserver;

use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoQuoteModelQuoteProductOptionFactory;
use MagentoQuoteApiDataProductOptionExtensionFactory;
use MagentoCatalogModelCustomOptionsCustomOptionFactory;

class SetImageForItem implements ObserverInterface
{
/** @var MagentoQuoteModelQuoteProductOptionFactory */
protected $productOptionFactory;

/** @var MagentoQuoteApiDataProductOptionExtensionFactory */
protected $extensionFactory;

/** @var CustomOptionFactory */
protected $customOptionFactory;

/**
* @param ProductOptionFactory $productOptionFactory
* @param ProductOptionExtensionFactory $extensionFactory
* @param CustomOptionFactory $customOptionFactory
*/
public function __construct(
ProductOptionFactory $productOptionFactory,
ProductOptionExtensionFactory $extensionFactory
CustomOptionFactory $customOptionFactory
) {
$this->productOptionFactory = $productOptionFactory;
$this->extensionFactory = $extensionFactory;
$this->customOptionFactory = $customOptionFactory;
}

public function execute(Observer $observer)
{
/** @var $item MagentoQuoteModelQuoteItem */
$item = $observer->getEvent()->getQuoteItem();//Gets the Quote Item Instance
$request = $item->getBuyRequest(); // Gets the posted data sent to "Add to cart" controller action
$this->processOptions($item);
return $this;
}//end execute()


/**
* @inheritDoc
*/
public function processOptions(CartItemInterface $cartItem)
{
$options = $this->getOptions($cartItem);
if (!empty($options) && is_array($options)) {
$this->updateOptionsValues($options);
$productOption = $cartItem->getProductOption()
? $cartItem->getProductOption()
: $this->productOptionFactory->create();

/** @var MagentoQuoteApiDataProductOptionExtensionInterface $extensibleAttribute */
$extensibleAttribute = $productOption->getExtensionAttributes()
? $productOption->getExtensionAttributes()
: $this->extensionFactory->create();

$extensibleAttribute->setCustomOptions($options);
$productOption->setExtensionAttributes($extensibleAttribute);
$cartItem->setProductOption($productOption);
}
}

/**
* Receive custom option from buy request
*
* @param CartItemInterface $cartItem
* @return array
*/
protected function getOptions(CartItemInterface $cartItem)
{
$buyRequest = !empty($cartItem->getOptionByCode('info_buyRequest'))
? unserialize($cartItem->getOptionByCode('info_buyRequest')->getValue())
: null;
return is_array($buyRequest) && isset($buyRequest['options'])
? $buyRequest['options']
: ;
}

/**
* Update options values
*
* @param array $options
* @return null
*/
protected function updateOptionsValues(array &$options)
{
foreach ($options as $optionId => &$optionValue) {
/** @var MagentoCatalogModelCustomOptionsCustomOption $option */
$option = $this->customOptionFactory->create();
$option->setOptionId($optionId);
if (is_array($optionValue)) {
$optionValue = implode(',', $optionValue);
}
$option->setOptionValue($optionValue);
$optionValue = $option;
}
}
}


I have not tried out the code, but should help you add new data to your product option.






share|improve this answer





















  • Where to set custom option in above code?
    – Bhupendra Jadeja
    Jul 13 '16 at 12:06



















0














I was having a similar problem and solved the part of showing another image like this. beware: It might have bugs, if the aspect ratio / size of the actual product image from backend differs from the customized one.



di.xml



<type name="MagentoCheckoutBlockCartItemRenderer">
<plugin sortOrder="1" name="foo" type="FooBarPluginBlockCartItemRendererPlugin"/>
</type>


RendererPlugin.php



<?php

namespace FooBarPluginBlockCartItem;

class RendererPlugin
{
/**
* Override cart image, if designer product
*
* @param MagentoCheckoutBlockCartItemRenderer $subject
* @param MagentoCatalogBlockProductImage $result
* @see MagentoCheckoutBlockCartItemRenderer::getImage
*/
public function afterGetImage(MagentoCheckoutBlockCartItemRenderer $subject, $result)
{
$item = $subject->getItem();
$optionId = $this->options->getDesignerCodeOptionId($subject->getProduct());
$designCode = $item->getOptionByCode('option_' . $optionId)->getValue();
$design = $this->design->getByDesignCode($designCode);

$previewImageUrl = $design->getData('preview_image_url');

$result->setImageUrl($previewImageUrl);

return $result; // recreate, to calculate aspect ratio an -- possible BUG: does not recalculate aspect ratio :-(

}
}





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%2f117863%2fmagento-2-generate-customization-image-in-product-page-and-add-it-to-product-o%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You can use the event checkout_cart_product_add_after to modify the product image information.



    Firstly in your product detail page you need to add a hidden field in the add to cart form something like:



    <input type="hidden" name="[option][front_designurl]" id="front_designurl"/>


    And using javascript add the value to the field for the generated image url by the user, this value gets saved in the info_buyRequest of the quote item options



    We have to create the file app/code/Foo/CustomImage/etc/events.xml to attach observers to the events:





    1. checkout_cart_product_add_after: Event is fired on Add to Cart


    2. checkout_cart_product_update_after: Event is fired on Cart Update (For add to cart from cart edit page)




    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
    <observer name="foo_customimage_observer_set_price_for_item_add" instance="FooCustomImageModelObserverSetImageForItem"/>
    </event>
    <event name="checkout_cart_product_update_after">
    <observer name="foo_customimage_observer_set_price_for_item_update" instance="FooCustomImageModelObserverSetImageForItem"/>
    </event>
    </config>


    Now for the observer logic we create a file at app/code/Foo/CustomImage/Model/Observer/SetImageForItem.php



    <?php

    namespace FooCustomImageModelObserver;

    use MagentoFrameworkEventObserver;
    use MagentoFrameworkEventObserverInterface;
    use MagentoQuoteModelQuoteProductOptionFactory;
    use MagentoQuoteApiDataProductOptionExtensionFactory;
    use MagentoCatalogModelCustomOptionsCustomOptionFactory;

    class SetImageForItem implements ObserverInterface
    {
    /** @var MagentoQuoteModelQuoteProductOptionFactory */
    protected $productOptionFactory;

    /** @var MagentoQuoteApiDataProductOptionExtensionFactory */
    protected $extensionFactory;

    /** @var CustomOptionFactory */
    protected $customOptionFactory;

    /**
    * @param ProductOptionFactory $productOptionFactory
    * @param ProductOptionExtensionFactory $extensionFactory
    * @param CustomOptionFactory $customOptionFactory
    */
    public function __construct(
    ProductOptionFactory $productOptionFactory,
    ProductOptionExtensionFactory $extensionFactory
    CustomOptionFactory $customOptionFactory
    ) {
    $this->productOptionFactory = $productOptionFactory;
    $this->extensionFactory = $extensionFactory;
    $this->customOptionFactory = $customOptionFactory;
    }

    public function execute(Observer $observer)
    {
    /** @var $item MagentoQuoteModelQuoteItem */
    $item = $observer->getEvent()->getQuoteItem();//Gets the Quote Item Instance
    $request = $item->getBuyRequest(); // Gets the posted data sent to "Add to cart" controller action
    $this->processOptions($item);
    return $this;
    }//end execute()


    /**
    * @inheritDoc
    */
    public function processOptions(CartItemInterface $cartItem)
    {
    $options = $this->getOptions($cartItem);
    if (!empty($options) && is_array($options)) {
    $this->updateOptionsValues($options);
    $productOption = $cartItem->getProductOption()
    ? $cartItem->getProductOption()
    : $this->productOptionFactory->create();

    /** @var MagentoQuoteApiDataProductOptionExtensionInterface $extensibleAttribute */
    $extensibleAttribute = $productOption->getExtensionAttributes()
    ? $productOption->getExtensionAttributes()
    : $this->extensionFactory->create();

    $extensibleAttribute->setCustomOptions($options);
    $productOption->setExtensionAttributes($extensibleAttribute);
    $cartItem->setProductOption($productOption);
    }
    }

    /**
    * Receive custom option from buy request
    *
    * @param CartItemInterface $cartItem
    * @return array
    */
    protected function getOptions(CartItemInterface $cartItem)
    {
    $buyRequest = !empty($cartItem->getOptionByCode('info_buyRequest'))
    ? unserialize($cartItem->getOptionByCode('info_buyRequest')->getValue())
    : null;
    return is_array($buyRequest) && isset($buyRequest['options'])
    ? $buyRequest['options']
    : ;
    }

    /**
    * Update options values
    *
    * @param array $options
    * @return null
    */
    protected function updateOptionsValues(array &$options)
    {
    foreach ($options as $optionId => &$optionValue) {
    /** @var MagentoCatalogModelCustomOptionsCustomOption $option */
    $option = $this->customOptionFactory->create();
    $option->setOptionId($optionId);
    if (is_array($optionValue)) {
    $optionValue = implode(',', $optionValue);
    }
    $option->setOptionValue($optionValue);
    $optionValue = $option;
    }
    }
    }


    I have not tried out the code, but should help you add new data to your product option.






    share|improve this answer





















    • Where to set custom option in above code?
      – Bhupendra Jadeja
      Jul 13 '16 at 12:06
















    1














    You can use the event checkout_cart_product_add_after to modify the product image information.



    Firstly in your product detail page you need to add a hidden field in the add to cart form something like:



    <input type="hidden" name="[option][front_designurl]" id="front_designurl"/>


    And using javascript add the value to the field for the generated image url by the user, this value gets saved in the info_buyRequest of the quote item options



    We have to create the file app/code/Foo/CustomImage/etc/events.xml to attach observers to the events:





    1. checkout_cart_product_add_after: Event is fired on Add to Cart


    2. checkout_cart_product_update_after: Event is fired on Cart Update (For add to cart from cart edit page)




    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
    <observer name="foo_customimage_observer_set_price_for_item_add" instance="FooCustomImageModelObserverSetImageForItem"/>
    </event>
    <event name="checkout_cart_product_update_after">
    <observer name="foo_customimage_observer_set_price_for_item_update" instance="FooCustomImageModelObserverSetImageForItem"/>
    </event>
    </config>


    Now for the observer logic we create a file at app/code/Foo/CustomImage/Model/Observer/SetImageForItem.php



    <?php

    namespace FooCustomImageModelObserver;

    use MagentoFrameworkEventObserver;
    use MagentoFrameworkEventObserverInterface;
    use MagentoQuoteModelQuoteProductOptionFactory;
    use MagentoQuoteApiDataProductOptionExtensionFactory;
    use MagentoCatalogModelCustomOptionsCustomOptionFactory;

    class SetImageForItem implements ObserverInterface
    {
    /** @var MagentoQuoteModelQuoteProductOptionFactory */
    protected $productOptionFactory;

    /** @var MagentoQuoteApiDataProductOptionExtensionFactory */
    protected $extensionFactory;

    /** @var CustomOptionFactory */
    protected $customOptionFactory;

    /**
    * @param ProductOptionFactory $productOptionFactory
    * @param ProductOptionExtensionFactory $extensionFactory
    * @param CustomOptionFactory $customOptionFactory
    */
    public function __construct(
    ProductOptionFactory $productOptionFactory,
    ProductOptionExtensionFactory $extensionFactory
    CustomOptionFactory $customOptionFactory
    ) {
    $this->productOptionFactory = $productOptionFactory;
    $this->extensionFactory = $extensionFactory;
    $this->customOptionFactory = $customOptionFactory;
    }

    public function execute(Observer $observer)
    {
    /** @var $item MagentoQuoteModelQuoteItem */
    $item = $observer->getEvent()->getQuoteItem();//Gets the Quote Item Instance
    $request = $item->getBuyRequest(); // Gets the posted data sent to "Add to cart" controller action
    $this->processOptions($item);
    return $this;
    }//end execute()


    /**
    * @inheritDoc
    */
    public function processOptions(CartItemInterface $cartItem)
    {
    $options = $this->getOptions($cartItem);
    if (!empty($options) && is_array($options)) {
    $this->updateOptionsValues($options);
    $productOption = $cartItem->getProductOption()
    ? $cartItem->getProductOption()
    : $this->productOptionFactory->create();

    /** @var MagentoQuoteApiDataProductOptionExtensionInterface $extensibleAttribute */
    $extensibleAttribute = $productOption->getExtensionAttributes()
    ? $productOption->getExtensionAttributes()
    : $this->extensionFactory->create();

    $extensibleAttribute->setCustomOptions($options);
    $productOption->setExtensionAttributes($extensibleAttribute);
    $cartItem->setProductOption($productOption);
    }
    }

    /**
    * Receive custom option from buy request
    *
    * @param CartItemInterface $cartItem
    * @return array
    */
    protected function getOptions(CartItemInterface $cartItem)
    {
    $buyRequest = !empty($cartItem->getOptionByCode('info_buyRequest'))
    ? unserialize($cartItem->getOptionByCode('info_buyRequest')->getValue())
    : null;
    return is_array($buyRequest) && isset($buyRequest['options'])
    ? $buyRequest['options']
    : ;
    }

    /**
    * Update options values
    *
    * @param array $options
    * @return null
    */
    protected function updateOptionsValues(array &$options)
    {
    foreach ($options as $optionId => &$optionValue) {
    /** @var MagentoCatalogModelCustomOptionsCustomOption $option */
    $option = $this->customOptionFactory->create();
    $option->setOptionId($optionId);
    if (is_array($optionValue)) {
    $optionValue = implode(',', $optionValue);
    }
    $option->setOptionValue($optionValue);
    $optionValue = $option;
    }
    }
    }


    I have not tried out the code, but should help you add new data to your product option.






    share|improve this answer





















    • Where to set custom option in above code?
      – Bhupendra Jadeja
      Jul 13 '16 at 12:06














    1












    1








    1






    You can use the event checkout_cart_product_add_after to modify the product image information.



    Firstly in your product detail page you need to add a hidden field in the add to cart form something like:



    <input type="hidden" name="[option][front_designurl]" id="front_designurl"/>


    And using javascript add the value to the field for the generated image url by the user, this value gets saved in the info_buyRequest of the quote item options



    We have to create the file app/code/Foo/CustomImage/etc/events.xml to attach observers to the events:





    1. checkout_cart_product_add_after: Event is fired on Add to Cart


    2. checkout_cart_product_update_after: Event is fired on Cart Update (For add to cart from cart edit page)




    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
    <observer name="foo_customimage_observer_set_price_for_item_add" instance="FooCustomImageModelObserverSetImageForItem"/>
    </event>
    <event name="checkout_cart_product_update_after">
    <observer name="foo_customimage_observer_set_price_for_item_update" instance="FooCustomImageModelObserverSetImageForItem"/>
    </event>
    </config>


    Now for the observer logic we create a file at app/code/Foo/CustomImage/Model/Observer/SetImageForItem.php



    <?php

    namespace FooCustomImageModelObserver;

    use MagentoFrameworkEventObserver;
    use MagentoFrameworkEventObserverInterface;
    use MagentoQuoteModelQuoteProductOptionFactory;
    use MagentoQuoteApiDataProductOptionExtensionFactory;
    use MagentoCatalogModelCustomOptionsCustomOptionFactory;

    class SetImageForItem implements ObserverInterface
    {
    /** @var MagentoQuoteModelQuoteProductOptionFactory */
    protected $productOptionFactory;

    /** @var MagentoQuoteApiDataProductOptionExtensionFactory */
    protected $extensionFactory;

    /** @var CustomOptionFactory */
    protected $customOptionFactory;

    /**
    * @param ProductOptionFactory $productOptionFactory
    * @param ProductOptionExtensionFactory $extensionFactory
    * @param CustomOptionFactory $customOptionFactory
    */
    public function __construct(
    ProductOptionFactory $productOptionFactory,
    ProductOptionExtensionFactory $extensionFactory
    CustomOptionFactory $customOptionFactory
    ) {
    $this->productOptionFactory = $productOptionFactory;
    $this->extensionFactory = $extensionFactory;
    $this->customOptionFactory = $customOptionFactory;
    }

    public function execute(Observer $observer)
    {
    /** @var $item MagentoQuoteModelQuoteItem */
    $item = $observer->getEvent()->getQuoteItem();//Gets the Quote Item Instance
    $request = $item->getBuyRequest(); // Gets the posted data sent to "Add to cart" controller action
    $this->processOptions($item);
    return $this;
    }//end execute()


    /**
    * @inheritDoc
    */
    public function processOptions(CartItemInterface $cartItem)
    {
    $options = $this->getOptions($cartItem);
    if (!empty($options) && is_array($options)) {
    $this->updateOptionsValues($options);
    $productOption = $cartItem->getProductOption()
    ? $cartItem->getProductOption()
    : $this->productOptionFactory->create();

    /** @var MagentoQuoteApiDataProductOptionExtensionInterface $extensibleAttribute */
    $extensibleAttribute = $productOption->getExtensionAttributes()
    ? $productOption->getExtensionAttributes()
    : $this->extensionFactory->create();

    $extensibleAttribute->setCustomOptions($options);
    $productOption->setExtensionAttributes($extensibleAttribute);
    $cartItem->setProductOption($productOption);
    }
    }

    /**
    * Receive custom option from buy request
    *
    * @param CartItemInterface $cartItem
    * @return array
    */
    protected function getOptions(CartItemInterface $cartItem)
    {
    $buyRequest = !empty($cartItem->getOptionByCode('info_buyRequest'))
    ? unserialize($cartItem->getOptionByCode('info_buyRequest')->getValue())
    : null;
    return is_array($buyRequest) && isset($buyRequest['options'])
    ? $buyRequest['options']
    : ;
    }

    /**
    * Update options values
    *
    * @param array $options
    * @return null
    */
    protected function updateOptionsValues(array &$options)
    {
    foreach ($options as $optionId => &$optionValue) {
    /** @var MagentoCatalogModelCustomOptionsCustomOption $option */
    $option = $this->customOptionFactory->create();
    $option->setOptionId($optionId);
    if (is_array($optionValue)) {
    $optionValue = implode(',', $optionValue);
    }
    $option->setOptionValue($optionValue);
    $optionValue = $option;
    }
    }
    }


    I have not tried out the code, but should help you add new data to your product option.






    share|improve this answer












    You can use the event checkout_cart_product_add_after to modify the product image information.



    Firstly in your product detail page you need to add a hidden field in the add to cart form something like:



    <input type="hidden" name="[option][front_designurl]" id="front_designurl"/>


    And using javascript add the value to the field for the generated image url by the user, this value gets saved in the info_buyRequest of the quote item options



    We have to create the file app/code/Foo/CustomImage/etc/events.xml to attach observers to the events:





    1. checkout_cart_product_add_after: Event is fired on Add to Cart


    2. checkout_cart_product_update_after: Event is fired on Cart Update (For add to cart from cart edit page)




    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
    <observer name="foo_customimage_observer_set_price_for_item_add" instance="FooCustomImageModelObserverSetImageForItem"/>
    </event>
    <event name="checkout_cart_product_update_after">
    <observer name="foo_customimage_observer_set_price_for_item_update" instance="FooCustomImageModelObserverSetImageForItem"/>
    </event>
    </config>


    Now for the observer logic we create a file at app/code/Foo/CustomImage/Model/Observer/SetImageForItem.php



    <?php

    namespace FooCustomImageModelObserver;

    use MagentoFrameworkEventObserver;
    use MagentoFrameworkEventObserverInterface;
    use MagentoQuoteModelQuoteProductOptionFactory;
    use MagentoQuoteApiDataProductOptionExtensionFactory;
    use MagentoCatalogModelCustomOptionsCustomOptionFactory;

    class SetImageForItem implements ObserverInterface
    {
    /** @var MagentoQuoteModelQuoteProductOptionFactory */
    protected $productOptionFactory;

    /** @var MagentoQuoteApiDataProductOptionExtensionFactory */
    protected $extensionFactory;

    /** @var CustomOptionFactory */
    protected $customOptionFactory;

    /**
    * @param ProductOptionFactory $productOptionFactory
    * @param ProductOptionExtensionFactory $extensionFactory
    * @param CustomOptionFactory $customOptionFactory
    */
    public function __construct(
    ProductOptionFactory $productOptionFactory,
    ProductOptionExtensionFactory $extensionFactory
    CustomOptionFactory $customOptionFactory
    ) {
    $this->productOptionFactory = $productOptionFactory;
    $this->extensionFactory = $extensionFactory;
    $this->customOptionFactory = $customOptionFactory;
    }

    public function execute(Observer $observer)
    {
    /** @var $item MagentoQuoteModelQuoteItem */
    $item = $observer->getEvent()->getQuoteItem();//Gets the Quote Item Instance
    $request = $item->getBuyRequest(); // Gets the posted data sent to "Add to cart" controller action
    $this->processOptions($item);
    return $this;
    }//end execute()


    /**
    * @inheritDoc
    */
    public function processOptions(CartItemInterface $cartItem)
    {
    $options = $this->getOptions($cartItem);
    if (!empty($options) && is_array($options)) {
    $this->updateOptionsValues($options);
    $productOption = $cartItem->getProductOption()
    ? $cartItem->getProductOption()
    : $this->productOptionFactory->create();

    /** @var MagentoQuoteApiDataProductOptionExtensionInterface $extensibleAttribute */
    $extensibleAttribute = $productOption->getExtensionAttributes()
    ? $productOption->getExtensionAttributes()
    : $this->extensionFactory->create();

    $extensibleAttribute->setCustomOptions($options);
    $productOption->setExtensionAttributes($extensibleAttribute);
    $cartItem->setProductOption($productOption);
    }
    }

    /**
    * Receive custom option from buy request
    *
    * @param CartItemInterface $cartItem
    * @return array
    */
    protected function getOptions(CartItemInterface $cartItem)
    {
    $buyRequest = !empty($cartItem->getOptionByCode('info_buyRequest'))
    ? unserialize($cartItem->getOptionByCode('info_buyRequest')->getValue())
    : null;
    return is_array($buyRequest) && isset($buyRequest['options'])
    ? $buyRequest['options']
    : ;
    }

    /**
    * Update options values
    *
    * @param array $options
    * @return null
    */
    protected function updateOptionsValues(array &$options)
    {
    foreach ($options as $optionId => &$optionValue) {
    /** @var MagentoCatalogModelCustomOptionsCustomOption $option */
    $option = $this->customOptionFactory->create();
    $option->setOptionId($optionId);
    if (is_array($optionValue)) {
    $optionValue = implode(',', $optionValue);
    }
    $option->setOptionValue($optionValue);
    $optionValue = $option;
    }
    }
    }


    I have not tried out the code, but should help you add new data to your product option.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jun 1 '16 at 15:29









    Atish GoswamiAtish Goswami

    3,24931645




    3,24931645












    • Where to set custom option in above code?
      – Bhupendra Jadeja
      Jul 13 '16 at 12:06


















    • Where to set custom option in above code?
      – Bhupendra Jadeja
      Jul 13 '16 at 12:06
















    Where to set custom option in above code?
    – Bhupendra Jadeja
    Jul 13 '16 at 12:06




    Where to set custom option in above code?
    – Bhupendra Jadeja
    Jul 13 '16 at 12:06













    0














    I was having a similar problem and solved the part of showing another image like this. beware: It might have bugs, if the aspect ratio / size of the actual product image from backend differs from the customized one.



    di.xml



    <type name="MagentoCheckoutBlockCartItemRenderer">
    <plugin sortOrder="1" name="foo" type="FooBarPluginBlockCartItemRendererPlugin"/>
    </type>


    RendererPlugin.php



    <?php

    namespace FooBarPluginBlockCartItem;

    class RendererPlugin
    {
    /**
    * Override cart image, if designer product
    *
    * @param MagentoCheckoutBlockCartItemRenderer $subject
    * @param MagentoCatalogBlockProductImage $result
    * @see MagentoCheckoutBlockCartItemRenderer::getImage
    */
    public function afterGetImage(MagentoCheckoutBlockCartItemRenderer $subject, $result)
    {
    $item = $subject->getItem();
    $optionId = $this->options->getDesignerCodeOptionId($subject->getProduct());
    $designCode = $item->getOptionByCode('option_' . $optionId)->getValue();
    $design = $this->design->getByDesignCode($designCode);

    $previewImageUrl = $design->getData('preview_image_url');

    $result->setImageUrl($previewImageUrl);

    return $result; // recreate, to calculate aspect ratio an -- possible BUG: does not recalculate aspect ratio :-(

    }
    }





    share|improve this answer


























      0














      I was having a similar problem and solved the part of showing another image like this. beware: It might have bugs, if the aspect ratio / size of the actual product image from backend differs from the customized one.



      di.xml



      <type name="MagentoCheckoutBlockCartItemRenderer">
      <plugin sortOrder="1" name="foo" type="FooBarPluginBlockCartItemRendererPlugin"/>
      </type>


      RendererPlugin.php



      <?php

      namespace FooBarPluginBlockCartItem;

      class RendererPlugin
      {
      /**
      * Override cart image, if designer product
      *
      * @param MagentoCheckoutBlockCartItemRenderer $subject
      * @param MagentoCatalogBlockProductImage $result
      * @see MagentoCheckoutBlockCartItemRenderer::getImage
      */
      public function afterGetImage(MagentoCheckoutBlockCartItemRenderer $subject, $result)
      {
      $item = $subject->getItem();
      $optionId = $this->options->getDesignerCodeOptionId($subject->getProduct());
      $designCode = $item->getOptionByCode('option_' . $optionId)->getValue();
      $design = $this->design->getByDesignCode($designCode);

      $previewImageUrl = $design->getData('preview_image_url');

      $result->setImageUrl($previewImageUrl);

      return $result; // recreate, to calculate aspect ratio an -- possible BUG: does not recalculate aspect ratio :-(

      }
      }





      share|improve this answer
























        0












        0








        0






        I was having a similar problem and solved the part of showing another image like this. beware: It might have bugs, if the aspect ratio / size of the actual product image from backend differs from the customized one.



        di.xml



        <type name="MagentoCheckoutBlockCartItemRenderer">
        <plugin sortOrder="1" name="foo" type="FooBarPluginBlockCartItemRendererPlugin"/>
        </type>


        RendererPlugin.php



        <?php

        namespace FooBarPluginBlockCartItem;

        class RendererPlugin
        {
        /**
        * Override cart image, if designer product
        *
        * @param MagentoCheckoutBlockCartItemRenderer $subject
        * @param MagentoCatalogBlockProductImage $result
        * @see MagentoCheckoutBlockCartItemRenderer::getImage
        */
        public function afterGetImage(MagentoCheckoutBlockCartItemRenderer $subject, $result)
        {
        $item = $subject->getItem();
        $optionId = $this->options->getDesignerCodeOptionId($subject->getProduct());
        $designCode = $item->getOptionByCode('option_' . $optionId)->getValue();
        $design = $this->design->getByDesignCode($designCode);

        $previewImageUrl = $design->getData('preview_image_url');

        $result->setImageUrl($previewImageUrl);

        return $result; // recreate, to calculate aspect ratio an -- possible BUG: does not recalculate aspect ratio :-(

        }
        }





        share|improve this answer












        I was having a similar problem and solved the part of showing another image like this. beware: It might have bugs, if the aspect ratio / size of the actual product image from backend differs from the customized one.



        di.xml



        <type name="MagentoCheckoutBlockCartItemRenderer">
        <plugin sortOrder="1" name="foo" type="FooBarPluginBlockCartItemRendererPlugin"/>
        </type>


        RendererPlugin.php



        <?php

        namespace FooBarPluginBlockCartItem;

        class RendererPlugin
        {
        /**
        * Override cart image, if designer product
        *
        * @param MagentoCheckoutBlockCartItemRenderer $subject
        * @param MagentoCatalogBlockProductImage $result
        * @see MagentoCheckoutBlockCartItemRenderer::getImage
        */
        public function afterGetImage(MagentoCheckoutBlockCartItemRenderer $subject, $result)
        {
        $item = $subject->getItem();
        $optionId = $this->options->getDesignerCodeOptionId($subject->getProduct());
        $designCode = $item->getOptionByCode('option_' . $optionId)->getValue();
        $design = $this->design->getByDesignCode($designCode);

        $previewImageUrl = $design->getData('preview_image_url');

        $result->setImageUrl($previewImageUrl);

        return $result; // recreate, to calculate aspect ratio an -- possible BUG: does not recalculate aspect ratio :-(

        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 days ago









        AlexAlex

        9,4231553113




        9,4231553113






























            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%2f117863%2fmagento-2-generate-customization-image-in-product-page-and-add-it-to-product-o%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

            An IMO inspired problem

            Management

            Investment