Magento 1.9 – Basic CRUD Operation from Admin Side

crudmagento-1.9

I want to understand the actual crud operation from admin side with coding.

Best Answer

I Found the Perfect Answer for that

Create Controller from admin side app\code\local\Crud\Pro\controllers\Adminhtml\ProController.php

<?php

class Crud_Pro_Adminhtml_ProController extends Mage_Adminhtml_Controller_action
{

    protected function _initAction()
    {
        $this->loadLayout()
            ->_setActiveMenu('pro/items');

        return $this;
    }   

    public function indexAction()
    {
        $this->_initAction()
            ->renderLayout();
    }


    public function editAction() 
    {

        $id     = $this->getRequest()->getParam('id');
        $model  = Mage::getModel('pro/pro')->load($id);


        if ($model->getStdId() || $id == 0) 
        {
            $data = Mage::getSingleton('adminhtml/session')->getFormData(true);                     
            if (!empty($data)) 
            {

                $model->setData($data); //Add Data
            }


            Mage::register('pro_data', $model);  //edit/tab/form.php
            $this->loadLayout();
            $this->_addContent($this->getLayout()->createBlock('pro/adminhtml_pro_edit')) //blocks
                ->_addLeft($this->getLayout()->createBlock('pro/adminhtml_pro_edit_tabs'));
            $this->renderLayout();
        } 
        else
        {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('pro')->__('Not Exist'));
            $this->_redirect('*/*/');
        }
    }

    public function deleteAction()
    {
        if( $this->getRequest()->getParam('id') > 0 ) 
        {

            $id     = $this->getRequest()->getParam('id');
            $model2  = Mage::getModel('pro/pro')->load($id);
            $model = Mage::getModel('pro/pro');             
                $model->setId($this->getRequest()->getParam('id'))
                    ->delete(); //delete operation

                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('successfully deleted'));
                $this->_redirect('*/*/');   

        }
        $this->_redirect('*/*/');
    }   

    public function saveAction() 
    {

        if ($data = $this->getRequest()->getPost())
        {           

                $id= ($this->getRequest()->getParam('id'));
                $model = Mage::getModel('pro/pro')->load($id);              


                $model->setData('id',$this->getRequest()->getPost('id'));//1st title->database 2nd title->form name

                if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '')
                {
                    /* Starting upload */   
                    $uploader = new Varien_File_Uploader('filename');

                    // Any extention would work
                    $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setAllowCreateFolders(true);
                    $uploader->setFilesDispersion(false);
                    $path = Mage::getBaseDir('media') . DS. 'test' ;                    
                    $uploader->save($path, $_FILES['filename']['name'] );
                    $model->setData('filename',$_FILES['filename']['name']);

                }





                $model->setData('stdname',$this->getRequest()->getPost('stdname'));
                $model->setData('email',$this->getRequest()->getPost('email'));
                $model->setData('rollno',$this->getRequest()->getPost('rollno'));


                $model->setData('status',$this->getRequest()->getPost('status'));
                $model->save();
                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('pro')->__('successfully saved'));
                $this->_redirect('*/*/');
                return;
        }

    }

    public function enableAction()
    {
        $id     = $this->getRequest()->getParam('id'); // form nu id che
        $model  = Mage::getModel('pro/pro')->load($id);
        $model->setData('status',"0");
        $model->save();
        $this->_redirect('*/*/index');
    }
    public function disableAction()
    {
        $id     = $this->getRequest()->getParam('id');
        $model  = Mage::getModel('pro/pro')->load($id);
        $model->setData('status',"1");
        $model->save();
        $this->_redirect('*/*/index');  

    }








    public function massDeleteAction() 
    {
            $sampleIds = $this->getRequest()->getParam('pro'); // getparam and getparams em be che result jovu hoy to getparams lakhvu jema pro ma value set che
            //print_r($sampleIds);
            //die;
             if(!is_array($sampleIds))
            {
                Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
            } 
            else 
            {
                try
                {
                    foreach ($sampleIds as $sampleId)
                    {
                        $sample = Mage::getModel('pro/pro')->load($sampleId);
                        $sample->delete();

                        $imageDir = Mage::getBaseDir('media').'/test/'.$sample->getFilename();
                        unlink($imageDir);  // delete image from local directory //
                    }
                    Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__('Total of %d record(s) were successfully deleted', count($sampleIds)));
                } 
                catch (Exception $e)
                {
                        Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                }
            }
                $this->_redirect('*/*/index');
    }



    public function massStatusAction()
    {

         $sampleIds = $this->getRequest()->getParam('pro');
//  $sampleIdss = $this->getRequest()->getPost('title');         
        if(!is_array($sampleIds))
        {
            Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
        }
        else
        {

            foreach ($sampleIds as $sampleId)
            {
                $sample = Mage::getSingleton('pro/pro')
                        ->load($sampleId)
                        ->setStatus($this->getRequest()->getParam('status'))
                        ->setIsMassupdate(true)
                        ->save();
            }
                $this->_getSession()->addSuccess($this->__('Total of %d record(s) were successfully updated', count($sampleIds)));
        }
        $this->_redirect('*/*/index');      
    }
}

Create Block from admin side app\code\local\Crud\Pro\Block\Adminhtml\Pro.php

<?php
class Crud_Pro_Block_Adminhtml_Pro extends Mage_Adminhtml_Block_Widget_Grid_Container
{
  public function __construct()
  {
    $this->_controller = 'adminhtml_pro';
    $this->_blockGroup = 'pro';
    $this->_headerText = Mage::helper('pro')->__('Manager');
    $this->_addButtonLabel = Mage::helper('pro')->__('Add Item');
    parent::__construct();

  }
}

Create edit functionality app\code\local\Crud\Pro\Block\Adminhtml\Pro\Edit.php

<?php

class Crud_Pro_Block_Adminhtml_Pro_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        parent::__construct();

        $this->_objectId = 'id';
        $this->_blockGroup = 'pro';
        $this->_controller = 'adminhtml_pro';

        $this->_updateButton('save', 'label', Mage::helper('pro')->__('Save Item'));
        $this->_updateButton('delete', 'label', Mage::helper('pro')->__('Delete'));
    }
      public function getHeaderText()
    {
        if( Mage::registry('pro_data') && Mage::registry('pro_data')->getId() ) {
            return Mage::helper('pro')->__("Edit Discount '%s'", $this->htmlEscape(Mage::registry('pro_data')->getGroup_name()));
        } else {
            return Mage::helper('pro')->__('Add Discount');
        }
    }
}

Create a grid from admin side

app\code\local\Crud\Pro\Block\Adminhtml\Pro\Grid.php

<?php

class Crud_Pro_Block_Adminhtml_Pro_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
  public function __construct()
  {
      parent::__construct();
      $this->setId('proGrid');
      $this->setDefaultSort('std_id');
      $this->setDefaultDir('ASC');
      $this->setSaveParametersInSession(true);
  }

  protected function _prepareCollection()
  {
      $collection = Mage::getModel('pro/pro')->getCollection();
      $this->setCollection($collection);
      return parent::_prepareCollection();
  }

  protected function _prepareColumns()
  {
      $this->addColumn('std_id', array(
          'header'    => Mage::helper('pro')->__('ID'),
          'align'     =>'right',
          'width'     => '50px',
          'index'     => 'std_id',
      ));   

      $this->addColumn('stdname', array(
          'header'    => Mage::helper('pro')->__('Name'),
          'align'     =>'right',
          'width'     => '50px',
          'index'     => 'stdname',
      ));   

      $this->addColumn('email', array(
          'header'    => Mage::helper('pro')->__('Email'),
          'align'     =>'right',
          'width'     => '50px',
          'index'     => 'email',
      ));

          $this->addColumn('rollno', array(
          'header'    => Mage::helper('pro')->__('Rollno'),
          'align'     =>'right',
          'width'     => '50px',
          'index'     => 'rollno',
      ));    

    $this->addColumn('filename', array(
            'header'    => Mage::helper('pro')->__('image'),
            'width'     => '97',
            'align'     =>'left',
            'index'     => 'filename',
            'renderer' => 'Crud_Pro_Block_Adminhtml_Renderer_Image'

        ));   

          $this->addColumn('status', array(
          'header'    => Mage::helper('pro')->__('status'),
          'align'     =>'right',
          'width'     => '50px',
          'index'     => 'status',
          'type'      => 'options',
          'options'    => array(
                                0 => 'enable',
                                1 => 'disable'
                            ),
      ));    

      $this->addColumn('status1',
            array(
                'header'    =>  Mage::helper('pro')->__('Status'),
                'width'     => '100',
                'type'      => 'action',
                'getter'    => 'getId',
                'actions'   => array(
                    array(
                        'caption'   => Mage::helper('pro')->__('Enable'),
                        'url'       => array('base'=> '*/*/enable'),
            'confirm'  => Mage::helper('pro')->__('Do you Want to Continue?'),
                        'field'     => 'id'
                    ),
            array(
                        'caption'   => Mage::helper('pro')->__('Disable'),
                        'url'       => array('base'=> '*/*/disable'),
            'confirm'  => Mage::helper('pro')->__('Do you Want to Continue?'),
                        'field'     => 'id'
                    )

        )));




      return parent::_prepareColumns();
  }   

    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('std_id');
        $this->getMassactionBlock()->setFormFieldName('pro');

        $this->getMassactionBlock()->addItem('delete', array(
             'label'    => Mage::helper('pro')->__('Delete'),
             'url'      => $this->getUrl('*/*/massDelete'),
             'confirm'  => Mage::helper('pro')->__('Are you sure?')
        ));



        $statuses = array("0"=>"Enable", "1"=>"Disable" );
        //array_unshift($statuses, array('label'=>'', 'value'=>''));
        $this->getMassactionBlock()->addItem('status', array(
             'label'=> Mage::helper('pro')->__('Change status'),
             'url'  => $this->getUrl('*/*/massStatus', array('_current'=>true)),
             'additional' => array(
                    'visibility' => array(
                         'name' => 'status',
                         'type' => 'select',
                         'class' => 'required-entry',
                         'label' => Mage::helper('pro')->__('Status'),
                         'values' => $statuses))));       
        return $this;
    }



  public function getRowUrl($row)
  {
      return $this->getUrl('*/*/edit', array('id' => $row->getId()));
  }  
}

Now Come to Edit Part 1.edit tab 2.edit form

app\code\local\Crud\Pro\Block\Adminhtml\Pro\Edit\Tabs.php

<?php

class Crud_Pro_Block_Adminhtml_Pro_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{

  public function __construct()
  {
      parent::__construct();
      $this->setId('pro_tabs');
      $this->setDestElementId('edit_form');
      $this->setTitle(Mage::helper('pro')->__('Information'));
  }

  protected function _beforeToHtml()
  {
      $this->addTab('form_section', array(
          'label'     => Mage::helper('pro')->__('Tabs Folder Information'),         
          'content'   => $this->getLayout()->createBlock('pro/adminhtml_pro_edit_tab_form')->toHtml(), //controller ma action call thay
      ));

      $this->addTab('form_section1', array(
          'label'     => Mage::helper('pro')->__('Product'),         
          'content'   => $this->getLayout()->createBlock('pro/adminhtml_pro_edit_tab_form')->toHtml(),
      ));

      return parent::_beforeToHtml();
  }


}

Create Edit form when click on grid part 1 the actual form is in part 2 app\code\local\Crud\Pro\Block\Adminhtml\Pro\Edit\Form.php

<?php

class Crud_Pro_Block_Adminhtml_Pro_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
  protected function _prepareForm()
  {
      $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'
                                   )
      );

      $form->setUseContainer(true);
      $this->setForm($form);
      return parent::_prepareForm();
  }
}

Create Edit form when click on grid part 2 app\code\local\Crud\Pro\Block\Adminhtml\Pro\Edit\Tab\Form.php

<?php

class Crud_Pro_Block_Adminhtml_Pro_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
  protected function _prepareForm()
  {
      $form = new Varien_Data_Form();
      $this->setForm($form);
      $fieldset = $form->addFieldset('abc', array('legend'=>Mage::helper('pro')->__('inform12ation')));

      $id = $this->getRequest()->getParam('id');
      $model = Mage::getModel('pro/pro')->load($id);

      $fieldset->addField('std_id', 'text', array(
          'label'     => Mage::helper('pro')->__('id'),
          'readonly' => true,
          'name'      => 'id',
          'value' => $model->getData('std_id'),
      ));
      $fieldset->addField('stdname', 'text', array(
          'label'     => Mage::helper('pro')->__('stdname'),          
          'name'      => 'stdname',
          'value' => $model->getData('stdname'),
      ));
      $fieldset->addField('email', 'text', array(
          'label'     => Mage::helper('pro')->__('email'),          
          'name'      => 'email',
          'value' => $model->getData('email'),
      ));
      $fieldset->addField('rollno', 'text', array(
          'label'     => Mage::helper('pro')->__('rollno'),          
          'name'      => 'rollno',
          'value' => $model->getData('rollno'),
      ));        

      $fieldset->addType('image', 'Crud_Pro_Block_Adminhtml_Adminimage_Image');

      $fieldset->addField('filename', 'image', array(
          'label'     => Mage::helper('pro')->__('Image'), 
          'name'      => 'filename',
          //'style'   => "display:none;"

      ));    
      $fieldset->addField('status', 'select', array(
          'label'     => Mage::helper('pro')->__('status'),          
          'name'      => 'status',
          'values' => array('1'=>'Enable','0' => 'Disable'),

      ));




      if ( Mage::registry('pro_data') ) {//edit karye etle data form ma dekhay che ne ena mate ani effect procontroller ma che procontroller ma 38 line
          $form->setValues(Mage::registry('pro_data')->getData());
      }
      return parent::_prepareForm();
  }
}

For Upload Image we want to create renderer folder app\code\local\Crud\Pro\Block\Adminhtml\Renderer\Image.php

<?php 
class Crud_Pro_Block_Adminhtml_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {
        //print_r($row->getData());
        //exit;
        $value = $row->getData($this->getColumn()->getIndex());
        if($value == "")
        {
            echo "Please Select image";
            return;
        }
        //return '<span style="color: white;font-size: 50px;">'.$value.'</span>';
        return '<img src='.Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'test/'.$value.' width="50px" height"50px"/>';
    }
}
?>

app\code\local\Crud\Pro\Block\Adminhtml\Adminimage\Image.php use to show image thumbnail from admin grid side

<?php

class Crud_Pro_Block_Adminhtml_Adminimage_Image extends Varien_Data_Form_Element_Image
 {
    protected function _getUrl(){
        $url = false;
        if ($this->getValue()) {
            $url = Mage::getBaseUrl('media').'test/'.$this->getValue();
        }
        return $url;
    }
}

?>

app\design\adminhtml\default\default\layout\pro.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <pro_adminhtml_pro_index>
        <reference name="content">
            <block type="pro/adminhtml_pro" name="pro" />
        </reference>
    </pro_adminhtml_pro_index>
</layout>
Related Topic