如何为Magento创建动态名称值?

时间:2012-09-18 07:00:41

标签: magento

我可以在app / design / frontend / default / mytheme / catalog / product / list.phtml中添加一堆代码,但我想知道是否有一种方法可以在另一个文件中创建“Name”值在前面提到的文件中简要地检索它。

我不想对每个项目的名称进行硬编码,而是希望将每个产品属性的名称拼凑在一起,并根据产品类型使用不同的逻辑。

Semi Pseudo code:

$attributes = $product->getAttributes();
// universal attributes:
$manuf = $attributes['manufacturer']->getFrontend()->getValue($product);
$color = $attributes['color']->getFrontend()->getValue($product);
$type = $attributes['product_type']->getFrontend()->getValue($product);

// base name, added to below
$name = $manuf . ' ' . $type . ' in ' . $color;

// then logic for specific types
switch($type) {
  case 'baseball hat':
    $team = $attributes['team']->getFrontend()->getValue($product);
    $name .= ' for ' . $team;
  break;
  case 'stilts':
    $length = $attributes['length']->getFrontend()->getValue($product);
    $name .= ' - ' . $length . ' feet long';
  break;
}

由于这个逻辑可能会很长,我觉得不应该把它全部塞进list.phtml。但是我应该怎么做呢?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

这种代码应该放在产品模型中。最好的方法是override the product class,但为了简单起见,我将描述更简单的方法:

1)复制

/app/code/core/Mage/Catalog/Model/Product.php

/app/code/local/Mage/Catalog/Model/Product.php

2)向文件添加新方法

/**
 * Get custom name here...
 *
 * @return    string
 */
public function getCombinedName()
{
    // your code below....
    $attributes = $this->getAttributes();
    // universal attributes:
    $manuf = $attributes['manufacturer']->getFrontend()->getValue($product);
    $color = $attributes['color']->getFrontend()->getValue($product);
    $type = $attributes['product_type']->getFrontend()->getValue($product);

    // base name, added to below
    $name = $manuf . ' ' . $type . ' in ' . $color;

    // then logic for specific types
    switch($type) {
        case 'baseball hat':
            $team = $attributes['team']->getFrontend()->getValue($product);
            $name .= ' for ' . $team;
      break;
      case 'stilts':
        $length = $attributes['length']->getFrontend()->getValue($product);
        $name .= ' - ' . $length . ' feet long';
      break;

    }

    return $name;
}