#StackBounty: #magento2 #payment #payment-gateway When to use Payment method facade

Bounty: 50

I am working custom payment method in Magento 2. I referred Magento documentation http://devdocs.magento.com/guides/v2.1/payments-integrations/base-integration/payment-option-config.html where
they mentioned using Payment method facade.

But I reviewed core model module-authorizenet where they have not used Payment method facade
They used “MagentoAuthorizenetModelDirectpost” instead of Payment method facade.
I am bit confused with when to use Payment method facade.

So when to use Payment method facade?


Get this bounty!!!

#StackBounty: #magento2 #cookie Unable to send the cookie. Maximum number of cookies would be exceeded Magento 2.1.5

Bounty: 50

Every time I open var/Repots in magento 2 website, I found hundreds and thousands of error files all having the same message:

a:4:{i:0;s:71:"Unable to send the cookie. Maximum number of cookies would be exceeded.";
i:1;s:12555:"#0 /home/domain/public_html/vendor/magento/framework/Stdlib/Cookie/PhpCookieManager.php(116): MagentoFrameworkStdlibCookiePhpCookieManager->checkAbilityToSendCookie('form_key', '........')...

I searched a lot, but I did not find a solution. The maximum number of cookies is set to 50 by default.

The problem is not happening on my browser. It mostly happens with customers using android mobile phone’s browser Android Version 4.0.2 to 4.4.0.

Clearing cache or using private browsing solves the issue on the client side. However I need a server side solution. (I asked a customer to clear the cache and the problem is solved on his mobile).


Get this bounty!!!

#StackBounty: #magento2 #modal How can I change an existing modal in Magento 2

Bounty: 100

I’m trying to change the behaviour of a Modal (not Model) in Magento 2. The modal in question is advanced_inventory_modal, declared in module-catalog-inventory/view/adminhtml/ui_component/product_form.xml.

Now I know I can use a Modifier in the product-form-modifier-pool:

<virtualType name="MagentoCatalogUiDataProviderProductFormModifierPool">
    <arguments>
        <argument name="modifiers" xsi:type="array">
            <item name="hf_quantity" xsi:type="array">
                <item name="class" xsi:type="string">VendorModuleUiDataProviderProductFormModifierQuantity</item>
                <item name="sortOrder" xsi:type="number">100</item>
            </item>
        </argument>
    </arguments>
</virtualType>

… and use the modifyMeta()-method in my modifier to manipulate the XML configuration, but for some reason, the inventory modal is not present in the data that is provided here. It’s also not a sortOrder-related problem, since I already set that way high. The sortOrder-attribute might have something to do with it.

So what gives? Can anyone tell me what’s the proper way to modify the content of an existing modal in Magento 2?

Edit:

I found a solution or workaround (not sure yet) on how to achieve what I am trying to achieve. It turns out that if I set sortOrder to 10000 I have some data in my modifyMeta()-method that I can use:

/**
 * @param array $meta
 */
public function modifyMeta(array $meta)
{
    if ($path = $this->arrayManager->findPath('quantity_and_stock_status_qty', $meta, null, 'children')) {
        $this->arrayManager->remove(
            $path . '/children/qty/arguments/data/config/validation/validate-digits',
            $meta
        );
    }

    if ($path = $this->arrayManager->findPath('advanced_inventory_modal', $meta)) {
        $meta = $this->arrayManager->merge(
            $path . '/children/stock_data/children/qty/arguments/data/config',
            $meta,
            ['validation' => ['validate-digits' => false]]
        );
    }

    return $meta;
}

“`

Note that the advanced_inventory_modal node is not yet complete, but my best guess is that the later addition of the modal merges with these settings, but doesn’t override it. Could be wrong though, perhaps someone could share some more light on how this mechanism works?


Get this bounty!!!

#StackBounty: #magento2 #full-page-cache Magento 2 – Cart – Cache issue

Bounty: 50

We’ve created an extension that sets a default shipping method for the cart. Below $50 the shipping costs will be $5,95, above $50 the shipping will be free.

The function itself works fine, but the problem is that the amount for shipping seems to be cached (different than other cart totals).

If I have a product that costs $19,95, add this to my cart, and in my cart set the quantity on 4, free shipping should be shown. All totals are updated, only the shipping still shows the $5,95. After I refresh the page again, the shipping cost is update to ‘Free’.

How can I prevent this cache?

This is the cart: https://www.dropbox.com/s/0qr9nxrrqidnp4n/Schermafbeelding%202017-08-30%20om%2011.28.54.png?dl=0


Get this bounty!!!

#StackBounty: #magento2 #module #overrides #dependency Magento 2 – override 3rd party module layout file in custom theme

Bounty: 50

We have a custom theme with some layout / template overrides

Now we have installed a 3rd party module, which is overriding one of layout files we have in our custom theme. So, only module’s override is being loaded

I suppose we can deal with this, by defining that concrete layout override in a custom module (instead of the custom theme approach), and then define the module dependencies to load both layout overrides

Or is there a way to do that without the need of declaring a new module?


Get this bounty!!!

#StackBounty: #magento2 Magento2 Hide/Show VAT field based on Country

Bounty: 50

Can someone guide me on how to keep VAT field visible and required for non-USA countries and hide and not require for USA country on checkout page add address ?

I tried this way but its not working

require(['jquery'],function($){
jQuery( document ).ready(function() {
    jQuery('#co-shipping-form div[name="shippingAddress.country_id"] select').change(function(){
        var cnt = jQuery(this).val();
        if ( cnt == 'US'){
            jQuery('#co-shipping-form [name="shippingAddress.vat_id"]').hide();
        }else{
            jQuery('#co-shipping-form [name="shippingAddress.vat_id"]').show();
        }
    });
}); 
});

Thanks


Get this bounty!!!

#StackBounty: #magento2 #payment-methods how to call specific payment model function on place order in Magento 2

Bounty: 50

I am developing a custom payment module. I have successfully setup credit card form on checkout page but while I am placing an order, capture function of that payment model doesn’t call.

You can check code here https://github.com/lalitkaushik/customcode

Is there anyone can help me to know how can I call capture function?

Edit: I have noticed that after installing the module in vanilla Magento setup, it’s working only first time.


Get this bounty!!!

#StackBounty: #magento2 #database #magento-enterprise #catalog #magento2-enterprise Magento 2 EE – fetch products with sales data on sp…

Bounty: 100

I have a M2 custom extension which fetches products with its sales data from database.

Current code:

/** @var $products MagentoCatalogModelResourceModelProductCollection $productCollection */
$products = $this->objectManager->create('MagentoCatalogModelResourceModelProductCollection');

// ... adding some filters to $collection

// Enrich collection with sales data
/** @var MagentoFrameworkAppResourceConnection $resource */
$resource = $objectManager->create('MagentoFrameworkAppResourceConnection');
$ordersTableName = $resource->getTableName('sales_order_item');
$superTableName = $resource->getTableName('catalog_product_super_link');

if ($this->productHelper->isAttributeEnabled($additionalAttributes, 'ordered_qty')) {
    $collection->getSelect()->columns('(SELECT SUM(qty_ordered) FROM ' . $ordersTableName . ' AS o LEFT JOIN ' . $superTableName . ' AS l ON l.product_id = o.product_id WHERE o.product_id = e.entity_id OR l.parent_id = e.entity_id) as ordered_qty');
}

// Process products
/** @var Product $product */
foreach ($collection as $product) {
    // do something
}

It works pretty well on both CE and EE. However when I turn on “split database” feature of M2 EE it breaks as sales data are located in a different database than products.

Error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'magento21ee.sales_order_item' doesn't exist, query was: ...

The questions is – what is the best practice to handle that? Should I remove the sales data from the collection and perform a separate query to fetch sales data for each product? It seems to be really not effective.

Should I fetch all products, all sales data and then pair it which processing? It’ll add additional complexity to the code, but will be much more effective than querying DB for each product.

Or is there any hidden Magento feature how to fetch products with sales data?

Thank a bunch for any help!


Get this bounty!!!

#StackBounty: #magento2 #magento-2.1 How do I create a configurable product programmatically and assign simple products?

Bounty: 50

I am trying to create some simple products, then have those simple products assigned to a configurable product programmatically. But no matter what I try, it seems to not associate them. What am I doing wrong?

Here is what I have so far. I have commented out all the attempts I have tried too so you can see what I’ve tried already:

namespace CompanyModuleControllerGet;

use Magento;
use CompanyModuleHelperHelper;

class OutboundItem extends MagentoFrameworkAppActionAction
{
    protected $storeManager;
    protected $productFactory;
    protected $indexerFactory;
    public $helper;

    public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoCatalogModelProductFactory $productFactory,
        MagentoIndexerModelIndexerFactory $indexerFactory,
        Helper $helper
    )
    {
        $this->storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->indexerFactory = $indexerFactory;
        $this->helper = $helper;
        return parent::__construct($context);
    }

    public function execute()
    {
        // Get Website ID
        $websiteId = $this->storeManager->getWebsite()->getWebsiteId();
        $storeId = $this->storeManager->getDefaultStoreView()->getId();

        // Get the the list of products that need importing from the document.
        $items = $this->helper->getItems();

        // Loop through all the results.
        foreach ($items as $item) {
            try {
                // Create common product info variables.
                $product_name = $item->ProdName;
                $price = $item->UnitPrice;
                $weight = $item->NetWeight;
                $categoryIds = [2, $this->helper->getCategoryIdByName(substr($product_name, 0, 1))];

                // Create variable to store the created variant ids.
                $variant_ids = array();

//                $prodData = array();
                // Loop through the variants.
                foreach ($item->variants as $variant) {
                    $product = $this->productFactory->create();

                    // Preparing data for new customer.
                    $product->setSku($product_name . '_' . $variant->Code);
                    $product->setName($variant->Description); // Name of Product
                    $product->setAttributeSetId($product->getDefaultAttributeSetId()); // Attribute set id
                    $product->setStatus(1); // Status on product enabled/ disabled 1/0
                    $product->setWeight($weight); // weight of product
                    $product->setVisibility(MagentoCatalogModelProductVisibility::VISIBILITY_NOT_VISIBLE); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                    $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
                    $product->setPrice($variant->SalesPrice); // price of product
                    $product->setStockData(
                        array(
                            'use_config_manage_stock' => 0,
                            'manage_stock' => 1,
                            'is_in_stock' => 1,
                            'qty' => $variant->AvailableQuantity
                        )
                    );

                    $product->setWebsiteIds(array($websiteId));
                    $product->setCategoryIds($categoryIds);
                    $product->setStoreId($storeId);

                    $colour = $variant->value2;
                    $colourId = $this->helper->createOrGetId('color', $colour);
                    $product->setColor($colourId);

                    $size = $variant->value1;
                    $sizeId = $this->helper->createOrGetId('size', $size);
                    $product->setSize($sizeId);

                    // Save data.
                    $product->save();

                    if ($product->getId() > 0) {
                        $variant_ids[] = $product->getId();
//                        $prodData[$product->getId()] = array(
//                            '0' => array(
//                                'label' => 'Size',
//                                'attribute_id' => $this->helper->getAttribute('size')->getAttributeId(),
//                                'value_index' => $sizeId
//                            ),
//                            '1' => array(
//                                'label' => 'Color',
//                                'attribute_id' => $this->helper->getAttribute('color')->getAttributeId(),
//                                'value_index' => $colourId
//                            )
//                        );
                    }

                    $prodConfAttr = $product->getExtensionAttributes();
                    $prodConfAttr->setConfigurableProductLinks($variant_ids);
                    $product->setExtensionAttributes($prodConfAttr);
                }

                // Instantiate magento customer object.
                $product = $this->productFactory->create();

                // Preparing data for new customer.
                $product->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable)
                $product->setSku($product_name);
                $product->setName($product_name); // Name of Product
                $product->setAttributeSetId($product->getDefaultAttributeSetId()); // Attribute set id
                $product->setStatus(1); // Status on product enabled/ disabled 1/0
                $product->setWeight($weight); // weight of product
                $product->setVisibility(MagentoCatalogModelProductVisibility::VISIBILITY_BOTH); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                $product->setPrice($price); // price of product
                $product->setStockData(
                    array(
                        'use_config_manage_stock' => 0,
                        'manage_stock' => 1,
                        'is_in_stock' => 1
                    )
                );
                //setCategoryId?
                $product->setWebsiteIds(array($websiteId));
                $product->setCategoryIds($categoryIds);
                $product->setStoreId($storeId);

                // Set variants
//                $product->setNewVariationsAttributeSetId($product->getDefaultAttributeSetId());
//                $product->setAssociatedProductIds($variant_ids);
//                $product->setAffectConfigurableProductAttributes(4);
//
//                $product->getTypeInstance()->setUsedProductAttributeIds(array(
//                    $this->helper->getAttribute('color')->getAttributeId(),
//                    $this->helper->getAttribute('size')->getAttributeId()
//                ), $product);
//                $attData = $product->getTypeInstance()->getConfigurableAttributesAsArray();
//                $product->setCanSaveConfigurableAttributes(true);
//                $product->setConfigurableAttributesData($attData, $product);
////                $prodData = array();
////                foreach($variant_ids as $key => $id) {
////                    $prodData[$id] = array(
////                        '0' => array(
////                            'label'
////                        )
////                    );
////                }
//                $product->setConfigurableProductsData($prodData);

//                unset($variant_ids);

                // Save data.
                $product->save();

                echo $this->helper->getPrint($variant_ids);
                echo $this->helper->getPrint($categoryIds);
                echo $this->helper->getPrint($storeId);
                echo $this->helper->getPrint($item);
            } catch (Exception $e) {
                echo $this->helper->getPrint($item);
                echo $this->helper->getPrint($e->getMessage());
            }
        }

        echo $this->helper->getPrint('Import Complete.');

        exit;
    }
}


Get this bounty!!!

#StackBounty: #magento2 #javascript #frontend #jquery #requirejs window.on 'load', function not useable with require JS loaded …

Bounty: 50

I am trying to use $(window).on('load', function(){}); in file that is being pulled into my template with require JS, but no matter how i configure the JS, it will not execute.

The odd part is, this code will execute fine when placed in tags in the phtml, so i know it’s not an issue with the JS itself.

In my template file i have this code:


{
    "*": {
        "Magento_Cms/js/tester": {}
    }
}

And i know this is calling in the correct JS file, as i have tested the console.log inside and outside the $(window).on('load', function(){});. When i hit the page, tester 1 always prints, tester 2 does not. Inside the JS file i have:

define([
    'jquery'
], function ($) {
    'use strict';
    console.log('tester 1');
    $(window).on('load', function(){
        console.log('tester 2');
    });
});

If i take this code and put it in the template file itself, it always prints:


    require([
        'jquery'
    ], function ($) {
        'use strict';
        $(window).on('load', function(){
            console.log('tester 1');
        });
    });

So the logical conclusion would be that there is an issue with require JS loading in this JS file, but how could i track this down and test to see why this is not loading correctly?


Get this bounty!!!