Buttle Butkus
Buttle Butkus

Reputation: 9466

How to create dynamic Name value for Magento?

I could add a bunch of code to app/design/frontend/default/mytheme/catalog/product/list.phtml, but I was wondering if there was a way I could create the "Name" value in another file and retrieve it concisely in the aforementioned file.

Instead of hard-coding a name for every item, I would like to cobble together the name from each product's attributes, and use different logic depending on product type.

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;
}

As this logic could get pretty long, I feel like it shouldn't all be crammed into list.phtml. But how should I go about doing it?

Upvotes: 0

Views: 605

Answers (2)

Andrew
Andrew

Reputation: 12809

This kind of code should be put inside the product model. The nicest way would be to override the product class, but for simplicity i'll describe the easier method:

1) Copy

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

to

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

2) Add a new method to the file

/**
 * 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;
}

Upvotes: 1

Related Questions