Csv Files for Magento
Denis Saltanakhmedov Avatar

Group Pricing is a great and flexible instrument for adding product prices for different groups of customers. Magento allows to affect the cost of separate products using group price mechanism for chosen groups. In this case, the product group price allows to set a product price for separate products and, at the same time, we do not need to create many catalog price rules.

Example on how to add Group Price for product in the admin panel

First of all, go to the admin panel -> choose Catalog -> Manage Products and click on Edit button for some product from your store.
Then, on the product edit page you can choose Price tab, and there just press the Add Group Price button. After that, select Website where the rule will be true, and choose Customer Group for this rule, the last step is to insert a price for the product.

Admin_group_price

It is easy to follow this way if we have just one product, but we need to concentrate on other important things if there are many products. As you may already know, adding price rule for every product manually is a very long process. However, we can do it using CSV file import.

Create extension for import Group Price from CSV file.

We will not pay attention for explanation about how to create an extension for Magento, because you can surely find many good posts on this topic. Now, let’s investigate a piece of code for an import.

Create a form for CSV file import – for example, it can be a fragment of code from phtml admin template:

   <div class="content-header">
    <h3 class="icon-head head-adminhtml-import">Import</h3>
</div>
<div class="entry-edit">
    <form id="edit_form" action="<?php echo $this->getUrl('*/*/import')?>" method="post" enctype="multipart/form-data" >
        <div>
            <input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
        </div>
        <div class="entry-edit-head">
            <h4 class="icon-head head-edit-form fieldset-legend">Import</h4>
            <div class="form-buttons"></div>
        </div>
        <div class="fieldset " id="base_fieldset">
            <div class="hor-scroll">
                <table cellspacing="0" class="form-list">
                    <tbody>
                    <tr>
                        <td class="label"><label for="import_file">Select File to Import <span class="required">*</span></label></td>
                        <td class="value">
                            <input id="import_file" name="import_file" value="" title="Select File to Import" type="file" class="required-entry">
                            <div class="validation-advice" id="advice-required-entry-import_file" style="opacity: 0; display: none;">This is a required field.</div>
                        </td>
                    </tr>
                    <tr>
                        <td class="label"></td>
                        <td>
                            &nbsp;&nbsp;<input type="submit" value="Import" id="import_csv_group_price">
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </form>
</div>

Now, create import controller:

class Atwix_Groupprice_ImportController extends Mage_Adminhtml_Controller_Action
{
    /**
     * Index Action, prepare and display form
     */
    public function indexAction()
    {
        $this->loadLayout();
        $this->_setActiveMenu('import_groupprice');
        $this->renderLayout();
    }

    /**
     * Import action, import group price from csv
     */
    public function importAction()
    {
        $fileTrue = $this->fileImportCsvUpload();
        if ($fileTrue == true) {
            $file = 'var/importexport/example.csv';
            $csv = new Varien_File_Csv();
            $data = $csv->getData($file);

            foreach ($data as $value) {
                $productId = $value[0];

                $product = Mage::getModel('catalog/product')->setStoreId(0)->load($productId);
                
                if ($product == false || !$product->getSku()) {
                    continue;
                }
                $pricesFilterKeys = array('price_id', 'all_groups', 'website_price');

                $groupPrice = $product->getData('group_price');
                $key = count($groupPrice);
                $groupPrice[$key+1]['website_id'] = $value[1];
                $groupPrice[$key+1]['cust_group'] = $value[2];
                $groupPrice[$key+1]['price'] = $value[3];

                $product->setData('group_price', $this->_filterOutArrayKeys($groupPrice, $pricesFilterKeys, true));

                $product->save();
            }
            Mage::getSingleton('core/session')->addSuccess("Import success");
        } else {
            Mage::getSingleton('checkout/session')->addError("Import is failed.");
        }

        $this->_redirect("*/*/index");
    }

    /**
     * Remove specified keys from array
     *
     * @param array $array
     * @param array $keys
     * @param bool $dropOrigKeys if true - return array as indexed array
     * @return array
     */
    protected function _filterOutArrayKeys(array $array, array $keys, $dropOrigKeys = false)
    {
        $isIndexedArray = is_array(reset($array));
        if ($isIndexedArray) {
            foreach ($array as &$value) {
                if (is_array($value)) {
                    $value = array_diff_key($value, array_flip($keys));
                }
            }
            if ($dropOrigKeys) {
                $array = array_values($array);
            }
            unset($value);
        } else {
            $array = array_diff_key($array, array_flip($keys));
        }

        return $array;
    }

    /**
     * Upload csv file and save in var/importexport/example.csv
     *
     * @return bool
     */
    public function fileImportCsvUpload()
    {
        if (isset($_FILES['import_file']['name']) and (file_exists($_FILES['import_file']['tmp_name']))) {
            try {
                $uploader = new Varien_File_Uploader('import_file');
                $uploader->setAllowedExtensions(array('csv')); // or pdf or anything


                $uploader->setAllowRenameFiles(false);
                $uploader->setFilesDispersion(false);

                $path = Mage::getBaseDir('var') . DS .'importexport' . DS;

                $uploader->save($path, $_FILES['fileinputname']['name'] = 'example.csv');

                $data['fileinputname'] = $_FILES['fileinputname']['name'];
                return true;
            }catch(Exception $e) {
                Mage::getSingleton('core/session')->addError("File extension is not supported!");
            }
        }
    }

}

Here is an example of the CSV file:

Csv_openof_ex

We’ve finished our brief explanation. Feel free to let us know if you have some questions, and we will be also glad to see your thoughts about this post in the comments.