Filtering a text-type column with MySQL-computed values in Magento Admin Grid - filter

Say one column in grid has computed values:
setCollection():
'refunded' => new Zend_Db_Expr("IF(qty_refunded > 0, 'Yes', 'No')"),
_prepareColumns():
$this->addColumnAfter('refunded', array(
'header' => Mage::helper('helper')->__('Refunded'),
'index' => 'refunded',
'type' => 'text',
), 'qty');
What and how must one change in order to have columns with "yes" values, in case admin types "yes" then filters?

Adminhtml grid columns have a filter property which specifies a block class. For boolean yes/no fields that would usually be adminhtml/widget_grid_column_filter_select.
It would be used automatically if your field type would be 'options'.
Try this in _prepareCollection():
'refunded' => new Zend_Db_Expr("IF(qty_refunded > 0, 1, 0)"),
And in _prepareColumns() use:
$this->addColumnAfter('refunded', array(
'header' => Mage::helper('helper')->__('Refunded'),
'index' => 'refunded',
'type' => 'options',
'options' => array(0 => $this->__('No'), 1 => $this->__('Yes'))
), 'qty');
This should still render your values as "Yes" and "No" in the Column, and you would get the select with the appropriate options as a filter dropdown.
This alone won't be enough since the column with the computed value can't be referenced directly in the WHERE clause by MySQL. Magento provides two options to work around that.
Column filter blocks have a method getCondition() which return a condition that will be used to filter the collection. See Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Abstract::getCondition() for an example.
So if you need to customize the SQL used to execute the filter, create your own column filter block extending Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Select and adjust the returned condition as needed, i.e. use the same computed value to match against.
Your custom filter can be specified for the column like this in the addColumn() definition:
'type' => 'options',
'options' => array(0 => $this->__('No'), 1 => $this->__('Yes')),
'filter' => 'your_module/adminhtml_widget_grid_column_filter_custom',
If you prefere to work outside of the limitations of Magento's ORM filter syntax, you can modify the collections select directly by using a filter callback:
'type' => 'options',
'options' => array(0 => $this->__('No'), 1 => $this->__('Yes')),
'filter_condition_callback' => array($this, '_applyMyFilter'),
The callback receives the collection and the column as arguments. Here is a simple example for that method:
protected function _applyMyFilter(Varien_Data_Collection_Db $collection, Mage_Adminhtml_Block_Widget_Grid_Column $column)
{
$select = $collection->getSelect();
$field = $column->getIndex();
$value = $column->getFilter()->getValue();
$select->having("$field=?, $value);
}
Needless to say that both approaches (filtering against the computed value) is very inefficient in MySQL. But maybe that's no a problem for you in this case.

I'll post a working example, but I'll choose Vinai's answer for being so detailed.
In Grid.php:
protected function _addColumnFilterToCollection($column)
{
if ($column->getId() == 'refunded' && $column->getFilter()->getValue()) {
$val = $column->getFilter()->getValue();
$comparison = ($val === "No") ? 'lteq' : 'gt'; // lteg: <=; gt: >
$this->getCollection()->addFieldToFilter('ois.qty_refunded', array($comparison => 0));
} else {
parent::_addColumnFilterToCollection($column);
}
return $this;
}

Related

magento show content according to condition in admin grid

I have developed custom admin module. I have used the usual methods _prepareCollection and _prepareColumns to show the data in Grid.
protected function _prepareCollection()
{
$collection = Mage::getModel("wallets/sellerrequest")->getCollection();
$collection->getSelect()
->join( array('ce1' => 'customer_entity_varchar'), 'ce1.entity_id=main_table.seller_id and ce1.attribute_id = "5"', array('seller_name' => 'value'));
$this->setCollection($collection);
parent::_prepareCollection();
return $this;
}
protected function _prepareColumns()
{
$helper = Mage::helper('sellers');
$currency = (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
$this->addColumn('id', array(
'header' => $helper->__('Request No'),
'index' => 'id'
));
$this->addColumn('Requested Amount', array(
'header' => $helper->__('Requested Amount'),
'index' => 'request_amount'
));
$this->addColumn('Seller Name', array(
'header' => $helper->__('Seller Name'),
'index' => 'seller_name',
));
$this->addColumn('Status', array(
'header' => $helper->__('Status'),
'index' => 'status_flag'
));
All the data shows correctly according to the table values. But I want to show the Request Amount column values preceding with $ sign, e.g. $300 etc. Also, I want to show the status flag according to condition. Means if the status flag is 1 then I want to show the value as "Approved", if flag is 2 then "Pending" etc. How should I customize the collection data and show in grid according to my requirement? Help appreciated.
Thanks.
I have answered to a question similar to your requirement
How to properly add a shipping_description column in magento order grid?
Check my answer and try to compare with your problem. In this example there is the solution for our currency problem too.
So check this out.Hope it will be helpful.
Here you should implement Grid Renderer.
Here is complete tutorial for that : http://inchoo.net/magento/how-to-add-custom-renderer-for-a-custom-column-in-magento-grid/
You can customize the value of any colum

Not saving data when add multiple select attribute in product grid

I have created one custom module with add associated products concept. Created successfully. And Its working well.
But when i add "Multi select attribute" column in product grid with that option values, That entity value not saved.
If i removed that option values from that brand attribute drop down, Its saving fine.
I have shown my code below what i did for add multi select attribute column in product grid
under _prepareColumns() method
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'brand'); // attribute code here
foreach ( $attribute->getSource()->getAllOptions(true, true) as $option)
{
if($option['value'] != '')
$valArr[$option['value']] = $option['label'];
}
$this->addColumn('brand', array(
'header'=> Mage::helper('catalog')->__('Brand'),
'align' => 'left',
'index' => 'brand',
'type' => 'options',
'options' => $valArr,
'renderer' => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Brands', // Will have to create the renderer.
'filter_condition_callback' => array($this, '_filterBrandCondition')
));
When i hide 'options' => $valArr, , All are working fine.
I can't able to understand, why its happening. Please suggest me your ideas. Thanks in advance.
Have you already created the _filterBrandCondition function ?
What Mage_Adminhtml_Block_Catalog_Product_Renderer_Brands look like ?

Magento Admin formfield multiselect selected

I´m currently developing a custom module for magento thats going to list employees.
I have figured out almost everything. The only thing I got left is how the selected values is going to be highlighted.
The problem I´m having is for the backend.
I got 2 tabs per employee, one for employee data and one tab for magento categories.
1 employee can have 1 or more categories.
The database table that the categories are stored in are a non-eav table.
So my question is
What in a multiselect determines which values are selected? As it is now, only one value is selected.
I think you can do this by simply passing in an array of the id's to be selected into the 'value' attribute of the field being added for the multiselect in the _prepareForm() method. Something like the following.
$fieldset->addField('category_id', 'multiselect', array(
'name' => 'categories[]',
'label' => Mage::helper('cms')->__('Store View'),
'title' => Mage::helper('cms')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('mymodule/mymodel')->getMymodelValuesForForm(),
'value' => array(1,7,10),
));
The id of the form element (e.g. category_id) must not be an attribute in your model, otherwise when the form values get set with $form->setValues() later on, the attribute value will be overwritten.
I normally store multiple selections as a text column separated by commas much like most magento modules handles stores which requires a slightly different approach as shown below.
In the form block for the tab with the multiselect, you firstly define the element to be displayed like so in the _prepareForm() method. You then get the values from the model and set put them into the form data.
protected function _prepareForm()
{
...
$fieldset->addField('store_id', 'multiselect', array(
'name' => 'stores[]',
'label' => Mage::helper('cms')->__('Store View'),
'title' => Mage::helper('cms')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true),
));
...
if ( Mage::getSingleton('adminhtml/session')->getMymodelData() )
{
$data = Mage::getSingleton('adminhtml/session')->getMymodelData();
} elseif ( Mage::registry('mymodel_data') ) {
$data = Mage::registry('mymodel_data')->getData();
}
$data['store_id'] = isset($data['stores']) ? explode(',', $data['stores']) : array();
$form->setValues($data);
}
I normally store the selected stores (categories as in your case) in the main model as a text column and comma separated values of ids, hence the explode.
In the controller for for the edit action, I put the model being edited into the mage registry so we can load it and it's values in the step above.
Mage::register('mymodel_data', $model);
Thanks for answering.
This is how my field looks like:
$fieldset->addField('npn_CatID', 'multiselect', array(
'label' => Mage::helper('employeelist')->__('Kategori'),
'class' => 'required-entry',
'required' => true,
'name' => 'npn_CatID',
'values' => $data,
'value' => array(3,5)
));
npn_CatID is the value in my db where the category id is saved.
I have tried to change the name and field ID but cant get it working.
When its the field id is like above ONE value is selected and its the last one inserted for the chosen employee
My data array looks likes
array(array('value' => '1', 'label' => 'USB'), array('value' => '2', 'label' => 'Memories'))

Codeigniter Update Multiple Records with different values

I'm trying to update a certain field with different values for different records.
If I were to use MySql syntax, I think it should have been:
UPDATE products
SET price = CASE id
WHEN '566423' THEN 49.99
WHEN '5681552' THEN 69.99
END
WHERE code IN ('566423','5681552');
But I prefer to use Active Record if it's possible.
My input is a tab delimited text which I convert into an array of the id and the desired value for each record:
$data = array(
array(
'id' => '566423' ,
'price' => 49.99
),
array(
'id' => '5681552' ,
'price' => 69.99
)
);
I thought this is the proper structure for update_batch, but it fails. Here's what I've tried:
function updateMultiple()
{
if($this->db->update_batch('products', $data, 'id'))
{
echo "updated";
}
else
{
echo "failed )-:";
}
}
And I get failed all the time. What am I missing?

cakephp custom validation does not display error message in the nested rule

im doing a custom validation but it does not display error message when invalidated.
do you know where is the problem? I think the problem might be in the invalidate function. do you know how to set it up for the nested validation like this one?
var $validate = array(
'receiver' => array(
'maxMsg' => array(
'rule' => array('maxMsgSend'),
//'message' => ''
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'field must not be left empty'
))......
custom validation method in the model:
function maxMsgSend ( $data )
{
$id = User::$auth['User']['id'];
$count_contacts = (int)$this->Contact->find( 'count', array( 'conditions' =>array( 'and' =>array( 'Contact.contact_status_id' => '2',
'Contact.user_id' => $id))));
$current_credit = (int)$this->field( '3_credit_counter', array( 'id' => $id));
$max_allowed_messages = ($count_contacts >= $current_credit)? $current_credit: $count_contacts ;
if ($data>$max_allowed_messages)
{
$this->invalidate('maxMsg', "you can send maximum of {$max_allowed_messages} text messages.");
}
}
UPDATE: how is solved it.
i moved the the guts of the function to beforeValidate() in the model.
function beforeValidate($data) {
if (isset($this->data['User']['receiver']))
{
$id = User::$auth['User']['id'];
$count_contacts = (int)$this->Contact->find( 'count', array( 'conditions' =>array( 'and' =>array( 'Contact.contact_status_id' => '2',
'Contact.user_id' => $id))));
$current_credit = (int)$this->field( '3_credit_counter', array( 'id' => $id));
$max_allowed_messages = ($count_contacts >= $current_credit)? $current_credit: $count_contacts ;
if ($data>$max_allowed_messages)
{
$this->invalidate('receiver', "you can send maximum of {$max_allowed_messages} text messages.");
return false;
}
}
return true;
}
I think your maxMsgSend function still needs to return false if validation fails.
I think the problem is in your Model::maxMsgSend function. As written in the bakery, (http://bakery.cakephp.org/articles/view/using-equalto-validation-to-compare-two-form-fields), to build a custom validation rule (they want to compare two fields, but the concepts are the same), they write:
I return a false if the values don't match, and a true if they do.
Check out their code for the Model class, about half way down. In short, you don't need to call invalidate from within the custom validation method; you simply return true if it passes validation, and false if it doesn't pass validation.

Resources