Wednesday, 16 January 2019

Grid in magento 2


1. Create registration.php file.
-----------------------------------------------
<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Krupa_Customcontact',
    __dir__
);

2. Define module.xml file. in etc directory
---------------------------------------------------------------
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNameSchemaLocation ="urn:magento:framework:Module/etc/module.xsd">
    <module name="Krupa_Customcontact" setup_version="2.2.2">
        <sequence>
            <module name="Magento_Contact"/>
        </sequence>
    </module>   
</config>

3. Create setup script (setup/InstallSchema.php)
-------------------------------------------------------------
<?php
namespace Krupa\Customcontact\Setup;

use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface {
   
    public function install(
        SchemaSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $installer = $setup;
       
        $installer->startSetup();
       
        $table = $installer->getConnection()
                ->newTable($installer->getTable('customcontact'))
                ->addColumn(
                    'entity_id',
                    \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    null,
                    ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary'=>true ],
                    'Entity Id'
                )
                ->addColumn(
                    'name',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    150,
                    ['unsigned'=>true, 'nullable' => false],
                    'Name'
                )
                ->addColumn(
                    'email',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    150,
                    ['nullable' => false],
                    'Email'
                )
                ->addColumn(
                    'telephone',
                    \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    null,
                    ['unsigned'=>true, 'nullable' => false],
                    'Telephone'
                )
                ->addColumn(
                    'comment',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    '64K',
                    ['nullable' => false],
                    'Comment'
                )
                ->setComment('Custom Contact');
               
        $installer->getConnection()->createTable($table);
       
        $installer->endSetup();
    }
   
}

4. Create a front end router (etc/frontend/routes.xml)
----------------------------------------------
<?xml version="1.0" ?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="customcontact" frontName="customcontact">
            <module name='Krupa_Customcontact'/>
        </route>
    </router>
</config>

5. Create a front end Di.xml file
------------------------------------------------
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   
    <type name="Magento\Contact\Controller\Index\Post">
        <plugin name="custom_contact_action" type="Krupa\Customcontact\Plugin\Post"/>
    </type>
</config>

6. create a Plugin
----------------------------------
<?php

namespace Krupa\Customcontact\Plugin;

class Post
{
    /**
* contact Factory
*
* @var \Krupa\Customcontact\Model\CustomcontactFactory
*/
protected $_contactsFactory;
   
    /**
     * @var \Magento\Framework\Controller\Result\RedirectFactory
     */
    protected $resultRedirectFactory;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $transportBuilder;

    /**
     * Core store config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Post constructor.
     *
     * @param \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilderd
     * @param \Krupa\Customcontact\Model\CustomcontactFactory $contactFactory
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Krupa\Customcontact\Model\CustomcontactFactory $contactFactory,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->_contactsFactory           = $contactFactory;
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->messageManager = $messageManager;
        $this->inlineTranslation = $inlineTranslation;
        $this->transportBuilder = $transportBuilder;
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @param \Magento\Contact\Controller\Index\Post $subject
     * @return $this|void
     */
    public function aroundExecute(
        \Magento\Contact\Controller\Index\Post $subject
    ) {

        $post = $subject->getRequest()->getPostValue();
       // var_dump($post); die;
        if (!$post) {
            return $this->resultRedirectFactory->create()->setPath('customcontact/index/index');
        }
        $this->inlineTranslation->suspend();
        try {
            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($post);

            $error = false;

            if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['comment']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                $error = true;
            }
            /* if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
                $error = true;
            } */
            if ($error) {
                throw new \Exception();
            }
            $contact  = $this->_contactsFactory->create();
            $contact->setName($post['name']);
            $contact->setEmail($post['email']);
            $contact->setTelephone($post['telephone']);
            $contact->setComment($post['comment']);
               
            $contact->save();
           
           /* $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $transport = $this->transportBuilder
                ->setTemplateIdentifier($this->scopeConfig->getValue(\Magento\Contact\Controller\Index\Post::XML_PATH_EMAIL_TEMPLATE, $storeScope))
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($this->scopeConfig->getValue(\Magento\Contact\Controller\Index\Post::XML_PATH_EMAIL_SENDER, $storeScope))
                ->addTo($this->scopeConfig->getValue(\Magento\Contact\Controller\Index\Post::XML_PATH_EMAIL_RECIPIENT, $storeScope))
                ->setReplyTo($post['email'])
                ->getTransport();

            $transport->sendMessage();
            $this->inlineTranslation->resume();*/
            $this->messageManager->addSuccess(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            return $this->resultRedirectFactory->create()->setPath('customcontact/index/index');
        } catch (\Exception $e) {
            //$this->inlineTranslation->resume();
            $this->messageManager->addError(
                __('We can\'t process your request right now. Sorry, that\'s all we know.')
            );
            return $this->resultRedirectFactory->create()->setPath('customcontact/index/index');
        }
    }
}

7. create a front controller index action
--------------------------------------------------------
<?php
namespace Krupa\Customcontact\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $forwardFactory;
    protected $pageFactory;
   
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPagefactory
    ) {
        $this->pageFactory = $resultPagefactory;
        return parent::__construct($context);
    }
   
    public function execute() {
        //echo 'hello ';
        $resultPage = $this->pageFactory->create();
$resultPage->addHandle('contact_index_index'); //loads the layout of module_custom_customlayout.xml file with its name
return $resultPage;        
    }
}

8. Create di.xml file. in etc
--------------------------------------------

<?xml version='1.0' ?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!-- create virtualType ContactGridDataProvider -->
   
    <virtualType name="ContactGridDataProvider" type="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider">
        <arguments>
            <argument name="collection" xsi:type="object" shared="false">Krupa\Customcontact\Model\ResourceModel\Customcontact\Collection</argument>
            <argument name="filterpool" xsi:type="object" shared="false"> ContactGridFilterPool</argument>
        </arguments>
    </virtualType>

 
    <!-- create ContactGridFilterPool -->
   
    <virtualType name="ContactGridFilterPool" type="Magento\Framework\View\Element\UiComponent\DataProvider\FilterPool">
        <arguments>
            <argument name="appliers" xsi:type="array">
                <item name="regular" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter</item>
                <item name="fulltext" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\FulltextFilter</item>
            </argument>
        </arguments>
    </virtualType>


   
    <!-- type for contacts_listing_data_source -->
    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="contacts_listing_data_source" xsi:type="string">Krupa\Customcontact\Model\ResourceModel\Customcontact\Grid\Collection</item>
            </argument>
        </arguments>
    </type>


   
    <!-- simulate Krupa\Customcontact\Model\ResourceModel\Customcontact\Grid\Collection -->
    <virtualType name="Krupa\Customcontact\Model\ResourceModel\Customcontact\Grid\Collection" type ="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
        <arguments>
            <argument name="mainTable" xsi:type="string">customcontact</argument>
<argument name="eventPrefix" xsi:type="string">contact_grid_collection</argument>
            <argument name="eventObject" xsi:type="string">contact_grid_collection</argument>
            <argument name="resourceModel" xsi:type="string">Krupa\Customcontact\Model\ResourceModel\Customcontact\Collection</argument>
        </arguments>
    </virtualType>


   
</config>

9.  create admin route (etc/adminhtml/routes.xml)
------------------------------------------------------------------
<?xml version="1.0" ?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="customcontact" frontName="customcontact">
            <module name="Krupa_Customcontact" before="Magento_Backend"/>
        </route>
    </router>
</config>

10. Create admin menu
-------------------------------
<?xml version="1.0" ?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instamce" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
    <menu>
        <add id ="Krupa_Customcontact::contacts" title="Contact Manager" module="Krupa_Customcontact" sortOrder='10' resource="Krupa_Customcontact::contacts" />
        <add id ="Krupa_Customcontact::contact" title="contacts" module="Krupa_Customcontact" sortOrder='1' resource="Krupa_Customcontact::contact" action="customcontact/index/index" parent="Krupa_Customcontact::contacts" />     
    </menu>
</config>

11. Create admin action
--------------------------------------------
<?php
namespace Krupa\Customcontact\Controller\Adminhtml\Index;

class Index extends \Magento\Backend\App\Action
{
   
     /**
     * Page result factory
     *
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $_resultPageFactory; 
    /**
     * Page factory
     *
     * @var \Magento\Backend\Model\View\Result\Page
     */
    protected $_resultPage;
   
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
       
    ){
         parent::__construct($context);
         $this->_resultPageFactory = $resultPageFactory;
       
    }
   
    public function execute()
    {
        /* echo 'hello admin';
        exit; */
$this->_setPageData();
        return $this->getResultPage();
    }
   
    public function getResultPage(){
        if(is_null($this->_resultPage)){
            $this->_resultPage = $this->_resultPageFactory->create();
        }
        return $this->_resultPage;
    }
   
    public function _setPageData(){
        $resultPage = $this->getResultPage();
        $resultPage->setActiveMenu('Krupa_Customcontact::contacts');
       
$title = 'View Contacts';
$resultPage->getConfig()->getTitle()->prepend($title);
       
        $resultPage->addBreadcrumb(__('Krupa'), __('Krupa'));
        $resultPage->addBreadcrumb(__('Contacts'), __('View Contacts'));

        return $this;
    }
   
}

12. Create admin layout (view/adminhtml/layout/customcontact_index_index)
--------------------------------------------------------------------------
<?xml version="1.0" ?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle='styles'/>
   
    <body>
       
        <referenceBlock name='menu'>
            <action method='setActiveMenu'>
                <argument name='itemId' xsi:type='string'> Krupa_Customcontact::contacts</argument>
            </action>
        </referenceBlock>
       
        <referenceBlock name='page.title'>
            <action method='setTitleClass'>
                <argument name='class' xsi:type='string'>complex</argument>
            </action>
        </referenceBlock>
       
        <referenceContainer name='content'>
            <uiComponent name='contacts_listing' />
        </referenceContainer>
       
    </body>
   
</page>

12. Create Ui listing for grid (view/adminhtml/ui_component/contacts_listing.xml)
----------------------------------------------------------------------
<?xml version='1.0' ?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
   
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">contacts_listing.contacts_listing_data_source</item>
            <item name="deps" xsi:type="string">contacts_listing.contacts_listing_data_source</item>   
        </item>
        <item name="spinner" xsi:type="string">contact_colums</item>
       
    </argument>
   
    <dataSource name="contacts_listing_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">ContactGridDataProvider</argument>
            <argument name="name" xsi:type="string">contacts_listing_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">entity_id</argument>
            <argument name="requestFieldName" xsi:type="string">entity_id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="update_url" xsi:type="url" path="mui/index/render" />
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
            </item>
        </argument>
    </dataSource>
   
    <container name="listing_top">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="template" xsi:type="string">ui/grid/toolbar </item>
            </item>
        </argument>
       
        <bookmark name="bookmarks">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="namespace" xsi:type="string">contacts_listing</item>
                    </item>
                </item>
            </argument>
        </bookmark>
       
        <component name="columns_control">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="columnsData" xsi:type="array">
                        <item name="provider" xsi:type="string">
                            contacts_listing.contacts_listing.contact_colums
                        </item>
                    </item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/controls/columns</item>
                    <item name="displayArea" xsi:type="string">dataGridAction</item>
                </item>
            </argument>
        </component>
       
        <exportButton name="export_button">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="selectProvider" xsi:type="array">
                        contacts_listing.contacts_listing.contact_colums.ids
                    </item>
                </item>
            </argument>           
        </exportButton>
       
        <filterSearch name="fulltext" />
        <filters name="listing_filters"/>
             
        <paging name="listing_paging">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">contacts_listing.contacts_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.paging</item>
                    </item>
                    <item name="selectProvider" xsi:type="string">contacts_listing.contacts_listing.contact_colums.ids</item>
                </item>
            </argument>
        </paging>
       
    </container>
   
    <columns name="contact_colums">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="storageConfig" xsi:type="array">
                    <item name="provider" xsi:type="string">contacts_listing.contacts_listing.listing_top.bookmarka</item>
                    <item name="namespace" xsi:type="string">current</item>
                </item>
           
                <!-- <item name="editorConfig" xsi:type="array">
                    <item name="selectorProvider" xsi:type="string">contacts_listing.contacts_listing.contact_colums.ids</item>
                    <item name="enabled" xsi:type="boolean"> true</item>
                    <item name="indexField" xsi:type="string">entity_id</item>
                    <item name="clientConfig" xsi:type="array">
                        <item name="saveUrl" xsi:type="url" path="events/events/inlineEdit"/>
                        <item name="ValidateBeforeSave" xsi:type="boolean">true</item>
                    </item>
                </item> -->
               
                <item name="childDefaults" xsi:type="array">
                    <item name="fieldAction" xsi:type="array">
                        <item name="provider" xsi:type="string">contacts_listing.contacts_listing.contact_colums_editor</item>
                        <item name="target" xsi:type="string">startEdit</item>
                        <item name="params" xsi:type="array">
                            <item name="0" xsi:type="string">${ $.$data.rowIndex }</item>
                            <item name="1" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">contacts_listing.contacts_listing.listing_top.bookmarks</item>
                        <item name="root" xsi:type="string">columns.${ $.index }</item>
                        <item name="namespace" xsi:type="string">current.${ $.storageConfig.root}</item>
                    </item>
                </item>
            </item>
        </argument>
       
        <selectionsColumn name='ids'>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="resizeEnabled" xsi:type="boolean">false</item>
                    <item name="resizeDefaultWidth" xsi:type="string">55</item>
                    <item name="indexField" xsi:type="string">entity_id</item>
                </item>
            </argument>
        </selectionsColumn>
       
        <column name="entity_id">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">textRange</item>
                    <item name="sorting" xsi:type="string">asc</item>
                    <item name="label" xsi:type="string" translate="true">ID</item>
                </item>
            </argument>
        </column>
       
        <column name="name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Name</item>
                </item>
            </argument>
        </column>
       
        <column name="email">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <!-- <item name="visible" xsi:type="boolean">true</item> -->
                    <item name="label" xsi:type="string" translate="true">E-mail</item>
<!-- <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item> -->
                    <item name="dataType" xsi:type="string">text</item>
                </item>
            </argument>
        </column>
        <column name="telephone">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Telephone</item>
<!-- <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item> -->
                    <item name="dataType" xsi:type="string">text</item>
                </item>
            </argument>
        </column>
<column name="comment">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Comment</item>
<!-- <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item> -->
                    <item name="dataType" xsi:type="string">text</item>
                </item>
            </argument>
        </column>     
    </columns>
   
</listing>

13. Create model
----------------------------
<?php
namespace Krupa\Customcontact\Model;

class Customcontact extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface {
   
    protected $_cacheTag ='customcontact';
   
    protected $_eventPrefix ='customcontact';
   
    protected function _construct(){
        $this->_init('Krupa\Customcontact\Model\ResourceModel\Customcontact');
    }
   
    /**
     * Get identities
     *
     * @return array
     */
public function getIdentities()
{
return [self::CACHE_TAG .'_'.$this->getId()];
}
/**
     * get entity default values
     *
     * @return array
     */
public function getDefaultvalues()
{
$values =[];
return $values;
}
}

14. Create resource model
---------------------------------------
<?php

namespace Krupa\Customcontact\Model\ResourceModel;

class Customcontact extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
                       
{
    public function __construct(
        \Magento\Framework\Model\ResourceModel\Db\Context $context
    ) {
        parent::__construct($context);
    }
   
    protected function _construct()
    {
        $this->_init('customcontact','entity_id');
    }
   
   
public function getConatctNameById($id)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTabel(),'name')
->where('entity_id : (int)$id');
$binds = ['entity_id'=> (int)$id];
return $adapter->fetchOne($select,$binds);
}


protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
{
return parent::_beforeSave($object);
}
}

15. create collection
-------------------------
<?php

namespace Krupa\Customcontact\Model\ResourceModel\Customcontact;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * ID Field Name
     * 
     * @var string
     */
protected $_idFieldName ='entity_id';
  /**
     * Event prefix
     * 
     * @var string
     */

protected $_eventPrefix = 'contact_collection';
/**
     * Event object
     * 
     * @var string
     */

protected $_eventObject ='contact_collection';
    
      
    protected function _construct()
    {
        $this->_init('Krupa\Customcontact\Model\Customcontact','Krupa\Customcontact\Model\ResourceModel\Customcontact');
    }
    
    /**
* Get SQL for get recoed count.
* Extra GROUP BY strip added. 
*
* @return \Magento\Framework\DB\Select
*/

public function getSelectCountSql()
{
$countSelect = Parent::getSelectCountSql();
return $countSelect;
}

/**
     * @param string $valueField
     * @param string $labelField
     * @param array $additional
     * @return array
     */
    protected function _toOptionArray($valueField = 'entity_id', $labelField = 'name', $additional = [])
    {
        return parent::_toOptionArray($valueField, $labelField, $additional);
    }
}

16 create grid collection
--------------------------------
<?php
namespace Krupa\Customcontact\Model\ResourceModel\Customcontact\Grid;

class Collection extends \Krupa\Customcontact\Model\ResourceModel\Customcontact\Collection implements \Magento\Framework\Api\Search\SearchResultInterface
{
/**
* Aggregations
*
    * @var \Magento\Framework\Search\AggregationInterface
*/
protected $_aggregations;

/**
* constructor
*
* @ param \magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory
* @ param \Psr\Log\LoggerInterface $logger
* @ param \magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchstrategy
* @ param \magento\Framework\Event\ManagerInterface $eventManager
* @ param $mainTable
* @ param $eventPrefix
* @ param $eventObject
* @ param $resourceModel
* @ param $model
* @ param $connection
*
* @ param \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource
*/
public function __construct(
\magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
\Psr\Log\LoggerInterface $logger,
\magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchstrategy,
\magento\Framework\Event\ManagerInterface $eventManager,
$mainTable,
$eventPrefix,
    $eventObject,
    $resourceModel,
    $model ='Magento\Framework\View\Element\UiComponnet\DataProvider\Document',
    $connection = null,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource =null
)
{
parent::__construct($entityFactory,$logger,$fetchstrategy,$eventManager, $connection, $resource);
$this->_eventPrefix = $eventPrefix;
$this->_eventObject = $eventObject;
$this->_init($model,$resourceModel);
$this->setMainTable($mainTable);

}
/**
*
* @ return \Magento\Framework\Search\AggregationInterface
*
*/

public function getAggregations()
{
return $this->_aggregations;
}

/**
* @ param \Magento\Framework\Api\Search\SearchResultInterface
* @ return $this
*
*/

public function setAggregations($aggregations)
{
$_aggregations = $aggregations;
}

/**
* Retrive all ids for collection
* Backward Compatibility with EAV collection
*
* @param int $limit
* @param int $offset
* @return array
*
*/

public function getAllIds($limit=null,$offset=null)
{
return $this->getConnection()->fetchCol($this->_getAllIdsSelect($limit,$offset),$this->_bindParams);
}

/**
* Get Search Criteria.
*
* @ return \Magento\Framework\Api\SearchCriteriaInterface |null
*
*/
public function getSearchCriteria()
{
return null;
}

/**
* Set Search Criteria
*
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return $this
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
*/
public function setSearchCriteria(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria =null)
{
return $this;
}

/**
* Get total count.
*
* @return int
*
*/

public function getTotalCount()
{
return $this->getSize();
}

/**
* set total count.
*
* @param int $totalCount
* @return $this
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
*/
public function setTotalCount($totalCount)
{
return $this;
}

/**
* Set item list.
*
* @param \Magento\Framework\Api\ExtensibleDataInterface[] $items
* @retuen Sthis
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
*/

public function setItems(array $items = null)
{
return $this;
}
}




Thursday, 10 August 2017

Autologin : auto login your customers from magento admin

For that we need to create custom module for that.

Here Namespace is : Krupa
Module name is : Autologin

1) Create Module declaration file : Krupa_Autologin.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Krupa_Autologin>
            <active>true</active>
            <codePool>local</codePool>
        </Krupa_Autologin>
    </modules>
</config>

2) Create module's configuration file under ( // app/code/local/Krupa/Autologin/etc/config.xml)

In this file I have overrite magento admin customer edit file and create custom  front controller.

<?xml version="1.0"?>
<config>
    <modules>
        <Krupa_Autologin>
            <version>0.1.0</version>
        </Krupa_Autologin>
    </modules>
    <frontend>
        <routers>
            <autologin>
                <use>standard</use>
                <args>
                    <module>Krupa_Autologin</module>
                    <frontName>autologin</frontName>
                </args>
            </autologin>
        </routers>
     
    </frontend>
    <global>
       <blocks>
         <adminhtml>
                <rewrite>
                    <customer_edit>Krupa_Autologin_Block_Adminhtml_Customer_Edit</customer_edit>
                </rewrite>
            </adminhtml>
        </blocks>
         </global>
</config>

3)  Create a block file to add button and it's click event on following path (//app/code/local/Krupa/Autologin/Block/Adminhtml/Customer/Edit.php )

<?php
class Krupa_Autologin_Block_Adminhtml_Customer_Edit extends Mage_Adminhtml_Block_Customer_Edit
{
    public function __construct()
    {
        $this->_objectId = 'id';
        $this->_controller = 'customer';

        if ($this->getCustomerId() &&
            Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/create')) {
            $this->_addButton('order', array(
                'label' => Mage::helper('customer')->__('Create Order'),
                'onclick' => 'setLocation(\'' . $this->getCreateOrderUrl() . '\')',
                'class' => 'add',
            ), 0);
        }
        if ($this->getCustomerId()) {
            $this->_addButton('autologin', array(
                'label' => Mage::helper('customer')->__('Autologin'),
                'onclick' => 'setLocation(\'' . $this->getAutologinUrl() . '\')',
                'class' => 'add',
            ),1);
        }

        parent::__construct();

        $this->_updateButton('save', 'label', Mage::helper('customer')->__('Save Customer'));
        $this->_updateButton('delete', 'label', Mage::helper('customer')->__('Delete Customer'));

        if (Mage::registry('current_customer')->isReadonly()) {
            $this->_removeButton('save');
            $this->_removeButton('reset');
        }

        if (!Mage::registry('current_customer')->isDeleteable()) {
            $this->_removeButton('delete');
        }
    }

    public function getAutologinUrl()
    {
        return $this->getUrl('autologin/index/loginascustomer',array('customer_id' => $this->getCustomerId()));
    }
 
}

4) Now Create front controller on following path . (\\app\code\local\Krupa\Autologin\controllers\IndexController.php )

<?php
class Krupa_Autologin_IndexController extends Mage_Core_Controller_Front_Action
{
    public function loginascustomerAction()
    {
        
  $session = Mage::getSingleton('customer/session');
         $id = (int) trim($this->getRequest()->getParam('customer_id'));
       try{ 
        if($id){
                    $customer = Mage::getModel('customer/customer')->load($id);
                    $session->setCustomerAsLoggedIn($customer);
                    }else{
                    throw new Exception ($this->__('The login attempt was unsuccessful. Some parameter is missing'));
                }
            }catch (Exception $e){
                $session->addError($e->getMessage());
            }
           
           $this->_redirect('customer/account/');
    }
}


That's it. Hope It may helpful to you :) 








Wednesday, 2 August 2017

Git Command

git checkout (branch name)
git pull origin (branch name)
git status
git add . OR git add app/code/local/CP/Store/Model/System/Store.php
git commit -m "write message(first task id and then message)"
git push origin (branch name)





merge stpes
-----
git checkout Development
git pull origin Development
git merge (last push branch name)
git push origin Development



to create a branch
 git checkout -b

Thursday, 22 June 2017

get attribute id from attribute code.

If you want to get attribute id from attribute code, use following code.

 $attributeId = Mage::getResourceModel('eav/entity_attribute')
    ->getIdByCode('catalog_product', 'small_image');



Thursday, 15 September 2016

Magento programatically clear cache from particular section.


If your magento's cache is enable and for particular section your dynamically content not reflect and remains same for every category or product page  use following code.

<?php Mage::app()->saveUseCache('block_html'); ?>

If you just need to refresh one type, Bock Html OutPut for instance, you just need to use this :
$type= "block_html";
Mage::app()->getCacheInstance()->cleanType($type);

 

That's it. Hope it will help you  :)

Thursday, 11 December 2014

Export Category with it's id in magento

<?php

ini_set('memory_limit', '-1');
set_time_limit(0);
    require_once('app/Mage.php');
    umask(0);
    Mage::app('default');
    define('MAGENTO', realpath(dirname(__FILE__)));
   
$file_path =  MAGENTO . '/var/export/catwithid.csv';
$mage_csv = new Varien_File_Csv();

$products_row = array();
$products_row['0']['categoryid'] = 'categoryid';
$products_row['0']['categoryname'] = 'categoryname';




$category = Mage::getModel ( 'catalog/category' );
    $tree = $category->getTreeModel ();
    $tree->load ();
   
    $ids = $tree->getCollection ()->getAllIds ();

foreach ($ids as $id)
{

    $data['categoryid'] = $id;
   
    $data['categoryname'] =  $category->load($id)->getName();

  $products_row[] = $data;
   
}
 




    $mage_csv->saveData($file_path, $products_row);
    echo "Please find test1.csv file in your folder.....";
   
   
    ?>