#StackBounty: #magento2 #grid #order-grid #dynamic-rows Add custom dynamic column in sales order grid Magento 2

Bounty: 50

This solution shows how to add custom column to sales order grid, but to add a custom column you need to add the column via xml,the problem is i need to read data collection to get available column data and add it as custom column in sales order grid, in conclusion i want to add multiple columns which will be generated dynamically from database collection data , is there anyway to do this?


Get this bounty!!!

#StackBounty: #magento2 #grid how i set the pagination in the admin in magento2 in custom module?

Bounty: 50

pagination is not working in custom module in admin in magento 2enter image description here

please tell me how it work in magento 2

<?php
namespace VendorModuleBlockAdminhtmlColor;

/**
 * Adminhtml news pages grid
 */
class Grid extends MagentoBackendBlockWidgetGridExtended
{
    /**
     * @var MagentoFrameworkModuleManager
     */
    protected $moduleManager;

    /**
     * @var MagentoEavModelResourceModelEntityAttributeSetCollectionFactory]
     */
    protected $_setsFactory;

    /**
     * @var MagentoCatalogModelProductFactory
     */
    protected $_productFactory;

    /**
     * @var MagentoCatalogModelProductType
     */
    protected $_type;

    /**
     * @var MagentoCatalogModelProductAttributeSourceStatus
     */
    protected $_status;
    protected $_collectionFactory;

    /**
     * @var MagentoCatalogModelProductVisibility
     */
    protected $_visibility;

    /**
     * @var MagentoStoreModelWebsiteFactory
     */
    protected $_websiteFactory;

    /**
     * @param MagentoBackendBlockTemplateContext $context
     * @param MagentoBackendHelperData $backendHelper
     * @param MagentoStoreModelWebsiteFactory $websiteFactory
     * @param MagentoEavModelResourceModelEntityAttributeSetCollectionFactory $setsFactory
     * @param MagentoCatalogModelProductFactory $productFactory
     * @param MagentoCatalogModelProductType $type
     * @param MagentoCatalogModelProductAttributeSourceStatus $status
     * @param MagentoCatalogModelProductVisibility $visibility
     * @param MagentoFrameworkModuleManager $moduleManager
     * @param array $data
     *
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoBackendHelperData $backendHelper,
        MagentoStoreModelWebsiteFactory $websiteFactory,
        OcodewireDesigntoolModelResourceColorCollection $collectionFactory,
        MagentoFrameworkModuleManager $moduleManager,
        array $data = []
    ) {

        $this->_collectionFactory = $collectionFactory;
        $this->_websiteFactory = $websiteFactory;
        $this->moduleManager = $moduleManager;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();

        $this->setId('productGrid');
        $this->setDefaultSort('id');
         $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);

    }

    /**
     * @return Store
     */
    protected function _getStore()
    {
        $storeId = (int)$this->getRequest()->getParam('store', 0);
        return $this->_storeManager->getStore($storeId);
    }

    /**
     * @return $this
     */
    protected function _prepareCollection()
    {
        try{


            $collection =$this->_collectionFactory->load();



            $this->setCollection($collection);

            parent::_prepareCollection();

            return $this;
        }
        catch(Exception $e)
        {
            echo $e->getMessage();die;
        }
    }

    /**
     * @param MagentoBackendBlockWidgetGridColumn $column
     * @return $this
     */
    protected function _addColumnFilterToCollection($column)
    {
        if ($this->getCollection()) {
            if ($column->getId() == 'websites') {
                $this->getCollection()->joinField(
                    'websites',
                    'catalog_product_website',
                    'website_id',
                    'product_id=entity_id',
                    null,
                    'left'
                );
            }
        }
        return parent::_addColumnFilterToCollection($column);
    }

    /**
     * @return $this
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function _prepareColumns()
    {
        // echo "dffdsfsd"; die;
        $this->addColumn(
            'color_id',
            [
                'header' => __('Color Id'),
                'type' => 'number',
                'index' => 'color_id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );


        $this->addColumn(
            'color_name',
            [
                'header' => __('Color Name'),
                'type' => 'text',
                'index' => 'color_name',
            ]
        );

        $this->addColumn(
            'color_code',
            [
                'header' => __('Color Code'),
                'index' => 'color_code',
                'class' => 'color code',  
            ]
        );


        $this->addColumn(
            'color_code',
            [
                'header' => __('Color Code'),
                'index' => 'color_code',
                'class' => 'color code',  
            ]
        );









         $this->addColumn(
            'Edit',
            [
                'header' => __('Edit'),
                'type' => 'action',
                'getter' => 'getId',
                'actions' => [
                    [
                        'caption' => __('Edit'),
                        'url' => [
                            'base' => '*/*/edit',
                            'params' => ['store' => $this->getRequest()->getParam('store')]
                        ],
                        'field' => 'id'
                    ]
                ],
                'filter' => false,
                'sortable' => false,
                'index' => 'stores',
                'header_css_class' => 'col-action',
                'column_css_class' => 'col-action'
            ]
        );


        /*{{CedAddGridColumn}}*/
        $block = $this->getLayout()->getBlock('grid.bottom.links');
        if ($block) {
            $this->setChild('grid.bottom.links', $block);
        }

        return parent::_prepareColumns();
    }

     /**
     * @return $this
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('id');
        $this->getMassactionBlock()->setFormFieldName('id');

        $this->getMassactionBlock()->addItem(
            'delete',
            array(
                'label' => __('Delete'),
                'url' => $this->getUrl('*/*/massDelete'),
                'confirm' => __('Are you sure?')
            )
        );
        return $this;
    }

    /**
     * @return string
     */


    /**
     * @param MagentoCatalogModelProduct|MagentoFrameworkObject $row
     * @return string
     */
    public function getRowUrl($row)
    {
        return $this->getUrl(
            '*/*/edit',
            ['store' => $this->getRequest()->getParam('store'), 'id' => $row->getId()]
        );
    }


     public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', ['_current' => true]);
    }
}


Get this bounty!!!

#StackBounty: #magento2 #collection #grid Filtering grid by using filter_url_params is not working

Bounty: 50

I added a grid to a ui_component form and I want to use an Url-parameter to filter the content of the grid. Herefore I added the ‘filter_url_params’ in my listing:

    <dataSource name="mcas_covertemplate_graphicelement_listing_data_source">
    <argument name="dataProvider" xsi:type="configurableObject">
        <argument name="class" xsi:type="string">MagentoFrameworkViewElementUiComponentDataProviderDataProvider</argument>
        <argument name="name" xsi:type="string">mcas_covertemplate_graphicelement_listing_data_source</argument>
        <argument name="primaryFieldName" xsi:type="string">graphicelement_id</argument>
        <argument name="requestFieldName" xsi:type="string">id</argument>
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
                <item name="update_url" xsi:type="url" path="mui/index/render"/>
                <item name="filter_url_params" xsi:type="array">
                    <item name="cover_id" xsi:type="string">*</item>
                </item>
                <item name="storageConfig" xsi:type="array">
                    <item name="indexField" xsi:type="string">graphicelement_id</item>
                </item>
            </item>
        </argument>
    </argument>
</dataSource>

The cover_id is visible in my Url, but it is not used to set the filter.
If I set a value for the cover_id manually it works.

What I am doing wrong?


Get this bounty!!!

#StackBounty: #magento-1.9 #event-observer #grid #filter #custom-column-grid filter_condition_callback function not called in observer

Bounty: 50

I’m adding a custom column (from a custom table) to an admin grid with an observer, and the filtering/sorting doesn’t work. Adding the ‘filter_condition_callback’ to my column doesn’t work, the function is never called.

I’ve seen other similar questions but none of them had this particular problem, or they were never answered.


I’ve made a module that modifies the admin_user grid.

It contains an observer linked to these events :

    <core_collection_abstract_load_before>
        <observers>
            <beforeCollectionLoad>
                <class>Namespace_Adminextra_Model_Observers_Users</class>
                <method>beforeCollectionLoad</method>
            </beforeCollectionLoad>
        </observers>
    </core_collection_abstract_load_before>

    <adminhtml_block_html_before>
        <observers>
            <add_an_field>
                <type>singleton</type>
                <class>Namespace_Adminextra_Model_Observers_Users</class>
                <method>appendContent</method>
            </add_an_field>
        </observers>
    </adminhtml_block_html_before>

So the beforeCollectionLoad method is called so I can join my custom column (from a custom table, not an attribute) :

public function beforeCollectionLoad(Varien_Event_Observer $observer)
{
    $collection = $observer->getCollection();
    if (!isset($collection)) {
        return;
    }
    if ($collection instanceof Mage_Admin_Model_Resource_User_Collection) {
        $collection->getSelect()->joinLeft(
            array('adminextra' => 'digitagri_adminextra'),
            'adminextra.user_id = main_table.user_id',
            array(
                'is_advisor' => 'adminextra.is_advisor',
                'phone' => 'adminextra.phone',
            )
        );
    }
}

This successfully seems to add the column to the collection.
The observer first calls the function appendContent, which checks the current grid :

public function appendContent(Varien_Event_Observer $observer){
    $block = $observer->getEvent()->getBlock();

    if (!isset($block)) {
        return $this;
    }
    if ($block instanceof Mage_Adminhtml_Block_Permissions_User_Grid) {
        $this->appendCustomColumns($block);
    }
    return $this;
}

Then the column is added :

public function appendCustomColumns($grid){
    $grid->addColumnAfter('is_advisor', array(
        'header' => 'Conseiller',
        'align' => 'left',
        'width' => '50',
        'index' => 'is_advisor',
        'type' => 'options',
        'options'   => array('1' => Mage::helper('adminhtml')->__('Oui'), '0' => Mage::helper('adminhtml')->__('Non')),
        'filter_condition_callback' => array($this,'_filterIsAdvisor'),
    ), 'is_active');
    $grid->sortColumnsByOrder();
}

The column is added and the values are displayed, the ‘options’ acts as a renderer and correctly displays ‘1’ as Oui and ‘0’ as Non. But the filtering and sorting don’t work. No error, no exceptions, it does nothing.

The function called in ‘filter_condition_callback’ never seems to be called either. I’ve put a Mage::log to check :

protected function _filterIsAdvisor($collection, $column){
    Mage::log('works?',null,'test.log',true);
}

So what am I doing wrong ?

Filtering and sorting seem incredibly finicky, especially since i’m joining a column from a custom table and not an attribute.


Get this bounty!!!

#StackBounty: #magento2 #layout #collection #grid Magento2 Need to filter grid when value is entered in search box, the column of the d…

Bounty: 50

I have added 4 columns in the grid as displayed in below screenshot.

enter image description here

For displaying for eg. Recipient Email column I added following code in XML & it’s renderer PHP file. (Code is added below)

app/code/Company/Module/view/adminhtml/layout/adminhtml_giftcardaccount_block.xml

<block class="MagentoBackendBlockWidgetGridColumn">
                    <arguments>
                        <argument name="header" xsi:type="string" translate="true">Recipient Email</argument>
                        <argument name="index" xsi:type="string">recipient_email</argument>
                        <argument name="renderer" xsi:type="string">CompanyModuleBlockAdminhtmlWidgetGridColumnRendererRecipientemail</argument>
                        <argument name="sortable" xsi:type="boolean">false</argument>
                    </arguments>
                </block>

app/code/Company/Module//Block/Adminhtml/Widget/Grid/Column/Renderer/Recipientemail.php

<?php
namespace CompanyModuleBlockAdminhtmlWidgetGridColumnRenderer;
class Recipientemail extends MagentoBackendBlockWidgetGridColumnRendererAbstractRenderer
{
    protected $_storeManager;

    public function __construct(
        MagentoBackendBlockContext $context,
        MagentoStoreModelStoreManagerInterface $storeManager,      
        MagentoSalesModelOrderItem $orderItem,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_storeManager = $storeManager;      
        $this->orderitem =  $orderItem;  
    }


    public function render(MagentoFrameworkDataObject $row)
    {
        $code = $row->getCode();
        $result = array();
        $salesorderitem =  $this->orderitem->getCollection()
                          ->addFieldToFilter('product_options', array('like' => '%'.$code.'%'));

        if(!empty($salesorderitem)) 
        {
            foreach($salesorderitem as $orderdata){
                $productOptions = $orderdata->getProductOptions();   
                $recipientemail = $productOptions['giftcard_recipient_email'];
                if(!empty($recipientemail)){
                return $recipientemail;
                }else{
                    return '-';
                }
            }
        }else{
               return '-';
        }


    }

Main table of grid is – magento_giftcardaccount

Recipientemail table is – product_options

{"info_buyRequest":{"uenc":"aHR0cDovLzE5Mi4xNjguMS4xODQvZGcvZHJ1bW1vbmQtZ29sZi1lLWdpZnQtY2FyZC5odG1s","product":"76450","selected_configurable_option":"","related_product":"","giftcard_amount":"5","giftcard_sender_name":"test","giftcard_sender_email":"testmscgoriteeps@gmail.com","giftcard_recipient_name":"test22","giftcard_recipient_email":"arjun.cmarix@gmail.com","giftcard_message":"test test gift","qty":"1"},"giftcard_sender_name":"test","giftcard_sender_email":"testmscgoriteeps@gmail.com","giftcard_recipient_name":"test22","giftcard_recipient_email":"arjun.cmarix@gmail.com","giftcard_message":"test test gift","giftcard_lifetime":null,"giftcard_is_redeemable":0,"giftcard_email_template":null,"giftcard_type":"0","email_sent":0,"giftcard_created_codes":["HQE9EMUNTA6N"]}

My issue is the filter is not working. When I enter email in the search text field of grid it keeps on spinning for some time & grid is loaded as it is without filter.

It would be really appreciable if someone can guide me on how to filter this search text.


Get this bounty!!!

#StackBounty: #python #search #grid #knn #imputation grid search with own estimator in python

Bounty: 50

I am trying to build my own estimator (regressor) and use it for imputation (KnnImputation).
For now – I wrote a very basic knn imputation, when it will work I will change the algorithm a bit.

I’m having a problem using the grid search “GridSearchCV”.
I tried to print the shapes of the data to get a sense of the problem. When the configuration is 10-fold cross validation I would expect the prints to be 10 times this lines:

xTrain size : 2487
yTrain size : 2487
test size : 276

But instead I get this lines:

xTrain size : 2487
yTrain size : 2487
test size : 276

test size : 2487

more the 60 times.

Any idea what is the problem?

My Code:

class KnnImputation(BaseEstimator, RegressorMixin):

    def __init__(self, k=5, distance='euclidean'):
        self.k = k
        self.distance = distance

    def get_params(self, deep=False):
        return {'k': self.k, 'distance': self.distance}

    def set_params(self, **parameters):
        self.k = parameters['k']
        self.distance = parameters['distance']

    def fit(self, X, y):
        self.xTrain = X.values
        self.yTrain = y.values
        print("nxTrain size : " + str(self.xTrain.shape[0]))
        print("yTrain size : " + str(self.yTrain.shape[0]))

        return self

    def predict(self, xTest):
        xTest = xTest.values
        num_test = xTest.shape[0]
        print("test size : " + str(num_test)+"n")
        yPred = np.zeros(num_test, dtype=self.yTrain.dtype).reshape(-1, 1)

        for i in range(num_test):
            distances = np.sum(np.abs(self.xTrain - xTest[i, :]), axis=1)
            idx = np.argsort(distances)
            minIndexes = idx[:self.k]
            kClosest = self.yTrain[minIndexes[:]]
            yPred[i] = np.mean(kClosest)

        return yPred

kf = KFold(n_splits=10, shuffle=False, random_state=23)
NN = KnnImputation()
gridSearchNN = GridSearchCV(NN, param_grid=params, scoring="neg_mean_squared_error", n_jobs=1,
                                cv=kf.split(xTrain, yTrain), verbose=1)
gridSearchNN.fit(X=xTrain, y=yTrain)

The Error:

  File "C:Users....dataImputation.py", line 85, in knnImputationMethod
    gridSearchNN.fit(X=xTrain, y=yTrain)
  File "C:Users...Anaconda3libsite-packagessklearnmodel_selection_search.py", line 740, in fit
    self.best_estimator_.fit(X, y, **fit_params)
AttributeError: 'NoneType' object has no attribute 'fit'


Get this bounty!!!

#StackBounty: #unity #collision-detection #physics #mathematics #grid Redundant checks from spatial partitioning

Bounty: 100

A simple 2D grid partition system for collision detection divides space into equal-sized tiles. Colliders then map themselves to tiles with their bounding box in O(N) time. Collision detection only has to be performed between objects that occupy the same tile(s).

Collision detection is expensive so the more culled, the better. With a grid partitioning system, how are collisions culled when colliders share multiple tiles?

For example, Circle_A and Circle_B both sit on the edge between Tile_1 and Tile_2. Iterating both tiles would make collision detection between Circle_A & Circle_B run twice.
Sharing Multiple Tiles

A global pair hashtable seems performance expensive since it has to be cleared every frame. Tracking pairs inside colliders takes a lot of memory. How do you mitigate redundant pairs when iterating through partition grid tiles?


Get this bounty!!!