Wouter Stulp
Wouter Stulp

Reputation: 113

Magento 1.9 - Add Ip addres to customer grid

I want to export the "manage customers" grid, and also want to add the ip addresses of the customers at the end of the grid.

this is the code that is executed when the grid is loaded

protected function _prepareCollection()
{
    $collection = Mage::getResourceModel('customer/customer_collection')
        ->addNameToSelect()
        ->addAttributeToSelect('email')
        ->addAttributeToSelect('created_at')
        ->addAttributeToSelect('group_id')
        ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
        ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
        ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
        ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
        ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');

    $this->setCollection($collection);

    return parent::_prepareCollection();
}

i have also added a column

        $this->addColumn('ip_address', array(
        'header'    => Mage::helper('customer')->__('IP Address'),
        'default'   => Mage::helper('customer')->__('n/a'),
        'index'     => 'remote_addr',
        'renderer'  => 'adminhtml/customer_online_grid_renderer_ip',
        'filter'    => false,
        'sort'      => false
    ));

but i dont get any data.

How can i get the customers ip address in the added column

Upvotes: 1

Views: 1927

Answers (1)

Wakar Ahamad
Wakar Ahamad

Reputation: 216

To add ip addresses of the customers at the end of the grid :-

We've to create a custom module :-

I'm taking namespace as Wakar & Modulename as Customeripaddress :-

1- app/etc/modules/Wakar_Customeripaddress.xml

So first of all we've to register this module :-

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

2- app/code/local/Wakar/Customeripaddress/etc/config.xml :-

In this file we're defining module configuration(Block override,controller override etc).

<?xml version="1.0"?>
<config>
  <modules>
    <Wakar_Customeripaddress>
      <version>0.1.0</version>
    </Wakar_Customeripaddress>
  </modules>
  <frontend>
    <routers>
      <customeripaddress>
        <use>standard</use>
          <args>
            <module>Wakar_Customeripaddress</module>
            <frontName>customeripaddress</frontName>
          </args>
      </customeripaddress>
    </routers>
  </frontend>
  <global>
        <rewrite>        
            <wakar_customeripaddress_customer_accountcontroller>
                <from><![CDATA[#^/customer/account/#]]></from> <!-- Mage_Customer_AccountController  -->
                <to>/customeripaddress/customer_account/</to> <!-- Wakar_Customeripaddress_Customer_AccountController  -->
            </wakar_customeripaddress_customer_accountcontroller>
        </rewrite>
    <helpers>
      <customeripaddress>
        <class>Wakar_Customeripaddress_Helper</class>
      </customeripaddress>
    </helpers>
    <blocks>
      <customeripaddress>
        <class>Wakar_Customeripaddress_Block</class>
      </customeripaddress>
            <adminhtml>
                <rewrite>
                    <customer_grid>Wakar_Customeripaddress_Block_Adminhtml_Customer_Grid</customer_grid>
                </rewrite>
            </adminhtml>
    </blocks>
    <models>
      <customeripaddress>
        <class>Wakar_Customeripaddress_Model</class>
        <resourceModel>customeripaddress_mysql4</resourceModel>
      </customeripaddress>
    </models>
    <resources>
      <customerattribute1523689716_setup>
        <setup>
          <module>Wakar_Customeripaddress</module>
          <class>Mage_Customer_Model_Entity_Setup</class>
        </setup>
        <connection>
          <use>core_setup</use>
        </connection>
      </customerattribute1523689716_setup>
      <customerattribute1523689716_write>
        <connection>
          <use>core_write</use>
        </connection>
      </customerattribute1523689716_write>
      <customerattribute1523689716_read>
        <connection>
          <use>core_read</use>
        </connection>
      </customerattribute1523689716_read>
    </resources>
  </global>
  <admin>
    <routers>
      <customeripaddress>
        <use>admin</use>
        <args>
          <module>Wakar_Customeripaddress</module>
          <frontName>admin_customeripaddress</frontName>
        </args>
      </customeripaddress>
    </routers>
  </admin>
</config> 

3-app/code/local/Wakar/Customeripaddress/sql/customerattribute1523689716_setup/mysql4-install-0.1.0.php

Now we're going to create a customer custom column & during customer registration we'll use this column to save visitor ip address & later we'll fetch this ip address to show customer ip address via renderer.

<?php
$installer = $this;
$installer->startSetup();


$installer->addAttribute("customer", "customer_ip_address",  array(
    "type"     => "varchar",
    "backend"  => "",
    "label"    => "IP Address",
    "input"    => "text",
    "source"   => "",
    "visible"  => true,
    "required" => false,
    "default" => "",
    "frontend" => "",
    "unique"     => false,
    "note"       => "Customer Ip Address"

    ));

        $attribute   = Mage::getSingleton("eav/config")->getAttribute("customer", "customer_ip_address");


$used_in_forms=array();

$used_in_forms[]="adminhtml_customer";
$used_in_forms[]="checkout_register";
$used_in_forms[]="customer_account_create";
$used_in_forms[]="customer_account_edit";
$used_in_forms[]="adminhtml_checkout";
        $attribute->setData("used_in_forms", $used_in_forms)
        ->setData("is_used_for_customer_segment", true)
        ->setData("is_system", 0)
        ->setData("is_user_defined", 1)
        ->setData("is_visible", 1)
        ->setData("sort_order", 100)
        ;
        $attribute->save();



$installer->endSetup();

4- app/code/local/Wakar/Customeripaddress/controllers/Customer/AccountController.php :-

Save Customer Ip address during registration:-

<?php
require_once "Mage/Customer/controllers/AccountController.php";  
class Wakar_Customercontrolleroverride_Customer_AccountController extends Mage_Customer_AccountController{

    public function postDispatch()
    {
        parent::postDispatch();
        Mage::dispatchEvent('controller_action_postdispatch_adminhtml', array('controller_action' => $this));
    }

      public function createPostAction()
    {
        $errUrl = $this->_getUrl('*/*/create', array('_secure' => true));

        if (!$this->_validateFormKey()) {
            $this->_redirectError($errUrl);
            return;
        }

        /** @var $session Mage_Customer_Model_Session */
        $session = $this->_getSession();
        if ($session->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }

        if (!$this->getRequest()->isPost()) {
            $this->_redirectError($errUrl);
            return;
        }

        $customer = $this->_getCustomer();

        try {
            $errors = $this->_getCustomerErrors($customer);

                // Get Visitor Ip address
            if (empty($errors)) {

            if (!empty($_SERVER["HTTP_CLIENT_IP"]))
            {
             //check for ip from share internet
                    $ip = $_SERVER["HTTP_CLIENT_IP"];
            }
             elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
                {
                     // Check for the Proxy User
                    $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
                }
                else
                {
                        $ip = $_SERVER["REMOTE_ADDR"];
                }

                $customer['customer_ip_address']=$ip;  

                $customer->cleanPasswordsValidationData();
                $customer->save();
                $this->_dispatchRegisterSuccess($customer);
                $this->_successProcessRegistration($customer);
                return;
            } else {
                $this->_addSessionError($errors);
            }
        } catch (Mage_Core_Exception $e) {
            $session->setCustomerFormData($this->getRequest()->getPost());
            if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
                $url = $this->_getUrl('customer/account/forgotpassword');
                $message = $this->__('There is already an account with this email address. If you are sure that it is your email address, <a href="%s">click here</a> to get your password and access your account.', $url);
            } else {
                $message = $this->_escapeHtml($e->getMessage());
            }
            $session->addError($message);
        } catch (Exception $e) {
            $session->setCustomerFormData($this->getRequest()->getPost());
            $session->addException($e, $this->__('Cannot save the customer.'));
        }

        $this->_redirectError($errUrl);
    }


}

5- app/code/local/Wakar/Customeripaddress/Block/Adminhtml/Customer/Grid.php :-

Add Ip address in customer grid:-

<?php
class Wakar_Customeripaddress_Block_Adminhtml_Customer_Grid extends Mage_Adminhtml_Block_Customer_Grid
{

    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('customer/customer_collection')
            ->addNameToSelect()
            ->addAttributeToSelect('email')
            ->addAttributeToSelect('created_at')
            ->addAttributeToSelect('group_id')
            ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
            ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
            ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
            ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
            ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');

        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    protected function _prepareColumns()
    {
        $this->addColumn('entity_id', array(
            'header'    => Mage::helper('customer')->__('ID'),
            'width'     => '50px',
            'index'     => 'entity_id',
            'type'  => 'number',
        ));


        /*$this->addColumn('firstname', array(
            'header'    => Mage::helper('customer')->__('First Name'),
            'index'     => 'firstname'
        ));
        $this->addColumn('lastname', array(
            'header'    => Mage::helper('customer')->__('Last Name'),
            'index'     => 'lastname'
        ));*/
        $this->addColumn('name', array(
            'header'    => Mage::helper('customer')->__('Name'),
            'index'     => 'name'
        ));
        $this->addColumn('email', array(
            'header'    => Mage::helper('customer')->__('Email'),
            'width'     => '150',
            'index'     => 'email'
        ));

        $groups = Mage::getResourceModel('customer/group_collection')
            ->addFieldToFilter('customer_group_id', array('gt'=> 0))
            ->load()
            ->toOptionHash();

        $this->addColumn('group', array(
            'header'    =>  Mage::helper('customer')->__('Group'),
            'width'     =>  '100',
            'index'     =>  'group_id',
            'type'      =>  'options',
            'options'   =>  $groups,
        ));

        $this->addColumn('Telephone', array(
            'header'    => Mage::helper('customer')->__('Telephone'),
            'width'     => '100',
            'index'     => 'billing_telephone'
        ));

        $this->addColumn('billing_postcode', array(
            'header'    => Mage::helper('customer')->__('ZIP'),
            'width'     => '90',
            'index'     => 'billing_postcode',
        ));

        $this->addColumn('billing_country_id', array(
            'header'    => Mage::helper('customer')->__('Country'),
            'width'     => '100',
            'type'      => 'country',
            'index'     => 'billing_country_id',
        ));

        $this->addColumn('billing_region', array(
            'header'    => Mage::helper('customer')->__('State/Province'),
            'width'     => '100',
            'index'     => 'billing_region',
        ));

        $this->addColumn('customer_since', array(
            'header'    => Mage::helper('customer')->__('Customer Since'),
            'type'      => 'datetime',
            'align'     => 'center',
            'index'     => 'created_at',
            'gmtoffset' => true
        ));



        if (!Mage::app()->isSingleStoreMode()) {
            $this->addColumn('website_id', array(
                'header'    => Mage::helper('customer')->__('Website'),
                'align'     => 'center',
                'width'     => '80px',
                'type'      => 'options',
                'options'   => Mage::getSingleton('adminhtml/system_store')->getWebsiteOptionHash(true),
                'index'     => 'website_id',
            ));
        }

        $this->addColumn('ip_address', array(
        'header'    => Mage::helper('customer')->__('IP Address'),
        'default'   => Mage::helper('customer')->__('N/A'),
        'index'     => 'remote_addr',
        'renderer'  => 'customeripaddress/adminhtml_renderer_location',
        'filter'    => false,
        'sort'      => false
    ));

        $this->addColumn('action',
            array(
                'header'    =>  Mage::helper('customer')->__('Action'),
                'width'     => '100',
                'type'      => 'action',
                'getter'    => 'getId',
                'actions'   => array(
                    array(
                        'caption'   => Mage::helper('customer')->__('Edit'),
                        'url'       => array('base'=> '*/*/edit'),
                        'field'     => 'id'
                    )
                ),
                'filter'    => false,
                'sortable'  => false,
                'index'     => 'stores',
                'is_system' => true,
        ));

        $this->addExportType('*/*/exportCsv', Mage::helper('customer')->__('CSV'));
        $this->addExportType('*/*/exportXml', Mage::helper('customer')->__('Excel XML'));
        return parent::_prepareColumns();
    }
}

6- app/code/local/Wakar/Customeripaddress/Block/Adminhtml/Renderer/Location.php

Using renderer to show ip address in the customer grid:-

<?php
class Wakar_Customeripaddress_Block_Adminhtml_Renderer_Location extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {

        // Instance of customer loaded by the given ID
                $customer = Mage::getModel('customer/customer')->load($row->getData('entity_id'));
                    return $customer['customer_ip_address'] ;

    }
}

Hope this will resolve your problem...!!!

Upvotes: 1

Related Questions