在自定义客户网格中获取属性文本而不是 ID
-
12-12-2019 - |
题
我想在 adminhtml 客户网格中显示客户的自定义属性。我设法通过创建一个新模块来做到这一点,并扩展了 setCollection
的方法 Mage_Adminhtml_Block_Customer_Grid
public function setCollection($collection)
{
$collection->addAttributeToSelect('x_customer_category');
parent::setCollection($collection);
}
我通过观察者将列添加到视图中
/**
* Adds column to admin customers grid
*
* @param Varien_Event_Observer $observer
*
* @return Mscg_TemplateOverwrite_Model_Customer_Observer
*/
public function addCustomerGroupToGrid(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('x_customer_category', array(
'header' => 'x_customer_category',
'type' => 'text',
'index' => 'x_customer_category',
), 'email');
}
}
但是,由于这是一个选项属性,我只获取客户所选值的 ID,但我确实需要文本值,而不是给定属性的实体值。
我怎样才能做到这一点?
解决方案
您需要将列类型更改为 text
到 options
并添加一个 options
包含此格式的值的元素 key => value
.
像这样的东西:
$block->addColumnAfter('x_customer_category', array(
'header' => 'x_customer_category',
'type' => 'options',
'index' => 'x_customer_category',
'options' => array(
'id1' => 'label 1',
'id2' => 'label 2',
),
), 'email');
如果可能的值是动态的,您应该首先构建一个包含所有值的数组。您应该知道一种方法来检索所有可能的值并将获得的数组分配给 options
元素。
如果您的属性是标准选择属性,您可以像这样构建它:
$attribute = Mage::getModel('eav/config')->getAttribute('customer', 'x_customer_category');
$options = $attribute->getSource()->getAllOptions(false);
$values = array();
foreach ($options as $option){
$values[$option['value']] = $option['label'];
}
然后像这样添加您的列:
$block->addColumnAfter('x_customer_category', array(
'header' => 'x_customer_category',
'type' => 'options',
'index' => 'x_customer_category',
'options' => $values,
), 'email');