Create an admin panel for our module

In the admin panel, we will create a separate block. In this block we will display the standard list of records (Grid), the form of working with the data. Among the form fields is a field for selecting a picture and an HTML editor for formatted output of content.

For this, we need to create:

  1. Class module controller in the admin panel (will work with data to implement CRUD)
  2. Block class for grid output
  3. Class helper - (we helper will implement the functional output of the full path of the picture and url pictures)
  4. In the configuration file, we need to specify the information about the block and create a menu button to go to our block
  5. Class for grid
  6. Сlass for outputting the form
  7. Widget class of form

Create the controller class of our module in the admin panel

The controller will output a table with a list of records and organize deletion, addition (including mass deletion), and editing data. Also, the controller will save the images that will be transmitted by the form.

Creating a catalog:

app/code/local/My/Articles/controllers/Adminhtml

Create the controller file:

app/code/local/My/Articles/controllers/Adminhtml/ArticlesController.php

Adding the code:

<?php

/**
* Class My_Articles_Adminhtml_ArticlesController
* Class of controller
*      1 displays a list of records
*      2 displays a form for editing data
*      3 processes data from the form + saves the picture
*      4 implements mass data deletion
*/
class My_Articles_Adminhtml_ArticlesController extends Mage_Adminhtml_Controller_Action
{

   /**
    * Output of a table with a list of data
    */
   public function indexAction()
   {
       /**
        * Loading Layout
        */
       $this->loadLayout();
       /**
        * Activate the menu
        */
       $this->_setActiveMenu('myarticles');
       /**
        * We get the block class
        */
       $contentBlock = $this->getLayout()->createBlock('my_articles_block/adminhtml_articles');
       /**
        * Initializing content
        */
       $this->_addContent($contentBlock);
       /**
        * Display the data
        */
       $this->renderLayout();
   }

   /**
    * Output form for adding data
    * In this case, it is thrown on an action packed edit
    */
   public function newAction()
   {
       $this->_forward('edit');
   }

   /**
    * Editing the data
    */
   public function editAction()
   {
       /**
        * Get the model data id if not - 0 (0 is a new record)
        */
       $id = (int) $this->getRequest()->getParam('id');
       /**
        * We get the model
        */
       $model = Mage::getModel('myarticles/articles')->load($id);
       /**
        * We register the model in the global sector
        */
       Mage::register('current_article', $model);
       /**
        * Activate the menu
        */
       $this->loadLayout()->_setActiveMenu('myarticles');
       /**
        * Download the block
        */
       $layout = $this->getLayout()->createBlock('my_articles_block/adminhtml_articles_edit');
       /**
        * Create content
        */
       $this->_addContent($layout);
       /**
        * Display the data
        */
       $this->renderLayout();
   }

   /**
    * Saving data from a form
    */
   public function saveAction()
   {
       /**
        * We receive form data from POST
        */
       if ($data = $this->getRequest()->getPost()) {
           try {
               /**
                * Download helper
                */
               $helper = Mage::helper('myarticles');
               /**
                * Download the model
                */
               $model = Mage::getModel('myarticles/articles');
               /**
                * Pass model data from the POST
                */
               $model->setData($data)->setId($this->getRequest()->getParam('id'));
               /**
                * If you did not specify a date, we pass the current one
                */
               if (!$model->getCreated()){
                   $model->setCreated(now());
               }
               /**
                * Save data to model
                */
               $model->save();
               /**
                * We get the Id model (if we create a new record - id, we find out after saving)
                */
               $id = $model->getId();
               /**
                * We look, whether the form has betrayed a picture
                * From the helper we get the path for the picture and save it
                * If the error - delete the picture
                * If everything is good - write down the name of the picture in the model
                */
               if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
                   $uploader = new Varien_File_Uploader('image');
                   $uploader->setAllowedExtensions(array('jpg', 'jpeg'));
                   $uploader->setAllowRenameFiles(false);
                   $uploader->setFilesDispersion(false);
                   $uploader->save($helper->getImagePath(), $id . '.jpg'); // Upload the image
                   $model->setImage($id . '.jpg');
                   $model->save();
               } else {
                   if (isset($data['image']['delete']) && $data['image']['delete'] == 1) {
                       @unlink($helper->getImagePath($id));
                   }
               }
               /**
                * The result of the save is written to the session and we display a message
                */
               Mage::getSingleton('adminhtml/session')->addSuccess($this->__('Article was saved successfully'));
               Mage::getSingleton('adminhtml/session')->setFormData(false);
               $this->_redirect('*/*/');
           } catch (Exception $e) {
               Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
               Mage::getSingleton('adminhtml/session')->setFormData($data);
               $this->_redirect('*/*/edit', array(
                   'id' => $this->getRequest()->getParam('id')
               ));
           }
           return;
       }
       Mage::getSingleton('adminhtml/session')->addError($this->__('Unable to find item to save'));
       /**
        *  We throw to the page with the list
        */
       $this->_redirect('*/*/');
   }

   /**
    * Deleting one picture
    */
   public function deleteAction()
   {
       /**
        *  Get id records
        */
       if ($id = $this->getRequest()->getParam('id')) {
           try {
               /**
                * Delete the record
                */
               Mage::getModel('myarticles/articles')->setId($id)->delete();
               Mage::getSingleton('adminhtml/session')->addSuccess($this->__('Article was deleted successfully'));
           } catch (Exception $e) {
               Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
               $this->_redirect('*/*/edit', array('id' => $id));
           }
       }
       $this->_redirect('*/*/');
   }

   /**
    * Mass deleting of records
    */
   public function massDeleteAction()
   {
       /**
        * We get the list of id records
        */
       $articles = $this->getRequest()->getParam('article', null);
       /**
        * If there are entries - we go around and delete one by one
        * After deletion, we go to the list of records and display the result in the message
        */
       if (is_array($articles) && sizeof($articles) > 0) {
           try {
               foreach ($articles as $id) {
                   Mage::getModel('myarticles/articles')->setId($id)->delete();
               }
               $this->_getSession()->addSuccess($this->__('Total of %d articles have been deleted', sizeof($articles)));
           } catch (Exception $e) {
               $this->_getSession()->addError($e->getMessage());
           }
       } else {
           $this->_getSession()->addError($this->__('Please select article'));
       }
       $this->_redirect('*/*');
   }
}

Create a helper class

We need a helper for various frequently repeated service cases, for example, when we display our data on the frontend-we will need to determine the presence of image files and our helper will help us returning the full path to the file by the record id. Also, our helper will help to return url images in general, we can implement different usefulness in it.

Creating a Catalog:

app/code/local/My/Articles/Helper

Create a file:

app/code/local/My/Articles/Helper/Data.php

Adding the code:

<?php

/**
 * Class My_Articles_Helper_Data
 * Class helper
 * Implements the output of the full path to id
 * and output url to the record id
 */
class My_Articles_Helper_Data extends Mage_Core_Helper_Abstract
{

    /**
     * The function implements the output of the full path to the picture file by the record id
     * We pass the record id
     * @param int $id
     * @return string
     */
    public function getImagePath($id = 0)
    {
        $path = Mage::getBaseDir('media') . '/my_articles';
        if ($id) {
            return "{$path}/{$id}.jpg";
        } else {
            return $path;
        }
    }

    /**
     * The function implements the output of the url to the picture file by the record id
     * We pass the record id
     * @param int $id
     * @return string
     */
    public function getImageUrl($id = 0)
    {
        $url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'my_articles/';
        if ($id) {
            return $url . $id . '.jpg';
        } else {
            return $url;
        }
    }
}

Create a block class in the admin panel

Block classes are used by Magento to output data on the page. So, we pass the logic, which is necessary for output, to the classes of blocks, and the controllers transfer the data processing functionality obtained from the form and storing them in the database.

Creating directories:

app/code/local/My/Articles/Block
app/code/local/My/Articles/Block/Adminhtml

Create a file:

app/code/local/My/Articles/Block/Adminhtml/Articles.php

Adding the code:

<?php

class My_Articles_Block_Adminhtml_Articles extends Mage_Adminhtml_Block_Widget_Grid_Container
{

    protected function _construct()
    {
        parent::_construct();
        $helper = Mage::helper('myarticles');
        $this->_blockGroup = 'my_articles_block';
        $this->_controller = 'adminhtml_articles';
        $this->_headerText = $helper->__('Article Management');
        $this->_addButtonLabel = $helper->__('Add Article');
    }
}

Adding parameters to the configuration file

In this file we will point Magento to our module, add a button to the menu and specify the information about our block.

app/code/local/My/Articles/etc/config.xml

We need to add blocks (see comments):

  1. Code for the block
  2. Code for admin panel
  3. Code for the admin panel menu
<?xml version="1.0" ?>
<config>
   <modules>
       <My_Articles>
           <version>1.0.0</version>
       </My_Articles>
   </modules>
   <!-- Code for controller -->
   <frontend>
       <routers>
           <marticles>
               <use>standard</use>
               <args>
                   <module>My_Articles</module>
                   <frontName>articles</frontName>
               </args>
           </marticles>
       </routers>
   </frontend>
   <global>
       <!-- Code for models -->
       <models>
           <myarticles>
               <class>My_Articles_Model</class>
               <resourceModel>myarticles_recource</resourceModel>
           </myarticles>
           <!-- The code for the model resources -->
           <myarticles_recource>
               <class>My_Articles_Model_Resource</class>
               <entities>
                   <table_myarticles>
                       <table>my_articles</table>
                   </table_myarticles>
               </entities>
           </myarticles_recource>
       </models>
       <!-- Code for adding tables to the database -->
       <resources>
           <marticles_setup>
               <setup>
                   <module>My_Articles</module>
               </setup>
           </marticles_setup>
       </resources>
       <!-- Code for the block -->
       <blocks>
           <my_articles>
               <class>My_Articles_Block</class>
           </my_articles>
       </blocks>
       <!-- Code for the helper -->
       <helpers>
           <myarticles>
               <class>My_Articles_Helper</class>
           </myarticles>
       </helpers>
   </global>
   <!-- Code for the admin panel -->
   <admin>
       <routers>
           <myarticles_admin>
               <use>admin</use>
               <args>
                   <module>My_Articles</module>
                   <frontName>myarticles_admin</frontName>
               </args>
           </myarticles_admin>
       </routers>
   </admin>
   <!-- Code for the admin menu -->
   <adminhtml>
       <menu>
           <myarticles module="myarticles">
               <title>My Articles</title>
               <sort_order>77</sort_order>
               <action>myarticles_admin/adminhtml_articles</action>
           </myarticles>
       </menu>
   </adminhtml>
</config>

Create a Grid (output list of articles) in the admin panel

Here we form the grid output. We specify which fields we will output and create a drop-down list for actions with records.

Create a folder:

app/code/local/My/Articles/Block/Adminhtml/Articles

Create a file:

app/code/local/My/Articles/Block/Adminhtml/Articles/Grid.php

Adding the code:

<?php

class My_Articles_Block_Adminhtml_Articles_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

    /**
    Initialize the collection
     */
    protected function _prepareCollection()
    {
        $collection  = Mage::getModel("myarticles/articles")->getCollection();
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    /**
    Specify the fields that we want to see in the grid
     */
    protected function _prepareColumns()
    {
        $helper = Mage::helper('myarticles');
        $this->addColumn('id', array(
            'header' => $helper->__('Articles ID'),
            'width' => '50px',
            'index' => 'id'
        ));
        $this->addColumn('title', array(
            'header' => $helper->__('Title'),
            'index' => 'title',
            'type' => 'text',
        ));
        $this->addColumn('created', array(
            'header' => $helper->__('Created'),
            'index' => 'created',
            'type' => 'date',
        ));
        return parent::_prepareColumns();
    }

    /**
     * Return a link to the data editing for
     * Clicking on the grid line - we will proceed to this form
     * @param $model
     * @return string
     */
    public function getRowUrl($model)
    {
        return $this->getUrl('*/*/edit', array(
            'id' => $model->getId(),
        ));
    }

    /**
     * In the grid header, you will see a drop-down list for selecting actions
     * Here we add a parameter to the list to delete the selected records
     * @return $this
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('id');
        $this->getMassactionBlock()->setFormFieldName('article');
        $this->getMassactionBlock()->addItem('delete', array(
            'label' => $this->__('Delete'),
            'url' => $this->getUrl('*/*/massDelete'),
        ));
        return $this;
    }
}

Create a block for editing

Here we create a block inside which the widget of the form will be displayed. We also initialize the use of the editor (wysiwyg).

Create a file:

app/code/local/My/Articles/Block/Adminhtml/Articles/Edit.php

Adding the code:

<?php

class My_Articles_Block_Adminhtml_Articles_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{

    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
            $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
        }
    }

    protected function _construct()
    {
        $this->_blockGroup = 'my_articles_block';
        $this->_controller = 'adminhtml_articles';
    }

    public function getHeaderText()
    {
        $helper = Mage::helper('myarticles');
        $model = Mage::registry('current_article');
        if ($model->getId()) {
            return $helper->__("Edit Articles item '%s'", $this->escapeHtml($model->getTitle()));
        } else {
            return $helper->__("Add Article item");
        }
    }
}

Create a form widget class

In this class, we specify the fields that we need in the HTML form.

We create the catalog:

app/code/local/My/Articles/Block/Adminhtml/Articles/Edit

Create a file:

app/code/local/My/Articles/Block/Adminhtml/Articles/Edit/Form.php

Adding the code:

<?php

class My_Articles_Block_Adminhtml_Articles_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{

    protected function _prepareForm()
    {
        $helper = Mage::helper('myarticles');
        $model = Mage::registry('current_article');
        $form = new Varien_Data_Form(array(
            'id' => 'edit_form',
            'action' => $this->getUrl('*/*/save', array(
                'id' => $this->getRequest()->getParam('id')
            )),
            'method' => 'post',
            'enctype' => 'multipart/form-data'
        ));
        $this->setForm($form);
        $fieldset = $form->addFieldset('myarticles_form', array('legend' => $helper->__('Article Information')));
        $fieldset->addField('title', 'text', array(
            'label' => $helper->__('Title'),
            'required' => true,
            'name' => 'title',
        ));
        $fieldset->addField('image', 'image', array(
            'label' => $helper->__('Image'),
            'name' => 'image',
        ));
        $fieldset->addField('header_h1', 'text', array(
            'label' => $helper->__('Header H1'),
            'required' => true,
            'name' => 'header_h1',
        ));
        $fieldset->addField('meta_tag_keywords', 'text', array(
            'label' => $helper->__('Keywords (SEO)'),
            'required' => true,
            'name' => 'meta_tag_keywords',
        ));
        $fieldset->addField('meta_tag_description', 'text', array(
            'label' => $helper->__('Description (SEO)'),
            'required' => true,
            'name' => 'meta_tag_description',
        ));
        $fieldset->addField('preview', 'editor', array(
            'label' => $helper->__('Preview'),
            'required' => true,
            'name' => 'preview',
        ));
        $fieldset->addField('content', 'editor', array(
            'label' => $helper->__('Content'),
            'wysiwyg' => true,
            'required' => true,
            'config' => Mage::getSingleton('cms/wysiwyg_config'),
            'name' => 'content',
        ));
        $fieldset->addField('created', 'date', array(
            'format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT),
            'image' => $this->getSkinUrl('images/grid-cal.gif'),
            'label' => $helper->__('Created'),
            'name' => 'created'
        ));
        $form->setUseContainer(true);
        if($data = Mage::getSingleton('adminhtml/session')->getFormData()){
            $form->setValues($data);
        } else {
            $form->setValues($model->getData());
        }
        return parent::_prepareForm();
    }
}

Article Source: https://кодер.укр/записи/magento-1-создание-модуля-часть-6-админка.