How To Create An Admin-Manageable Magento Entity For Brands: - TopicsExpress



          

How To Create An Admin-Manageable Magento Entity For Brands: In this tutorial, we will create a new “brand” entity in Magento that can be managed through the admin panel. Once we are finished, you will be able to create, update and delete brands that can be viewed in the front-end independently, much in the same way that you can interact with existing entities such as “products” and “categories.” In addition, we will associate our new brand entity with other Magento entities, such as products. The process itself is quite lengthy because I will explain each step in detail, but it really is easy once you know how, and it’s a great example of how powerful the Magento platform can be with minimal effort. We will cover the following topics: * Create a new brand entity in Magento. * Browse, filter and sort brands in Magento’s admin panel. * Create, update and delete brands in the admin panel. * Create a brand list, and view pages in the front-end. * Associate brands with products. * Display a product-brand association in the front-end. * Include images throughout. This tutorial refers to the Magento Community Edition 1.8.0.0, the latest version available at the time of writing. But the code and principles apply to all recent Magento versions, both Community and Enterprise. While I have tried to be as thorough as possible in my explanations, documenting the code is sometimes the best way to explain certain things, so you will find a lot of comments in the code snippets. The code snippet linked to at the end contains more usages and items than are covered in this tutorial, to show you how to extend the things that you will learn about here. Creating Our Module Start by creating the following folder and file structure. For the time being, all files will be empty. Normally, these files and folders would be created one at a time as needed, but for the sake of this tutorial, we will put everything in place up front. As usual, I assume you already know the basics of creating a Magento module and are comfortable with this step, with no explanation required. app - code - community - SmashingMagazine - BrandDirectory - Block - Adminhtml - Brand - Edit - Form.php - Edit.php - Grid.php - Brand.php - Helper - Data.php - Model - Resource - Brand - Collection.php - Brand.php - Brand.php - controllers - Adminhtml - BrandController.php - etc - adminhtml.xml - config.xml - sql - smashingmagazine_branddirectory_setup - install-0.0.1.php - etc - modules - SmashingMagazine_BrandDirectory.xml Module Setup Scripts For our module to be of any use, we need somewhere to store our data. Therefore, we need to write a module setup script to create a database table to hold information about our brand entity. Setup scripts are stored in two places within the module, /sql and /data. The former is for physical changes to your Magento instance, such as database schema updates, and the latter is for populating or removing entries from the existing schema. In our case, we are adding a new table. So, edit the file at sql/smashingmagazine_branddirectory_setup/install-0.0.1.php with the following code: setName($this->getTable(smashingmagazine_branddirectory/brand)); /** * Add the columns we need for now. If you need more later, you can * always create a new setup script as an upgrade. We will introduce * that later in this tutorial. */ $table->addColumn( entity_id, Varien_Db_Ddl_Table::TYPE_INTEGER, 10, array( auto_increment => true, unsigned => true, nullable=> false, primary => true ) ); $table->addColumn( created_at, Varien_Db_Ddl_Table::TYPE_DATETIME, null, array( nullable => false, ) ); $table->addColumn( updated_at, Varien_Db_Ddl_Table::TYPE_DATETIME, null, array( nullable => false, ) ); $table->addColumn( name, Varien_Db_Ddl_Table::TYPE_VARCHAR, 255, array( nullable => false, ) ); $table->addColumn( url_key, Varien_Db_Ddl_Table::TYPE_VARCHAR, 255, array( nullable => false, ) ); $table->addColumn( description, Varien_Db_Ddl_Table::TYPE_TEXT, null, array( nullable => false, ) ); $table->addColumn( visibility, Varien_Db_Ddl_Table::TYPE_BOOLEAN, null, array( nullable => false, ) ); /** * These two important lines are often missed. */ $table->setOption(type, InnoDB); $table->setOption(charset, utf8); /** * Create the table! */ $this->getConnection()->createTable($table); $this->endSetup(); Initializing Our Module At this point, we still do not have an active Magento module; we just have a number of folders and empty files and an installation setup script that does not do anything yet. This is on purpose. In the next steps, we will populate the app/etc/modules XML file and configure config.xml so that Magento knows where to look for our setup script, after which the next visit to the website will trigger the content of our setup script to run. If we had performed these tasks the other way round (that is, configured the module first and then populated the setup script), then there is a chance Magento would think that our module was on version 0.0.1 and that our setup script was still empty and, as a result, that the script would effectively have to be skipped. So, to limit face-palm moments for you guys, I’ve tried to keep the order of steps as safe as possible. Configuring Our Module Edit the file at app/etc/modules/SmashingMagazine_BrandDirectory.xml, and add the following to enable our module: true community You will notice we are using the community codepool. This BrandDirectory module will not contain any client-specific code or customizations. Instead, it will contain the building blocks for our new entity, which can be used in other modules, depending on the use case. Therefore, this community module may be dropped into any Magento instance and used as is, without any code needing to be changed. If code changes were required for each use, then this would be more suitable to the local code pool. Now, we tell Magento that we have a module with a version number, which in fact will determine which setup scripts are run and where to find the setup scripts. Edit etc/config.xml with the following: 0.0.1 smashingmagazine_branddirectory_resource smashingmagazine_branddirectory_brand SmashingMagazine_BrandDirectory Mage_Eav_Model_Entity_Setup core_setup Is Everything Working So Far? Go ahead and access any page of your website — the home page will do. Magento will find that it has a new module at version 0.0.1, yet it has no record of this module in the core_resource database table. This missing entry will trigger Magento to look for an installation setup script and execute its contents. If All Goes Well… If all goes well, then it will seem like nothing has happened. The Magento page might take a few moments longer to load while the contents of our setup script is run (i.e. while the new database table is created), and then the page will continue to load as normal. You now have two tasks to perform to check that everything has gone as expected: * Ensure that Magento knows about your module and that the module is enabled by going to System → Configuration → Advanced → Advanced. * Access your database via either the terminal or something like PHPMyAdmin to see whether Magento has created a new table, smashingmagazine_branddirectory_brand. If All Does Not Go Well… If all does not go well, then it might also seem like nothing has happened, only this time nothing really has happened! The reason for this could be typos in config.xml, badly named folders or files (take care with case-sensitivity) or something else. Go through the previous steps and double-check that everything is as it should be. On the other hand, you might see an error message — perhaps a “PHP Fatal Error” or a report page, depending on the severity of the error. Use your debugging skills to identify the problem and correct it, again double-checking all previous steps in this tutorial. “It Went Wrong. How Do I Try Again?” To try again from scratch, you can perform the following actions — not all may be required, depending on how far Magento got before things went wrong. You will need to access your database directly because this cannot be performed through Magento: * In the core_resource table, delete the single row smashingmagazine_branddirectory_setup. * Delete the smashingmagazine_branddirectory_brand table. Creating Our Helper We don’t actually need to define any custom functionality in a helper for this tutorial. But we will be adding menu items to the admin panel that use a helper for translation purposes, so we can simply create one in Helper/Data.php and forget about it. _init(smashingmagazine_branddirectory/brand); } /** * This method is used in the grid and form for populating the dropdown. */ public function getAvailableVisibilies() { return array( self::VISIBILITY_HIDDEN => Mage::helper(smashingmagazine_branddirectory) ->__(Hidden), self::VISIBILITY_DIRECTORY => Mage::helper(smashingmagazine_branddirectory) ->__(Visible in Directory), ); } protected function _beforeSave() { parent::_beforeSave(); /** * Perform some actions just before a brand is saved. */ $this->_updateTimestamps(); $this->_prepareUrlKey(); return $this; } protected function _updateTimestamps() { $timestamp = now(); /** * Set the last updated timestamp. */ $this->setUpdatedAt($timestamp); /** * If we have a brand new object, set the created timestamp. */ if ($this->isObjectNew()) { $this->setCreatedAt($timestamp); } return $this; } protected function _prepareUrlKey() { /** * In this method, you might consider ensuring * that the URL Key entered is unique and * contains only alphanumeric characters. */ return $this; } } Brand Resource Model As in my introduction to the model above, I won’t go into any more detail than to say that the job of the resource model is to persist and retrieve data from the database. So edit Model/Resource/Brand.php with this: getId() will retrieve the data from the * column named entity_id. */ $this->_init(smashingmagazine_branddirectory/brand, entity_id); } } Brand Resource Collection Finally, we need a resource collection to allow iteration through our brands for things like admin panel grids and front-end listing pages. Edit Model/Resource/Brand/Collection.php with this:
Posted on: Sun, 23 Mar 2014 21:44:10 +0000

Trending Topics



Recently Viewed Topics




© 2015