Adding Status Column to Customer Information -> Orders in Magento - magento

I've been attempting to add a "Status" column in the Orders grid that's shown when you view the Customer Information -> Orders tab.
I've been able to add the column, and the filter populates with the correct status values, but it breaks the default sorting and you can't filter by any item or sort.
I know there's probably a much better way of adding the column, but all the examples I found related to the main Orders table and I couldn't figure out how to modify it for this use case.
Here's my extension code - in /Pnp/Customer/Block/Customer/Edit/Tab/Orders.php
<?php
class Pnp_Customer_Block_Customer_Edit_Tab_Orders extends Mage_Adminhtml_Block_Customer_Edit_Tab_Orders
{
public function __construct()
{
parent::__construct();
$this->setId('customer_orders_grid');
$this->setUseAjax(true);
$this->setDefaultSort('created_at');
$this->setDefaultDir('DESC');
$this->setSaveParametersInSession(true);
}
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('sales/order_grid_collection')
->addFieldToSelect('entity_id')
->addFieldToSelect('increment_id')
->addFieldToSelect('customer_id')
->addFieldToSelect('created_at')
->addFieldToSelect('grand_total')
->addFieldToSelect('order_currency_code')
->addFieldToSelect('store_id')
->addFieldToSelect('billing_name')
->addFieldToSelect('shipping_name')
->addFieldToSelect('status')
->addFieldToFilter('customer_id', Mage::registry('current_customer')->getId())
->setIsCustomerMode(true);
$this->setCollection($collection);
return $this;
}
protected function _prepareColumns()
{
parent::_prepareColumns();
$this->addColumn('status', array(
'header' => Mage::helper('sales')->__('Status'),
'index' => 'status',
'type' => 'options',
'width' => '70px',
'options' => Mage::getSingleton('sales/order_config')->getStatuses()
));
return parent::_prepareColumns();
}
}
Thanks in advance for any help you can offer!
Many thanks to the answers so far.
I've nearly got there with a combination of Harit and Emipro Technologies answers, here's what I have so far:
etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Pnp_Customer>
<version>0.4.0</version>
</Pnp_Customer>
</modules>
<global>
<models>
<pnp_statusgrid>
<class>Pnp_Customer_Model</class>
</Pnp_statusgrid>
</models>
</global>
<adminhtml>
<events>
<core_block_abstract_prepare_layout_before>
<observers>
<statusgrid_column_append>
<type>model</type>
<class>Pnp_Customer_Model_Observer</class>
<method>appendCustomColumn</method>
</statusgrid_column_append>
</observers>
</core_block_abstract_prepare_layout_before>
</events>
</adminhtml>
</config>
Model/Observer.php
<?php
class Pnp_Customer_Model_Observer extends Varien_Event_Observer
{
/**
* Adds column to admin customers grid
*
* #param Varien_Event_Observer $observer
* #return Pnp_Customer_Model_Observer
*/
public function appendCustomColumn(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
if (!isset($block)) {
return $this;
}
if ($block->getType() == 'adminhtml/customer_edit_tab_orders') {
/* #var $block Mage_Adminhtml_Block_Customer_Grid */
$block->addColumn('status', array(
'header' => Mage::helper('customer')->__('Status'),
'type' => 'options',
'options' => Mage::getSingleton('sales/order_config')->getStatuses(),
'width' => '70px',
'index' => 'status',
'renderer' => 'Pnp_Customer_Block_Customer_Edit_Tab_Renderer_Status',
}
}
}
Block/Customer/Edit/Tab/Orders.php
<?php
class Pnp_Customer_Block_Customer_Edit_Tab_Orders extends Mage_Adminhtml_Block_Customer_Edit_Tab_Orders
{
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('sales/order_grid_collection')
->addFieldToSelect('entity_id')
->addFieldToSelect('increment_id')
->addFieldToSelect('customer_id')
->addFieldToSelect('created_at')
->addFieldToSelect('grand_total')
->addFieldToSelect('order_currency_code')
->addFieldToSelect('store_id')
->addFieldToSelect('billing_name')
->addFieldToSelect('shipping_name')
->addFieldToSelect('status')
->addFieldToFilter('customer_id', Mage::registry('current_customer')->getId())
->setIsCustomerMode(true);
$this->setCollection($collection);
return $this;
}
}
Block/Customer/Edit/Tab/Renderer/status.php
<?php
class Pnp_Customer_Block_Customer_Edit_Tab_Renderer_Status extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {
public function render(Varien_Object $row)
{
if (!$value = $this->getColumn()->getIndex()){
return $this;
}
$value = $row->getData('increment_id');
$order = Mage::getModel('sales/order')->loadByIncrementId($value);
return '<span >'.$order['status']'</span>';
}
}
?>
Everything is working except the column shows the status name as underscored, i.e. payment_pending. I looked at the object being returned and can't see the label version. As a final thing to get the above finished, would anyone be able to point me in the right direction to print the human readable version of the attribute?
Final Edit:
I managed to figure it out - I changed:
return '<span >'.$order['status']'</span>';
to
return '<span >'.$order->getStatusLabel().'</span>';

This is definately work add renderer
change your column by
$this->addColumn('status', array(
'header' => Mage::helper('customer')->__('Status'),
'index' => 'status',
'type' => 'options',
'options' => $this->_getorderstatus(),
'renderer' => 'Pnp_Customer_Block_Customer_Edit_Renderer_Status',
));
Add new function in same file
protected function _getorderstatus(){
$ordstatus = (array) Mage::getModel('sales/order_status')->getResourceCollection()->getData();
$orderstatus=array();
foreach($ordstatus as $item){
$orderstatus[$item['status']]=$item['label'];
}
return $orderstatus;
}
status.php put function like
public function render(Varien_Object $row)
{
if (!$value = $this->getColumn()->getIndex()){
return $this;
}
$value = $row->getData('increment_id');
$order = Mage::getModel('sales/order')->loadByIncrementId($value);
return '<span >'.$order['status'].'</span>';
}

An easier and reliable way to achieve this is through observer.
Create a Module
Inside app/code/local/My/Module/etc/config.xml
<global>
<models>
<my_customgrid>
<class>My_Module_Model</class>
</my_customgrid>
</models>
</global>
<adminhtml>
<events>
<core_block_abstract_prepare_layout_before>
<observers>
<customgrid_column_append>
<type>model</type>
<class>My_Module_Model_Observer</class>
<method>appendCustomColumn</method>
</customgrid_column_append>
</observers>
</core_block_abstract_prepare_layout_before>
</events>
</adminhtml>
What it does is, it allows you to observe the block before its layout is prepared.
Create a file called Observer.php for your module and write down following:
class My_Module_Model_Observer extends Varien_Event_Observer {
/**
*
* #param Varien_Event_Observer $observer
* #return \My_Module_Model_Observer
*/
public function appendCustomColumn(Varien_Event_Observer $observer) {
$block = $observer->getBlock();
if (!isset($block)) {
return $this;
}
if ($block->getType() == 'adminhtml/customer_grid') {
/* #var $block Mage_Adminhtml_Block_Customer_Grid */
$block->addColumnAfter('field', array(
'header' => 'Your Field',
'type' => 'text',
'index' => 'field',
), 'email');
}
}
}
Follow this link for more information:
http://www.atwix.com/magento/add-column-to-customers-grid-alternative-way/
Hope it helps.

Related

Magento2 Custom attribute is not saving during customer registration from frontend

I am trying to add the custom attribute to registration form. And i have added the attribute successfully by the following code
class InstallData implements InstallDataInterface
{
/**
* #var EavSetupFactory Magento\Eav\Setup\EavSetupFactory
*/
private $eavSetupFactory;
/**
* #var $_eavConfig Config
*/
protected $eavConfig;
public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'mobile',
[
'type' => 'varchar',
'label' => 'Mobile',
'input' => 'text',
'required' => false,
'system' => false,
'position' => 100,
'visible' => true,
'user_defined' => true
]
);
$mobile = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'mobile');
//$forms = ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit'];
$forms = ['adminhtml_customer'];
$mobile->setData(
'used_in_forms',
$forms
);
$mobile->save();
}
}
And to show at front-end i am using the layout handler customer_account_create with the following code
<referenceContainer name="form.additional.info">
<block class="Namespace\SMS\Block\Active" name="sms_block">
<action method="setTemplate" ifconfig="sms/actions/register" ifvalue="1">
<argument name="template" xsi:type="string">Namespace_SMS::sms/register.phtml</argument>
</action>
</block>
</referenceContainer>
Now it is showing the mobile field during registration. But when i try to create account mobile field value is empty after create account.
Note: I know if i add the 'customer_account_create', 'customer_account_edit' with used_in_form then mobile value save. But after this i can not use a specific template file to render mobile field.
Can you please let me know how can i solve this issue? Thank you very much.
I do not know whether it is 100% correct according to the coding rules. But I have resolved this issue using the observer and little bit changes in InstallData script.
InstallData.php is like this
class InstallData implements InstallDataInterface
{
/**
* Customer setup factory
*
* #var \Magento\Customer\Setup\CustomerSetupFactory
*/
private $customerSetupFactory;
/**
* Init
*
* #param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
*/
public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory) {
$this->customerSetupFactory = $customerSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
/** #var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'mobile',
[
'type' => 'varchar',
'label' => 'Mobile',
'input' => 'text',
'required' => false,
'system' => false,
'position' => 100,
'visible' => true,
'user_defined' => true
]
);
$customerSetup->updateAttribute('customer', 'mobile', 'is_used_for_customer_segment', '1');
//$forms = ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit'];
$forms = ['adminhtml_customer'];
$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'mobile');
$attribute->setData('used_in_forms', ['adminhtml_customer']);
$attribute->addData([
'attribute_set_id' => 1,
'attribute_group_id' => 1
]);
$attribute->save();
$setup->endSetup();
}
}
then events.xml is like this
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_register_success">
<observer name="sMSHandleCustomerSaveAfter" instance="\Namepace\SMS\Observer\CustomerRegisterObserver" />
</event>
</config>
And the observer is like this
class CustomerRegisterObserver implements ObserverInterface
{
/**
* #var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
function __construct(CustomerFactory $customerFactory)
{
$this->_customerFactory = $customerFactory;
}
public function execute(Observer $observer)
{
$customerData = $observer->getCustomer();
if($_POST['mobile']) {
$customer = $this->_customerFactory->create()->load($customerData->getId());
$customer->setData('mobile', $_POST['mobile']);
$customer->save();
}
}
}
IF someone is looking for the solution, nearly to the #Abbas answer, but modified in observer part:
<?php
namespace {Vendor}\Module\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
class CustomerRegisterObserver implements ObserverInterface
{
/**
* #var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
protected $_customerRepository;
function __construct(
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Psr\Log\LoggerInterface $logger
) {
$this->_customerFactory = $customerFactory;
$this->_logger = $logger;
}
public function execute(EventObserver $observer)
{
//$this->_logger->info("Observer CustomerRegisterObserver Loaded !");
$event = $observer->getEvent();
$customerData = $event->getCustomer();
if($_POST['mobile']) {
$customer = $this->_customerFactory->create()->load($customerData->getId());
$customer->setData('mobile', $_POST['mobile']);
$customer->save();
}
}
}

Add another tab with Product Grid to Category edit page in Mangento

I am trying to add another tab to the category edit page that contains another product grid. I need to do this because i want to add to each category page a zone that contains the products that are selected in this grid.
Can anyone help me finish the module ? or is there a easier or existing module to do this ?
PS: Complete code is greatly appreciated :)
This is where i got so far:
etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Forideas_Promotion>
<version>0.1.0</version>
</Forideas_Promotion>
</modules>
<global>
<resources>
<forideas_promotion_setup>
<setup>
<module>Forideas_Promotion</module>
<class>Forideas_Promotion_Model_Resource_Setup</class>
</setup>
</forideas_promotion_setup>
</resources>
<helpers>
<promotion>
<class>Forideas_Promotion_Helper</class>
</promotion>
</helpers>
<models>
<forideas_promotion>
<class>Forideas_Promotion_Model</class>
</forideas_promotion>
<promotion_resource>
<entities>
<category_product>
<table>category_product</table>
</category_product>
</entities>
</promotion_resource>
</models>
<events>
<adminhtml_catalog_category_tabs>
<observers>
<forideas_promotion_observer>
<class>forideas_promotion/observer</class>
<method>addCategoryTab</method>
</forideas_promotion_observer>
</observers>
</adminhtml_catalog_category_tabs>
</events>
</global>
<adminhtml>
<layout>
<updates>
<forideas_category_promotion>
<file>forideas_promotion.xml</file>
</forideas_category_promotion>
</updates>
</layout>
</adminhtml>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<Forideas_Promotion before="Mage_Adminhtml">Forideas_Promotion_Adminhtml</Forideas_Promotion>
</modules>
</args>
</adminhtml>
</routers>
</admin>
</config>
Block/Adminhtml/Category/Edit/Tab/Product.php:
<?php
class Forideas_Promotion_Block_Adminhtml_Category_Edit_Tab_Product
extends Mage_Adminhtml_Block_Widget_Grid {
public function __construct(){
parent::__construct();
$this->setId('product_grid');
$this->setDefaultSort('position');
$this->setDefaultDir('ASC');
$this->setUseAjax(true);
if ($this->getCategory()->getId()) {
$this->setDefaultFilter(array('in_products'=>1));
}
}
protected function _prepareCollection() {
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToSelect('price');
$adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
$collection->joinAttribute('product_name', 'catalog_product/name', 'entity_id', null, 'left', $adminStore);
if ($this->getCategory()->getId()){
$constraint = '{{table}}.category_id='.$this->getCategory()->getId();
}
else{
$constraint = '{{table}}.category_id=0';
}
$collection->joinField('position',
'promotion/category_product',
'position',
'product_id=entity_id',
$constraint,
'left');
$this->setCollection($collection);
parent::_prepareCollection();
return $this;
}
protected function _prepareMassaction(){
return $this;
}
protected function _prepareColumns(){
$this->addColumn('in_products', array(
'header_css_class' => 'a-center',
'type' => 'checkbox',
'name' => 'in_products',
'values'=> $this->_getSelectedProducts(),
'align' => 'center',
'index' => 'entity_id'
));
$this->addColumn('product_name', array(
'header'=> Mage::helper('catalog')->__('Name'),
'align' => 'left',
'index' => 'product_name',
));
$this->addColumn('sku', array(
'header'=> Mage::helper('catalog')->__('SKU'),
'align' => 'left',
'index' => 'sku',
));
$this->addColumn('price', array(
'header'=> Mage::helper('catalog')->__('Price'),
'type' => 'currency',
'width' => '1',
'currency_code' => (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
'index' => 'price'
));
$this->addColumn('position', array(
'header'=> Mage::helper('catalog')->__('Position'),
'name' => 'position',
'width' => 60,
'type' => 'number',
'validate_class'=> 'validate-number',
'index' => 'position',
'editable' => true,
));
}
protected function _getSelectedProducts(){
$products = $this->getCategoryProducts();
if (!is_array($products)) {
$products = array_keys($this->getSelectedProducts());
}
return $products;
}
public function getSelectedProducts() {
$products = array();
$selected = Mage::registry('current_category')->getSelectedProducts();
if (!is_array($selected)){
$selected = array();
}
foreach ($selected as $product) {
$products[$product->getId()] = array('position' => $product->getPosition());
}
return $products;
}
public function getRowUrl($item){
return '#';
}
public function getGridUrl(){
return $this->getUrl('*/*/productsGrid', array(
'id'=>$this->getCategory()->getId()
));
}
public function getCategory(){
return Mage::registry('current_category');
}
protected function _addColumnFilterToCollection($column){
// Set custom filter for in product flag
if ($column->getId() == 'in_products') {
$productIds = $this->_getSelectedProducts();
if (empty($productIds)) {
$productIds = 0;
}
if ($column->getFilter()->getValue()) {
$this->getCollection()->addFieldToFilter('entity_id', array('in'=>$productIds));
}
else {
if($productIds) {
$this->getCollection()->addFieldToFilter('entity_id', array('nin'=>$productIds));
}
}
}
else {
parent::_addColumnFilterToCollection($column);
}
return $this;
}
}
controllers/Adminhtml/Promotion/Category/ProductController.php:
<?php
require_once ("Mage/Adminhtml/controllers/Catalog/ProductController.php");
class Forideas_Promotion_Adminhtml_Promotion_Category_ProductController extends Mage_Adminhtml_Catalog_ProductController
{
public function productsAction(){
//$this->_initEntity(); //if you don't have such a method then replace it with something that will get you the entity you are editing.
$this->loadLayout();
$this->getLayout()->getBlock('category.edit.tab.product')
->setCategoryProducts($this->getRequest()->getPost('category_products', null));
$this->renderLayout();
}
public function productsgridAction(){
//$this->_initCategory();
$this->loadLayout();
$this->getLayout()->getBlock('category.edit.tab.product')
->setCategoryProducts($this->getRequest()->getPost('category_products', null));
$this->renderLayout();
}
}
Model/Observer.php
<?php
class Forideas_Promotion_Model_Observer{
public function addCategoryTab($observer)
{
$block = $observer->getEvent()->getTabs();
$block->addTab('features', array(
'label' => Mage::helper('catalog')->__('Some Label here'),
'url' => Mage::helper('adminhtml')->getUrl('adminhtml/promotion_category_product/productsgrid', array('_current' => true)),
'class' => 'ajax',
));
}
}
sql/setup/install-0.1.0.php
$this->startSetup();
$table = $this->getConnection()
->newTable($this->getTable('promotion/category_product'))
->addColumn('rel_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'identity' => true,
'nullable' => false,
'primary' => true,
), 'Relation ID')
->addColumn('category_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Category ID')
->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Product ID')
->addColumn('position', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'nullable' => false,
'default' => '0',
), 'Position')
->addIndex($this->getIdxName('promotion/category_product', array('product_id')), array('product_id'))
->addForeignKey($this->getFkName('promotion/category_product', 'category_id', 'promotion/category', 'entity_id'), 'category_id', $this->getTable('promotion/category'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->addForeignKey($this->getFkName('promotion/category_product', 'product_id', 'catalog/product', 'entity_id'), 'product_id', $this->getTable('catalog/product'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->setComment('Category to Product Linkage Table');
$this->getConnection()->createTable($table);
$this->endSetup();
I found the answer to your 'ajax loader will not disappear' problem. This is due to the fact that the HTML that is returned from the AJAX call actually refers to the original table, catalog_category_products_table. But the Javascript is looking for your own table name but can't find it and thus the infinite Please wait loader.
The solution is to create your own controller that extends Mage_Adminhtml_Catalog_CategoryController and load your own block with your gridname there. Then, in the block where you extended Mage_Adminhtml_Block_Catalog_Category_Tab_Product, you will define getGridUrl() and return the path to your newly created controller. Now everything will just work fine.
Don't know for what purpose you have uploaded all these code. As far as I can see it doesn't refer to your question. If you want to add new tab do following:
config.xml
<adminhtml>
<events>
<adminhtml_catalog_category_tabs>
<observers>
<add_new_tab>
<type>singleton</type>
<class>company_module/observer</class>
<method>addNewCategoryTab</method>
</add_new_tab>
</observers>
</adminhtml_catalog_category_tabs>
</events>
</adminhtml>
Model/Observer.php
class Company_Module_Model_Observer
{
public function addNewCategoryTab($observer)
{
$tabs = $observer->getTabs();
$tabs->addTab('prod', array(
'label' => Mage::helper('catalog')->__('Other Products'),
'content' => $tabs->getLayout()->createBlock(
'adminhtml/catalog_category_tab_product',
'category.product.grid'
)->toHtml(),
));
}
Than use your block extended from adminhtml/catalog_category_tab_product with yours rewrited _prepareCollection method. (Don't forget to put you block inside createBlock method)

Magento - Creating new Adminhtml Form, but saveAction() not working

I'm using Magento 1.9.0.1 and currently i'm working on a custom Magento extension!
Here is a screenshot of the Form:
When i hit Save Item i got this:
As you can see the saveAction() has not saved the changes.
When i place: Mage::log($this->getRequest()->getPost()); to see if the form is working i get this:
2015-02-17T13:25:08+00:00 DEBUG (7): Array
(
[form_key] => zj9E8FpNOCyFIqaT
[Receiver] => Veni
[Phone] => 359884685063
[Date] => 2015-02-05 19:06:44
)
By this i think the form is okey.
Let me show you all the code i have in my Extension!
I have in: /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status.php:
<?php
class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status extends Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct()
{
$this->_controller = 'adminhtml_sms_status';
$this->_blockGroup = 'smsnotification';
$this->_headerText = Mage::helper('smsnotification')->__('Item Manager');
$this->_addButtonLabel = Mage::helper('smsnotification')->__('Add Item');
parent::__construct();
}
}
I have in: /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Grid.php:
<?php
class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('smsnotification_grid');
$this->setDefaultSort('id');
$this->setDefaultDir('DESC');
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('smsnotification/smsnotification_collection');
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('id', array(
'header' => Mage::helper('smsnotification')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'id',
));
$this->addColumn('Receiver', array(
'header' => Mage::helper('smsnotification')->__('Receiver'),
'align' =>'left',
'index' => 'Receiver',
));
$this->addColumn('Phone', array(
'header' => Mage::helper('smsnotification')->__('Phone'),
'align' =>'left',
'index' => 'Phone',
));
$this->addColumn('Date', array(
'header' => Mage::helper('smsnotification')->__('Date'),
'align' =>'left',
'index' => 'Date',
));
return parent::_prepareColumns();
}
public function getRowUrl($row)
{
return $this->getUrl('*/*/edit', array('id'=>$row->getId()));
}
}
I have in: /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Edit.php:
<?php
class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::__construct();
$this->_objectId = 'id';
$this->_blockGroup = 'smsnotification';
$this->_controller = 'adminhtml_sms_status';
$this->_updateButton('save', 'label', Mage::helper('smsnotification')->__('Save Item'));
$this->_updateButton('delete', 'label', Mage::helper('smsnotification')->__('Delete Item'));
}
public function getHeaderText()
{
if( Mage::registry('smsnotification_data') && Mage::registry('smsnotification_data')->getId() ) {
return Mage::helper('smsnotification')->__("Edit Item '%s'", $this->htmlEscape(Mage::registry('smsnotification_data')->getReceiver()));
} else {
return Mage::helper('smsnotification')->__('Add Item');
}
}
}
I have in: /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Edit/Form.php:
<?php
class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
));
$fieldset = $form->addFieldset('edit_form', array('legend'=>Mage::helper('smsnotification')->__('Item information')));
$fieldset->addField('Receiver', 'text', array(
'label' => Mage::helper('smsnotification')->__('Receiver'),
'class' => 'required-entry',
'required' => true,
'name' => 'Receiver',
));
$fieldset->addField('Phone', 'text', array(
'label' => Mage::helper('smsnotification')->__('Phone'),
'class' => 'required-entry',
'required' => true,
'name' => 'Phone',
));
$fieldset->addField('Date', 'text', array(
'label' => Mage::helper('smsnotification')->__('Date'),
'class' => 'required-entry',
'required' => true,
'name' => 'Date',
));
if ( Mage::getSingleton('adminhtml/session')->getsmsnotificationData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getsmsnotificationData());
Mage::getSingleton('adminhtml/session')->setsmsnotificationData(null);
} elseif ( Mage::registry('smsnotification_data') ) {
$form->setValues(Mage::registry('smsnotification_data')->getData());
}
// Add these two lines
$form->setUseContainer(true);
$this->setForm($form);
////
return parent::_prepareForm();
}
}
I have in: /app/code/community/VivasIndustries/SmsNotification/controllers/Adminhtml/SmsorderstatusesController.php:
<?php
class VivasIndustries_SmsNotification_Adminhtml_SmsorderstatusesController extends Mage_Adminhtml_Controller_Action
{
public function indexAction()
{
$this->_title($this->__('SMS Center'))->_title($this->__('SMS Center'));
$this->loadLayout();
$this->_setActiveMenu('vivassms');
$this->_addContent($this->getLayout()->createBlock('smsnotification/adminhtml_sms_status'));
$this->renderLayout();
}
public function editAction()
{
$smsnotificationId = $this->getRequest()->getParam('id');
$smsnotificationModel = Mage::getModel('smsnotification/smsnotification')->load($smsnotificationId);
if ($smsnotificationModel->getId() || $smsnotificationId == 0) {
Mage::register('smsnotification_data', $smsnotificationModel);
$this->loadLayout();
$this->_setActiveMenu('vivassms');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('smsnotification/adminhtml_sms_status_edit'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('smsnotification')->__('Item does not exist'));
$this->_redirect('*/*/');
}
}
public function newAction()
{
$this->_forward('edit');
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
try {
Mage::log($this->getRequest()->getPost());
$postData = $this->getRequest()->getPost();
$smsnotificationModel = Mage::getModel('smsnotification/smsnotification')->load($this->getRequest()->getParam('id'));
$smsnotificationModel->setReceiver($postData['Receiver'])
->setPhone($postData['Phone'])
->setDate($postData['Date'])
->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setsmsnotificationData(false);
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setsmsnotificationData($this->getRequest()->getPost());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
public function deleteAction()
{
if( $this->getRequest()->getParam('id') > 0 ) {
try {
$smsnotificationModel = Mage::getModel('smsnotification/smsnotification');
$smsnotificationModel->setId($this->getRequest()->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
/**
* Product grid for AJAX request.
* Sort and filter result for example.
*/
public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('smsnotification/adminhtml_smsnotification_grid')->toHtml()
);
}
}
I have in: /app/code/community/VivasIndustries/SmsNotification/etc/config.xml:
<?xml version="1.0"?>
<config>
<modules>
<VivasIndustries_SmsNotification>
<version>0.1.0</version>
</VivasIndustries_SmsNotification>
</modules>
<global>
<models>
<smsnotification>
<class>VivasIndustries_SmsNotification_Model</class>
<resourceModel>vivasindustries_smsnotification_resource</resourceModel>
</smsnotification>
<vivasindustries_smsnotification_resource>
<class>VivasIndustries_SmsNotification_Model_Resource</class>
<entities>
<smsnotification>
<table>VivasIndustries_SmsNotification</table>
</smsnotification>
</entities>
</vivasindustries_smsnotification_resource>
</models>
<resources>
<smsnotification_setup>
<setup>
<module>VivasIndustries_SmsNotification</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</smsnotification_setup>
<smsnotification_read>
<connection>
<use>core_read</use>
</connection>
</smsnotification_read>
<smsnotification_write>
<connection>
<use>core_write</use>
</connection>
</smsnotification_write>
</resources>
<events>
<sales_order_save_after>
<observers>
<vivasindustries_smsnotification>
<class>smsnotification/observer</class>
<method>orderSaved</method>
</vivasindustries_smsnotification>
</observers>
</sales_order_save_after>
</events>
<helpers>
<smsnotification>
<class>VivasIndustries_SmsNotification_Helper</class>
</smsnotification>
</helpers>
<blocks>
<smsnotification>
<class>VivasIndustries_SmsNotification_Block</class>
</smsnotification>
</blocks>
</global>
<adminhtml>
<acl>
<resources>
<all>
<title>Allow Everything</title>
</all>
<admin>
<children>
<system>
<children>
<config>
<children>
<vivas>
<title>Vivas - All</title>
</vivas>
</children>
</config>
</children>
</system>
</children>
</admin>
</resources>
</acl>
<layout>
<updates>
<smsnotification>
<file>smsnotification.xml</file>
</smsnotification>
</updates>
</layout>
</adminhtml>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<VivasIndustries_SmsNotification before="Mage_Adminhtml">VivasIndustries_SmsNotification_Adminhtml</VivasIndustries_SmsNotification>
</modules>
</args>
</adminhtml>
</routers>
</admin>
</config>
I have in: /app/code/community/VivasIndustries/SmsNotification/Model/Resource/Smsnotification.php:
<?php
class VivasIndustries_SmsNotification_Model_Resource_Smsnotification extends Mage_Core_Model_Resource_Db_Abstract
{
/**
* Initialize resource model
*
* #return void
*/
public function _construct()
{
$this->_init('smsnotification/smsnotification','id');
}
}
I have in: /app/code/community/VivasIndustries/SmsNotification/Model/Resource/Smsnotification/Collection.php:
<?php
class VivasIndustries_SmsNotification_Model_Resource_Smsnotification_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract{
protected function _construct(){
$this->_init('smsnotification/smsnotification');
}
}
I have in: /app/code/community/VivasIndustries/SmsNotification/Model/
<?php
class VivasIndustries_SmsNotification_Model_Smsnotification extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init('smsnotification/smsnotification');
}
}
I have in: /app/code/community/VivasIndustries/SmsNotification/sql/smsnotification_setup/install-1.0.0.php:
<?php
$installer=$this;
$installer->startSetup();
$installer->run("
CREATE TABLE IF NOT EXISTS `VivasIndustries_SmsNotification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Receiver` varchar(500) NOT NULL,
`Phone` varchar(500) NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
");
$installer->endSetup();
?>
This are all files which i have in my Extension, exept adminhtml.xml and system.xml.
If you think they are important to be shown i'll show them.
So do you can you see the problem why it is not making the save properly ?
Can you help me out fix this problem?
Thanks in advance!
My guess is the id is missing in the post data. So it doesn't load the needed model data but creates a new entry.
Probably, $this->getRequest()->getParam('id') returns null.
Add a hidden field id to you form with the entry id.
xpoback is correct, you need to add an hidden field in your form if you're in edit action:
So in _prepareForm(), add before the Receiver field:
$model = Mage::registry('smsnotification_data');
if ($model->getId()) {
$fieldset->addField('id', 'hidden', array(
'name' => 'id',
));
}

How to override _prepareCollection and _prepareColumns in Magento Admin

How to override _prepareCollection and _prepareColumn from core to local. I want to add new column in a grid. How to do this?
protected function _prepareCollection()
{
$collection = Mage::getModel('players/players')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('player_id', array(
'header' => Mage::helper('players')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'player_id',
));
$this->addColumn('name', array(
'header' => Mage::helper('players')->__('Name'),
'align' =>'left',
'index' => 'name',
));
return parent::_prepareColumns();
}
Well there are two ways to do it. The first, while easier is not preferred, is to "local include hack" it and move the grid from core/Mage/../.. to local/Mage../.. and simply make your changes are required.
The alternative is to do a rewrite of the file in a module config.xml:
<blocks>
<customadminhtml>
<class>Namespace_CustomAdminhtml_Block</class>
</customadminhtml>
<adminhtml>
<rewrite>
<sales_order_grid>Namespace_CustomAdminhtml_Block_Adminhtml_Sales_Order_Grid</sales_order_grid>
</rewrite>
</adminhtml>
</blocks>
In the rewritten file I would not both trying to override the "_prepareCollection" call. How are you going to call it and set the collection, logically, you can't insert your changes in there properly and still maintain original functionality. Instead I would override the "setCollection" method. By doing this you maintain the logic of the original _prepareCollection function and can insert your logic into the flow:
/**
* #brief Add customer_email to sales order
* #param Mage_Sales_Model_Resource_order_grid_collection $collection
*/
public function setCollection($collection)
{
/** #var Mage_Eav_Model_Config $eav */
$eav = Mage::getModel('eav/config');
$attribute = $eav->getAttribute('customer', 'customer_number');
$connection = $collection->getConnection();
$collection->join(array('sfo' => 'sales/order'), 'main_table.entity_id=sfo.entity_id', 'customer_email');
if ($attribute->getId()) {
$collection->getSelect()
->joinLeft(array('c' => $connection->getTableName('customer_entity_varchar')),
'main_table.customer_id = c.entity_id AND c.attribute_id = '.$attribute->getId(),
array('customer_number' => 'value'));
}
parent::setCollection($collection);
}
Finally, you can add the column by overriding the normal "_prepareColumns" function, just call the parent before hand:
public function _prepareColumns()
{
parent::_prepareColumns();
$this->addColumnAfter('customer_email', array(
'header' => Mage::helper('customer')->__('Customer Email'),
'width' => '50px',
'index' => 'customer_email',
), 'shipping_name');
$this->sortColumnsByOrder();
return $this;
}

Magento Admin Grid is Empty

I am trying to create a custom module.When i click a module menu,empty grid is displaying.Log is not showing any errors
Grid.php
class Training_Banners_Block_Adminhtml_Banners_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('bannersGrid');
$this->setDefaultDir('ASC');
$this->setDefaultSort('banner_id');
$this->setSaveParamatersInSession(true);
}
protected function _prepareCollection()
{
$collection=Mage::getModel('banners/manage')->getCollection();
$this->setCollection($collection);
Mage::log(var_dump($collection));
return $collection;
}
protected function _prepareColumns()
{
$this->addColumn('banner_id', array(
'header' => Mage::helper('banners')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'banner_id'
));
$this->addColumn('name', array(
'header' => Mage::helper('banners')->__('Name'),
'align' =>'left',
'index' => 'name'
));
return parent::_prepareColumns();
}
}
banners.xml
<?xml version="1.0"?>
<layout version="0.1.0">
<adminhtml_banners_index>
<reference name="content">
<block type="banners/adminhtml_banners" name="training.banners" />
</reference>
</adminhtml_banners_index>
</layout>
Controller
<?php
class Training_Banners_Adminhtml_BanneradminController extends Mage_Adminhtml_Controller_Action
{
public function _initAction()
{
$this->loadLayout()->_setActiveMenu('banners/banners')
->_addBreadcrumb(Mage::helper('adminhtml')->__('Banners Manager'), Mage::helper('adminhtml')->__('Banners Manager'));
return $this;
}
public function indexAction()
{
$this->_initAction();
$this->loadLayout();
$this->_addContent($this->getLayout()->createBlock('banners/adminhtml_banners'));
$this->renderLayout();
}
}
First Please clear your cache and then logout and login.
Also please check the config.xml file ,whether the block and other declarations are same..

Resources