Thursday 26 April 2018

How to reindex | Upgrade | static-content:deploy | Cache flush | Cache clean | Important commands in Magento 2

You need to put this command on CMD | Terminal


For Upgrade data in Magento 2
php -dmemory_limit=5G bin/magento setup:upgrade 
For code compile
php bin/magento setup:di:compile
For Reindex data in Magento 2
php -dmemory_limit=5G bin/magento indexer:reindex
For Static Content Deploy data  in Magento 2
php -dmemory_limit=5G bin/magento setup:static-content:deploy -f
For Flush Cache in Magento 2
php -dmemory_limit=5G bin/magento cache:flush
For Clean Cache in Magento 2
php -dmemory_limit=5G bin/magento cache:clean
For generate a new image cache
bin/magento catalog:image:resize 
For Files and Directory Permission
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
find var pub/static pub/media  generated/ app/etc -type f -exec chmod g+w {} \;
find var pub/static pub/media generated/ app/etc -type d -exec chmod g+ws {} \;
chown -R ubuntu:www-data .
chmod u+x bin/magento
chmod -R 777 . 

Thursday 19 April 2018

Calendar.setup Calendar popup not display proper on Magento admin panel


HTML Code

<td class="label"><label for="tran_date">Date</label></td>
<td class="value">
    <input name="deposit[created_at]" id="tran_date" type="text" class="input-text" value="<?php echo Mage::getModel('core/date')->gmtDate('m/d/Y'); ?>"/>
    <img src="<?php echo $this->getSkinUrl('images/grid-cal.gif') ?>" class=""
        id="tran_date_trig"/>
    <div id="calendar--flat"></div>
</td>
</tr>
SCRIPT
 <script type="text/javascript">
// <![CDATA[
Calendar.setup({
flat: 'calendar--flat',
ifFormat: '%m/%e/%Y',
button: 'tran_date_trig',
align: 'Bl',
singleClick: true,
onSelect: function(dateText,selectedDate) {
    jQuery('#tran_date').val(selectedDate);
    jQuery('#calendar--flat').hide();
}
});
// ]]>
</script>

CSS

#calendar--flat {
    position: absolute;


Monday 16 April 2018

Remove / Disable checkbox Checked / unChecked when click on click row in magento 1.9

Need to change code in grid.js (magento\js\mage\adminhtml\grid.js)

Replace code from

rowMouseClick : function(event){
        if(this.rowClickCallback){
            try{
                this.rowClickCallback(this, event);
            }
            catch(e){}
        }
        varienGlobalEvents.fireEvent('gridRowClick', event);
    },
TO

rowMouseClick : function(event){
        var element = Event.findElement(event, 'table');
        if(element.id!='depositGrid_table') {
            if(this.rowClickCallback){
                try{
                    this.rowClickCallback(this, event);
                }
                catch(e){}
            }
        }
        varienGlobalEvents.fireEvent('gridRowClick', event);
    },

Saturday 14 April 2018

SQLSTATE[HY000]: General error: 1 Can't create/write to file '/tmp/#sql_83d_0.MYI' (Errcode: 28) Magento / PHP

Problem can be connected with inodes. Maybe you have too many small files and your inodes are full. You can check inode status with df -i 

Thursday 12 April 2018

How to Find / Search a file using CMD / Terminal Command Linux Ubuntu


1. Find file from computer using CMD / Terminal Command

sudo find / -name index.php
2. Find file from Specific Directory using CMD / Terminal Command

sudo find /var/www/html/ -name index.php

Saturday 10 March 2018

How to display product associated categories & filter product grid by categories in admin panel



Step 1.

Copy file from "app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php" to "app/code/local/Mage/Adminhtml/Block/Catalog/Product/Grid.php"
Step 2 : Add Column for category.

protected function _prepareColumns() {
    ......
    ......
    ......
    $this->addColumn(
        'category_id',
            array(
             'header'                    => Mage::helper('jaydip_kansagra')->__('Category'),
             'width'                     => '100px',
             'index'                     => 'category_ids',
             'type'                      => 'options',
             'options'                   => $this->getCategoriesOptions(),
             'filter_condition_callback' => array($this, '_callbackCategoryFilter'),
             'renderer'                  => 'Jaydip_Kansagra_Block_Adminhtml_Renderer_Categories'
           )
    );
    ......
    ......
    ......
Step 3 : Create new functions in this grid file.

protected function getCategoriesOptions() {
   $categoriesOptions = array();
   $this->prepareCategoriesOptions($this->_getCategories()->getNodes(), $categoriesOptions);
   return $categoriesOptions;
}

protected function _getCategories() {
   $storeId = (int) $this->getRequest()->getParam('store');
   if ($storeId) {
       $store = Mage::app()->getStore($storeId);
       $parent = $store->getRootCategoryId();
   } else {
       $parent = Mage_Catalog_Model_Category::TREE_ROOT_ID;
   }
   $tree = Mage::getResourceModel('catalog/category_tree');
   /* @var $tree Mage_Catalog_Model_Resource_Category_Tree */
   $nodes = $tree->loadNode($parent)
        ->loadChildren(0)
        ->getChildren();
   $tree->addCollectionData(null, true, $parent, true, false);
   return $nodes;
}

protected function prepareCategoriesOptions($nodes, &$options) {
    /** @var $node Varien_Data_Tree_Node */
    foreach ($nodes as $node) {
        if ($node->getName()) {
            $options[$node->getId()] = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $node->getLevel() - 1) . $node->getName();
        }
        if ($node->hasChildren()) {
            $this->prepareCategoriesOptions($node->getAllChildNodes(), $options);
        }
    }
    return $options;
}

*********Or For without category tree view**********

protected function getCategoriesOptions() {
   $categoriesOptions = array();
   $this->prepareCategoriesOptions($this->_getCategories()->getNodes(), $categoriesOptions);
   return $categoriesOptions;
}
Step 4 : Create new function for filter in this file protected method _callbackCategoryFilter

protected function _callbackCategoryFilter($collection, $column)
{
    if (!$value = $column->getFilter()->getValue()) {
        return null;
    }
    $collection->joinField(
        'category_id',
        'catalog/category_product',
        'category_id',
        'product_id = entity_id',
        '{{table}}.category_id=' . $column->getFilter()->getValue(),
        'inner'
    );
Step 5 : Create renderer file in any extension

class Jaydip_Kansagra_Block_Adminhtml_Renderer_Categories extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {
    public function render(Varien_Object $row) {
     
        $productCategories = array();
        $product = Mage::getModel('catalog/product')->load($row->getData('entity_id'));
        $categories = $product->getCategoryCollection()->addAttributeToSelect('name');
        foreach ($categories as $category) {
            array_push($productCategories, $category->getName());
        }
        return implode(',', $productCategories);
    } 

Tuesday 27 February 2018

How to create simple and custom order report in magento 1.9


Step 1 : Add Menu on adminhtml.xml file : app/code/local/Jaydip/Kansagra/etc/adminhtml.xml

<config>
    <menu>
        <report>
            <children>
                <jobber translate="title">
                    <title>Jobber</title>
                    <children>
                        <jaydip_kansagra_summary translate="title">
                            <title>Jobber Summary</title>
                            <action>adminhtml/kansagra_reports/summary</action>
                            <sort_order>10</sort_order>
                        </jaydip_kansagra_summary>
                    </children>
                </jobber>
            </children>
        </report>
    </menu>
    <acl>
        ....
        ....
        ....
    </acl>
</config>
Step 2 : Create Report Controller on your model controller file : app/code/local/Jaydip/Kansagra/controllers/Adminhtml/Kansagra/ReportsController.php

<?php
class Jaydip_Kansagra_Adminhtml_Kansagra_ReportsController extends Mage_Adminhtml_Controller_Action {
       
    /**
     * Initialize titles and navigation breadcrumbs
     * @return Jaydip_Reports_Adminhtml_ReportsController
     */
    protected function _initAction() {
        $this->_title($this->__('Reports'))->_title($this->__('Sales'))->_title($this->__('Summary'));
        $this->loadLayout()
                ->_setActiveMenu('report/sales')
                ->_addBreadcrumb(Mage::helper('jaydip_kansagra')->__('Reports'), Mage::helper('jaydip_kansagra')->__('Reports'))
                ->_addBreadcrumb(Mage::helper('jaydip_kansagra')->__('Jobber'), Mage::helper('jaydip_kansagra')->__('Jobber'));
        return $this;
    }
    /**
     * Prepare blocks with request data from our filter form
     * @return Jaydip_Reports_Adminhtml_ReportsController
     */
    protected function _initReportAction($blocks) {
        if (!is_array($blocks)) {
            $blocks = array($blocks);
        }
        $requestData = Mage::helper('adminhtml')->prepareFilterString($this->getRequest()->getParam('filter'));
        $requestData = $this->_filterDates($requestData, array('fromdate', 'todate'));
        $params = $this->_getDefaultFilterData();
        foreach ($requestData as $key => $value) {
            if (!empty($value)) {
                $params->setData($key, $value);
            }
        }
        foreach ($blocks as $block) {
            if ($block) {
                $block->setFilterData($params);
            }
        }
        return $this;
    }
    protected function _getDefaultFilterData() {
        return new Varien_Object(array(
            'fromdate' => '',
            'todate' => '',
            'salesperson' => 0,
        ));
    } 
   
    public function summaryAction() {
        $this->_initAction();
        $this->_title($this->__('Summary'));
        $gridBlock = $this->getLayout()->getBlock('adminhtml_reports_summary.grid');
        $filterFormBlock = $this->getLayout()->getBlock('grid.filter.form');
        $this->_initReportAction(array(
            $gridBlock,
            $filterFormBlock
        ));
        $this->renderLayout();
    }
   
    public function detailAction() {
        $this->_initAction();
        $this->_title($this->__('Detail'));
        $gridBlock = $this->getLayout()->getBlock('adminhtml_detail.grid');
        $filterFormBlock = $this->getLayout()->getBlock('grid.filter.form');
        $this->_initReportAction(array(
            $gridBlock,
            $filterFormBlock
        ));
        $this->renderLayout();
    }
}
Step 3 : Create admin layout xml file : app/design/adminhtml/default/default/layout/jaydip_kansagra.xml

<layout>
.....
.....
.....
<adminhtml_kansagra_reports_summary>
        <reference name="content">
            <block type="jaydip_kansagra/adminhtml_reports_summary" template="report/grid/container.phtml" name="jaydip_kansagra_reports_summary_grid_container">
                <block type="jaydip_kansagra/adminhtml_reports_filter_formsummary" name="grid.filter.form" />
            </block>
        </reference>
    </adminhtml_kansagra_reports_summary>
</layout> 
Step 4 : Create block file : app/code/local/Jaydip/Kansagra/Block/Adminhtml/Reports/Summary.php

class Jaydip_Kansagra_Block_Adminhtml_Reports_Summary extends Mage_Adminhtml_Block_Widget_Grid_Container {
    /**
     * This is your module alias
     */
    protected $_blockGroup = 'jaydip_kansagra';
    /**
     * This is the controller's name (this block)
     */
    protected $_controller = 'adminhtml_reports_summary';
    /*
      Note: the grid block's name would prepare from $_blockGroup and $_controller with the suffix '_grid'.
      So the complete block would called jaydip_kansagra/adminhtml_report_grid . As you already guessed it,
      this will resolve to the class Jaydip_Reports_Adminhtml_Report_Grid .
     */
    /**
     * Prepare grid container, add and remove additional buttons
     */
    public function __construct() {
        // The head title of the grid
        $this->_headerText = Mage::helper('jaydip_kansagra')->__('Summary');
        $this->setTemplate('report/grid/container.phtml');
        parent::__construct();
        $this->_removeButton('add');
        $this->addButton('filter_form_submit', array(
            'label' => Mage::helper('jaydip_kansagra')->__('Show Report'),
            'onclick' => 'filterFormSubmit()'
        ));
    }
    /**
     * This function will prepare our filter URL
     * @return string
     */
    public function getFilterUrl() {
        $this->getRequest()->setParam('filter', null);
        return $this->getUrl('*/*/summary', array('_current' => true));
    }
}
Step 5 : Create Grid file : app/code/local/Jaydip/Kansagra/Block/Adminhtml/Reports/Summary/Grid.php

<?php
class Jaydip_Kansagra_Block_Adminhtml_Reports_Summary_Grid extends Mage_Adminhtml_Block_Widget_Grid {
    /**
     * Basic setup of our grid
     */
    public function __construct() {
        parent::__construct();
        $this->setPagerVisibility(false);
        $this->setUseAjax(false);
        $this->setFilterVisibility(false);
        $this->setDefaultLimit(50);
        $this->setEmptyCellLabel(Mage::helper('jaydip_kansagra')->__('No records found.'));
        $this->setId('mxReportsGrid');
        // set our grid to obtain totals
        $this->setCountTotals(true);
    }
    /**
     * Return totals data
     * Count totals if it's not previously counted and set to retrieve
     * @return Varien_Object
     */
    public function getTotals() {
        $totals = new Varien_Object();
        $fields = array(
            'jobberprofit' => '',
            'jobberamount' => '',
            'invoiceamount' => '',
        );
        foreach ($this->getCollection() as $item) {
            foreach ($fields as $field => $value) {
                $fields[$field] += $item->getData($field);
            }
        }
        //First column in the grid
        $fields['sortorder'] = 'Totals';
        $totals->setData($fields);
        return $totals;
    }
    // prepare columns and collection   
    /**
     * Prepare our grid's columns to display
     * @return Jaydip_Kansagra_Block_Adminhtml_Report_Summary_Grid
     */
    protected function _prepareColumns() {
       
        $currencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
       
        $this->addColumn('created_at', array(
            'header' => Mage::helper('sales')->__('Date'),
            'index' => 'created_at',
            'type' => 'datetime',
            'width' => '120'
        ));
       
        $this->addColumn('company', array(
            'header' => Mage::helper('sales')->__('Company name'),
            'index' => 'company',
            'align' => 'right',
            'width' => '50'
        ));
        $this->addColumn('address', array(
            'header' => Mage::helper('sales')->__("Full Address"),
            'index' => 'street',
            'width' => '210'
        ));
        // add export types
        //$this->addExportType('*/*/exportCSV', Mage::helper('jaydip_kansagra')->__('CSV'));
        return parent::_prepareColumns();
    }
    /**
     * Prepare our collection which we'll display in the grid
     * First, get the resource collection we're dealing with, with our custom filters applied.
     * In case of an export, we're done, otherwise calculate the totals
     * @return Jaydip_Kansagra_Block_Adminhtml_Report_Summary_Grid
     */
    protected function _prepareCollection() {
       
        $data = $this->getFilterData();
       
        $datefrom = Mage::getModel('core/date')->gmtDate('Y-m-d',strtotime($data->fromdate));
        $dateto = Mage::getModel('core/date')->gmtDate('Y-m-d',strtotime($data->todate));
        $salesperson = $data->salesperson;
        $orders = Mage::getModel('sales/order')->getCollection()
                    ->addFieldToFilter('entity_id', array('eq' => 0));
        $this->setCollection($orders);
        //echo $this->showExtraCounts($collection);
        return parent::_prepareCollection();
    }
}
Step 6 : Create Filter Form file : app/code/local/Jaydip/Kansagra/Block/Adminhtml/Reports/Filter/Formsummary.php

<?php
class Jaydip_Kansagra_Block_Adminhtml_Reports_Filter_Formsummary extends Mage_Adminhtml_Block_Widget_Form {
    /**
     * This will contain our form element's visibility
     * @var array
     */
    protected $_fieldVisibility = array();
    /**
     * Field options
     * @var array
     */
    protected $_fieldOptions = array();
    /**
     * Sets a form element to be visible or not
     * @param string $fieldId
     * @param bool $visibility
     * @return Jaydip_Kansagra_Block_Adminhtml_Report_Filter_Form
     */
    public function setFieldVisibility($fieldId, $visibility) {
        $this->_fieldVisibility[$fieldId] = $visibility ? true : false;
        return $this;
    }
    /**
     * Returns the field is visible or not. If we hadn't set a value
     * for the field previously, it will return the value defined in the
     * defaultVisibility parameter (it's true by default)
     * @param string $fieldId
     * @param bool $defaultVisibility
     * @return bool
     */
    public function getFieldVisibility($fieldId, $defaultVisibility = true) {
        if (isset($this->_fieldVisibility[$fieldId])) {
            return $this->_fieldVisibility[$fieldId];
        }
        return $defaultVisibility;
    }
    /**
     * Set field option(s)
     * @param string $fieldId
     * @param string|array $option if option is an array, loop through it's keys and values
     * @param mixed $value if option is an array this option is meaningless
     * @return Jaydip_Kansagra_Block_Adminhtml_Report_Filter_Form
     */
    public function setFieldOption($fieldId, $option, $value = null) {
        if (is_array($option)) {
            $options = $option;
        } else {
            $options = array($option => $value);
        }
        if (!isset($this->_fieldOptions[$fieldId])) {
            $this->_fieldOptions[$fieldId] = array();
        }
        foreach ($options as $key => $value) {
            $this->_fieldOptions[$fieldId][$key] = $value;
        }
        return $this;
    }
    /**
     * Prepare our form elements
     * @return Jaydip_Kansagra_Block_Adminhtml_Report_Filter_Form
     */
    protected function _prepareForm() {
        // inicialise our form
        $actionUrl = $this->getCurrentUrl();
        $form = new Varien_Data_Form(array(
            'id' => 'filter_form',
            'action' => $actionUrl,
            'method' => 'get'
        ));
        // set ID prefix for all elements in our form
        $htmlIdPrefix = 'jaydip_kansagra_jobber_';
        $form->setHtmlIdPrefix($htmlIdPrefix);
        // create a fieldset to add elements to
        $fieldset = $form->addFieldset('base_fieldset', array('legend' => Mage::helper('jaydip_kansagra')->__('Filter')));
        // prepare our filter fields and add each to the fieldset
        // date filter
        $dateFormatIso = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
       
        $fieldset->addField('fromdate', 'date', array(
            'name' => 'fromdate',
            'format' => $dateFormatIso,
            'image' => $this->getSkinUrl('images/grid-cal.gif'),
            'label' => Mage::helper('jaydip_kansagra')->__('From Date'),
            'title' => Mage::helper('jaydip_kansagra')->__('From Date'),
            'required' => true
        ));
       
        $fieldset->addField('todate', 'date', array(
            'name' => 'todate',
            'format' => $dateFormatIso,
            'image' => $this->getSkinUrl('images/grid-cal.gif'),
            'label' => Mage::helper('jaydip_kansagra')->__('To Date'),
            'title' => Mage::helper('jaydip_kansagra')->__('To Date'),
            'required' => true
        ));
       
        $fieldset->addField('salesperson', 'select', array(
            'name' => 'salesperson',
            'values' => Mage::getModel('admin/user')->getAdminUsersArrByRole('Sales Person'),
            'label' => Mage::helper('jaydip_kansagra')->__('Jobbers'),
            'required' => true,
        ));
        $form->setUseContainer(true);
        $this->setForm($form);
        return $this;
    }
    /**
     * Inicialise form values
     * Called after prepareForm, we apply the previously set values from filter on the form
     * @return Jaydip_Kansagra_Block_Adminhtml_Report_Filter_Form
     */
    protected function _initFormValues() {
        $filterData = $this->getFilterData();
        $this->getForm()->addValues($filterData->getData());
        return parent::_initFormValues();
    }
    /**
     * Apply field visibility and field options on our form fields before rendering
     * @return Jaydip_Kansagra_Block_Adminhtml_Report_Filter_Form
     */
    protected function _beforeHtml() {
        $result = parent::_beforeHtml();
        $elements = $this->getForm()->getElements();
        // iterate on our elements and select fieldsets
        foreach ($elements as $element) {
            $this->_applyFieldVisibiltyAndOptions($element);
        }
        return $result;
    }
    /**
     * Apply field visibility and options on fieldset element
     * Recursive
     * @param Varien_Data_Form_Element_Fieldset $element
     * @return Varien_Data_Form_Element_Fieldset
     */
    protected function _applyFieldVisibiltyAndOptions($element) {
        if ($element instanceof Varien_Data_Form_Element_Fieldset) {
            foreach ($element->getElements() as $fieldElement) {
                // apply recursively
                if ($fieldElement instanceof Varien_Data_Form_Element_Fieldset) {
                    $this->_applyFieldVisibiltyAndOptions($fieldElement);
                    continue;
                }
                $fieldId = $fieldElement->getId();
                // apply field visibility
                if (!$this->getFieldVisibility($fieldId)) {
                    $element->removeField($fieldId);
                    continue;
                }
                // apply field options
                if (isset($this->_fieldOptions[$fieldId])) {
                    $fieldOptions = $this->_fieldOptions[$fieldId];
                    foreach ($fieldOptions as $k => $v) {
                        $fieldElement->setDataUsingMethod($k, $v);
                    }
                }
            }
        }
        return $element;
    }
}