I add an attribute in product management in the backoffice (dropdown list)and I want to show the value instead of id.
here is the solution now it works i updated it :)
Grid.phtml
protected function _prepareCollection()
{
...
$collection->addAttributeToSelect('manufacturer'); //my add attribute
...
}
protected function _prepareColumns()
{
// add this code
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'manufacturer');
$options = $attribute->getSource()->getAllOptions(false);
$values = array();
foreach ($options as $option){
$values[$option['value']] = $option['label'];
}
$this->addColumn('manufacturer', //my add attribute
array(
'header'=> 'Manufacturer',
'width' => '100px',
'index' => 'manufacturer',
'type' => 'options',
'options' => $values,
));
Take a look into Mage_Adminhtml_Block_Catalog_Product_Grid::_prepareCollection() there are many attributes with addColumn.
You should customize the options index with the possible values.
There is a great tutorial in http://www.demacmedia.com/magento-commerce/mini-tutorial-adding-custom-attributes-to-the-backend-product-grid/
In resume you should use the following code.
protected function _getAttributeOptions($attribute_code)
{
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attribute_code);
$options = array();
foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {
$options[$option['value']] = $option['label'];
}
return $options;
}
And now lets update our addColumn functions to the following:
$this->addColumn('manufacturer', //my add attribute
array(
'header'=> Mage::helper('catalog')->__('Manufacturer'),
'width' => '100px',
'index' => 'manufacturer',
'type' => 'text',
'options' => $this->_getAttributeOptions('attribute_code'),
));
For getting attribute just use
$attribute = Mage::getSingleton('eav/config')->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'manufacturer');
instead of yours!
Related
I m trying to add cms page to topnavigation but it display only two level i want to make it like magento default rendering menu.i have tried following code to add cms page to top navigation but if there is sub menu of parent then how can i add to that child to parent using recursion method.
public function addItemsToTopmenuItems($observer)
{
$menu = $observer->getMenu();
$tree = $menu->getTree();
$node = new Varien_Data_Tree_Node(array(
'name' => 'Categories',
'id' => 'categories',
'url' => Mage::getUrl(), // point somewhere
), 'id', $tree, $menu);
$menu->addChild($node);
// Children menu items
$collection = Mage::getModel('cms/page')->getCollection()
->addFieldToFilter('is_active',1)
->addFieldToFilter('identifier',array(array('nin'=>array('no-route','enable-cookies'))));
foreach ($collection as $category) {
$tree = $node->getTree();
$data = array(
'name' => $category->getTitle(),
'id' => 'category-node-'.$category->getId(),
'url' => Mage::getUrl($category->getIdentifier()),
);
$subNode = new Varien_Data_Tree_Node($data, 'id', $tree, $node);
$node->addChild($subNode);
}
}
I was in your situation this week, and finally I achieved the solution using tree nodes. Here is the solution:
public function addItemsToTopmenuItems($observer)
{
/** #var Varien_Data_Tree_Node */
$menu = $observer->getMenu();
/** #var Varien_Data_Tree*/
$tree = $menu->getTree();
/** #var Varien_Data_Tree_Node_Collection */
$menuCollection = $menu->getChildren();
/** #var array of Varien_Data_Tree_Node*/
$nodes = $menuCollection->getNodes();
//Get "inlcude in navigation menu" parent CMS pages
$collection = Mage::getModel('cms/page')->getCollection()
->addFieldToFilter('include_in_nav',true)
->addFieldToFilter('is_active',true)
->addFieldToFilter('parent_id', array(array('null' => true), array('eq' => 0)))
->setOrder('sort_order');
$cmsHelper=Mage::helper('cms/page');
foreach ($collection as $item) {
$node = new Varien_Data_Tree_Node(array(
'name' => $item->getData('title'),
'id' => $item->getData('identifier'),
'url' => $cmsHelper->getPageUrl($item->getData('page_id')), // point somewhere
), 'id', $tree, $menu);
$menu->addChild($node);
$parent_id = $item->getData('page_id');
$this->getAllChilds($node,$parent_id);
}
}
And getAllChilds function:
private function getAllChilds($node,$parent, $defaultNode = null){
$cmsHelper=Mage::helper('cms/page');
$pages = Mage::getModel('cms/page')
->getCollection()
->addFieldToSelect('title')
->addFieldToSelect('page_id')
->addFieldToSelect('identifier')
->addFieldToFilter('parent_id', $parent)
->addFieldToFilter('is_active', 1)
->load();
$tree = $node->getTree();
if(count($pages) > 0) {
foreach ($pages as $item){
$data = array(
'name' => $item->getData('title'),
'id' => $item->getData('identifier'),
'url' => $cmsHelper->getPageUrl($item->getData('page_id')),
);
$subNode = new Varien_Data_Tree_Node($data, 'id', $tree, $node);
$node->addChild($subNode);
$node = $this->getAllChilds($subNode,$item->getData('page_id'), $node);
}
$node = $this->getAllChilds($subNode,$item->getData('page_id'));
}
$childNode = $node;
if($defaultNode !== null)
$childNode = $defaultNode;
return $childNode;
}
But you need some extra data in cms tables, like as 'parent_id' field. This is my mysql4-install-0.1.0.php file:
<?php
$installer = $this;
$installer->startSetup();
$table = $installer->getTable('cms/page');
$installer->getConnection()->addColumn($table,'parent_id',array(
'type' =>Varien_Db_Ddl_Table::TYPE_INTEGER,
'comment' => 'Parent CMS Page'
));
$installer->getConnection()->addColumn($table,'include_in_nav',
array(
'type' =>Varien_Db_Ddl_Table::TYPE_BOOLEAN,
'comment' => 'Include in navigation menu'
));
$installer->getConnection()->addColumn($table,'position',
array(
'type' =>Varien_Db_Ddl_Table::TYPE_INTEGER,
'comment' => 'Position from navigation (category) menu. 1=left; 2=right'
)); //1: left; 2: right
$installer->endSetup();
And finally you need to add these fields to the CMS / Pages backend menu: https://www.atwix.com/magento/adding-custom-attribute-to-a-cms-page/
Best regards!
I have added a column for the shipping method to the sales order grid. But now sorting and searching is not working for any of the column.I have 65 orders being listed at a time even if I select 20 from view drop-down.
I have created a custom module for this and I am getting correct values under shipping information column.
Following is my code in Grid.php file.
<?php
class Mynamespace_Ordergrid_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid
{
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->join('sales_flat_order', 'main_table.entity_id = sales_flat_order.entity_id',array('shipping_description'));
$this->setCollection($collection);
}
protected function _prepareColumns() {
$this->addColumn('shipping_description', array(
'header' => Mage::helper('sales')->__('Shipping Method'),
'index' => 'shipping_description',
'filter_index'=>'sales_flat_order.shipping_description',
));
return parent::_prepareColumns();
}
public function getGridUrl()
{
return $this->getUrl('*/*/grid', array('_current'=>true));
}
}
?>
Please help
muk,try below
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->join(array('myorder'=>'sales_flat_order'),'main_table.entity_id=myorder.entity_id',array('myorder.shipping_method as myorder_shipping_method'));
$this->setCollection($collection);
return parent::_prepareCollection();
}
Columns view of
$this->addColumn('myorder_shipping_method', array(
'header' => Mage::helper('sales')->__('Status'),
'index' => 'myorder_shipping_method',
'type' => 'options',
'width' => '70px',
'options' => $this->toOptionArray(),
));
add new function
public function toOptionArray($isMultiSelect = false)
{
$methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
$options = array();
foreach($methods as $_code => $_method)
{
if(!$_title = Mage::getStoreConfig("carriers/$_code/title"))
$_title = $_code;
$options[$_code.'_'.$_code] = $_title . " ($_code)";
}
return $options;
}
I am working on Magento 1.7 version.
My code is below:-
$categoryArray = Mage::getSingleton('lookbook/category')->getOptionArray();
$catId = Mage::getSingleton('core/session')->getCatId(); //it has value 4
$fieldset->addField('category_id', 'select', array(
'label' => Mage::helper('lookbook')->__('Lookbook'),
'name' => 'category_id[]',
'values' => $categoryArray,
'value' => $catId,
'disabled' => true
));
How to set this value selected in drop-down of admin grid form in Magento?
Take a look # https://magento.stackexchange.com/questions/544/how-to-set-default-value-for-form-fields
protected function _prepareForm()
{
$form_data = new Varien_Object();
$form = new Varien_Data_Form();
$this->setForm($form);
....
if ( Mage::getSingleton('adminhtml/session')->getXyzData() )
{
$form_data = Mage::getSingleton('adminhtml/session')->getXyzData();
Mage::getSingleton('adminhtml/session')->setXyzData(null);
}
else if ( Mage::registry('xyz_data') ) {
$form_data = Mage::registry('xyz_data');
}
$catId = Mage::getSingleton('core/session')->getCatId(); // it has value 4
if( empty($form_data->getData('category_id')) ){
$form_data->setData('category_id', $catId);
}
$fieldset->addField('category_id', 'select', array(
'label' => Mage::helper('lookbook')->__('Lookbook'),
'name' => 'category_id[]',
'values' => $categoryArray,
'disabled' => true
));
....
$form->setValues($form_data);
$this->setForm($form);
}
Add this in the __construct method of your grid.
$this->_defaultFilter = array('category_id'=>Mage::getSingleton('core/session')->getCatId());
Copy Ordered.php
From
app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products
to
app/code/local/Mage/Adminhtml/Block/Dashboard/Tab/Products
Rename New.php
I have modified the following code:
class Mage_Adminhtml_Block_Dashboard_Tab_Products_New extends Mage_Adminhtml_Block_Dashboard_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('productsNewGrid');
}
protected function _prepareCollection()
{
if (!Mage::helper('core')->isModuleEnabled('Mage_Sales')) {
return $this;
}
if ($this->getParam('website')) {
$storeIds = Mage::app()->getWebsite($this->getParam('website'))->getStoreIds();
$storeId = array_pop($storeIds);
} else if ($this->getParam('group')) {
$storeIds = Mage::app()->getGroup($this->getParam('group'))->getStoreIds();
$storeId = array_pop($storeIds);
} else {
$storeId = (int)$this->getParam('store');
}
$todayStartOfDayDate = Mage::app()->getLocale()->date()
->setTime('00:00:00')
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$todayEndOfDayDate = Mage::app()->getLocale()->date()
->setTime('23:59:59')
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$collection
->addStoreFilter()
->addAttributeToFilter('news_from_date', array('or'=> array(
0 => array('date' => true, 'to' => $todayEndOfDayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter('news_to_date', array('or'=> array(
0 => array('date' => true, 'from' => $todayStartOfDayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter(
array(
array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
)
);
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('name', array(
'header' => $this->__('Product Name'),
'sortable' => false,
'index' => 'product_name'
));
$this->addColumn('price', array(
'header' => $this->__('Price'),
'width' => '120px',
'type' => 'currency',
'currency_code' => (string) Mage::app()->getStore((int)$this->getParam('store'))->getBaseCurrencyCode(),
'sortable' => false,
'index' => 'product_price'
));
$this->addColumn('ordered_qty', array(
'header' => $this->__('Quantity Ordered'),
'width' => '120px',
'align' => 'right',
'sortable' => false,
'index' => 'qty_ordered',
'type' => 'number'
));
$this->setFilterVisibility(false);
$this->setPagerVisibility(false);
return parent::_prepareColumns();
}
/*
* Returns row url to show in admin dashboard
* $row is bestseller row wrapped in Product model
*
* #param Mage_Catalog_Model_Product $row
*
* #return string
*/
public function getRowUrl($row)
{
// getId() would return id of bestseller row, and product id we get by getProductId()
$productId = $row->getProductId();
// No url is possible for non-existing products
if (!$productId) {
return '';
}
$params = array('id' => $productId);
if ($this->getRequest()->getParam('store')) {
$params['store'] = $this->getRequest()->getParam('store');
}
return $this->getUrl('*/catalog_product/edit', $params);
}
}
Then Copy Grids.php
From
app/code/core/Mage/Adminhtml/Block/Dashboard/
to
app/code/local/Mage/Adminhtml/Block/Dashboard/
added the following code:
$this->addTab('new_products', array(
'label' => $this->__('New Product'),
'content' => $this->getLayout()->createBlock('adminhtml/dashboard_tab_products_new')->toHtml(),
'class' => 'ajax'
));
I want to add a new product tab in admin dashboard,beside customers.I don't know what wrong with the New.php.I click the new product tab,it's not working.How to fix it?
I have managed to get this working with only a few more lines to change.
Update the Dashboard controller Mage_Adminhtml_DashboardController to add the new action
public function productsNewAction()
{
$this->loadLayout();
$this->renderLayout();
}
Update the admin layout.xml design\adminhtml\default\default\layout\main.xml to add the new section
<adminhtml_dashboard_productsnew>
<block type="core/text_list" name="root" output="toHtml">
<block type="adminhtml/dashboard_tab_products_new" name="adminhtml.dashboard.tab.products.new"/>
</block>
</adminhtml_dashboard_productsnew>
The you would just need to update your code in the Grids.php to the following.
$this->addTab('new_products', array(
'label' => $this->__('New Product'),
'url' => $this->getUrl('*/*/productsNew', array('_current'=>true)),
'class' => 'ajax'
));
This should then work using a call to the url rather than the block content.
You then need to select the attributes you want to show. You can do this by selecting all or by attribute code.
$collection->addAttributeToSelect('*')
$collection->addAttributeToSelect('name');
Important is the column index defined in _prepareColumns match these attribute codes Otherwise you will just get an empty row.
I would suggest packaging these changes into a new module with a controller, layout.xml and block files. There are lots of great tutorials around on how to do this, but obviously you don't have to :)
I currently have the following models:
class Category extends AppModel {
var $name = 'Category';
/*var $validate = array(
'name' => 'multiple'
);
no idea how to use this
*/
var $hasAndBelongsToMany = array(
'Post' => array(
'className' => 'Post'
)
);
class Post extends AppModel {
var $name = 'Post';
var $hasAndBelongsToMany = array(
'Category' => array(
'className' => 'Category'
)
);
var $belongsTo = array(
'Page' => array(
'className' => 'Page'
)
);
class Page extends AppModel {
var $name = 'Page';
var $order = array('Page.modified' => 'desc');
var $hasOne = array(
'Post' => array(
'className' => 'Post'
));
I also have this Form in the view:
<div id="content-wrap">
<div id="main">
<h2>Add Post</h2>
<?php echo $this->Session->flash();?>
<div>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('Post.title');
echo $this->Form->input('Category.Category', array('multiple' => 'checkbox'));
echo $this->Form->input('Post.body', array('rows' => '3'));
echo $this->Form->input('Page.meta_keywords');
echo $this->Form->input('Page.meta_description');
echo $this->Form->end('Save Post');
?>
</div>
<!-- main ends -->
</div>
My Controller:
function admin_add() {
// pr(Debugger::trace());
$this->set('categories', $this->Post->Category->find('list'));
if ( ! empty($this->data)) {
$this->data['Page']['title'] = $this->data['Post']['title'];
$this->data['Page']['layout'] = 'index';
if ($this->Post->saveAll($this->data)) {
$this->Session->setFlash('Your post has been saved', 'flash_good');
$this->redirect($this->here);
}
}
}
The problem I am having is that I could save a Post without choosing a category for it.
I've tried adding the following as a rule to the Category Model:
var $validate = array(
'rule' => array('multiple', array('in' => array(1, 2, 3, 4))),
'required' => TRUE,
'message' => 'Please select one, two or three options'
);
The Post and Page Model validates.
How do I activate validation for the Category?
First off, you haven't set up the $validate variable properly. The keys in the $validate array must be field names. Secondly, the multiple rule is used to check if the value(s) of a field lies within a set of values.
var $validate = array(
'color' => array(
'multiple' => array(
'rule' => array('multiple', array('in' => array('Red', 'Blue', 'Green'))),
'required' => false,
'message' => 'Please select one, two or three options'
),
),
);
I checked the example in the book for multiple and it's a typo there. The above code is correct.
Next, if you want to validate related models, I suggest you do that in your beforeSave() function:
function beforeSave(){
if (isset($this->data['Category']['Category']) && empty($this->data['Category']['Category'])) {
return false;
}
return true;
}
Here, returning false from the beforeSave() would prevent the save from going through. So, you will have successfully validated your requirement.