0
votes

Please I am trying to create a module in magento that edits the products' name by concatenating the existing product names with randomly generated numbers.

$model = Mage::getModel('catalog/product') ->load(1111) //getting product model

$collection = $model->getCollection(); //products collection

foreach ($collection as $product) //loop for getting products

{

$model->load($product->getId());

$pname = $product->getName(); 

$this->model = Mage::getModel('catalog/product');

$new_name = $pname.' '.rand(1000,5000);

$this->model->setName($new_name);

}

This is my code, I am trying to create a module to achieve this functionality without editing the core files or using the admin panel.

2
You should be able to do this with the magento apiOrangepill
@Orangepill there is my code, its a technical task that has to be done that way and its urgent too. thanks in advance guysvickey Akinmade
are you getting any errors with this?Orangepill
and I can't tell if you are trying to change the name on an existing model or create a new modelOrangepill
have u added $this->model->save(); ?Dushyant Joshi

2 Answers

2
votes

Sorry but your code is ugly.

If you want to use collection (that is a good way to access data from a list of object) you must not use a ->load() (very expensive and should be used only when accessing data for a single object, like a product page)

Try this code instead :

    $collection = Mage::getModel('catalog/product')->getCollection(); //products collection
    $collection->addAttributeToSelect('name'); //retrieve only product name (optimising SQL)

    foreach ($collection as $product) //loop for getting products
    {
        $pname = $product->getName(); 
        $new_name = $pname.' '.rand(1000,5000);
        $product->setName($new_name);
        $product->save(); // you missed that
    }

If you have a high number or product, you could also make a single SQL query with the SQL CONCAT() function ...

0
votes

class Digital_GoogleMpn_Model_Observer {

public function googleMpn(Varien_Event_Observer $observer)
{

$product = $observer->getEvent()->getProduct();

    $pname = $product->getName();         

$google_mpn = rand(1000,5000);
  
    $new_name = "{$pname}.' '.{$google_mpn}"; 
  
    $product->setName($new_name);
  
    $product->save(); 

  
}      }