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;
    }
}

No comments:

Post a Comment