0

I'm using Magento 1.9.0.1 and i'm working a custom extension.

Right now i'm stuck on the part of creating a admin form. Let me show you.

Here is the grid table in a custom page which i've created in the admin fetching data from custom MySQL table called VivasIndustries_SmsNotification:

enter image description here

When i click on a row with result here is what i get:

enter image description here

As you can see the input fields Receiver, Phone and Date are blank, but they must not be blank. This is an edit form and these fields must hold the data printed in the row in the grid table. Also when i hit save it should save the edited data, but it is not working.

I've done all that part for the form from this guide: http://www.smashingmagazine.com/2014/03/13/tutorial-create-admin-manageable-magento-entity-brands/

So let me show you what i have done so far:

I have in: /app/code/community/VivasIndustries/SmsNotification/etc/config.xml:

<?xml version="1.0"?>
<config>
  <modules>
    <VivasIndustries_SmsNotification>
      <version>0.1.0</version>
    </VivasIndustries_SmsNotification>
  </modules>
  <global>
    <models>
        <smsnotification>
            <class>VivasIndustries_SmsNotification_Model</class>
            <resourceModel>vivasindustries_smsnotification_resource</resourceModel>
        </smsnotification>
        <vivasindustries_smsnotification_resource>
        <class>VivasIndustries_SmsNotification_Model_Resource</class>
        <entities>
            <smsnotification>
            <table>VivasIndustries_SmsNotification</table>
            </smsnotification>
        </entities>
        </vivasindustries_smsnotification_resource>
    </models>
    <resources>
        <smsnotification_setup>
            <setup>
                <module>VivasIndustries_SmsNotification</module>
            </setup>
            <connection>
                 <use>core_setup</use>
             </connection>
        </smsnotification_setup>
        <smsnotification_read>
            <connection>
                <use>core_read</use>
            </connection>
        </smsnotification_read>
        <smsnotification_write>
            <connection>
                <use>core_write</use>
            </connection>
        </smsnotification_write>
    </resources>    
    <events>
        <sales_order_save_after>
            <observers>
                <vivasindustries_smsnotification>
                    <class>smsnotification/observer</class>
                    <method>orderSaved</method>
                </vivasindustries_smsnotification>
            </observers>
        </sales_order_save_after>
    </events>
    <helpers>
        <smsnotification>
            <class>VivasIndustries_SmsNotification_Helper</class>
        </smsnotification>
    </helpers>
    <blocks>
        <smsnotification>
             <class>VivasIndustries_SmsNotification_Block</class>
        </smsnotification>
    </blocks>
  </global>
  <adminhtml>
    <acl>
        <resources>
            <all>
                <title>Allow Everything</title>
            </all>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <vivas>
                                        <title>Vivas - All</title>
                                    </vivas>
                                </children>
                            </config>
                        </children>
                    </system>
                </children>
            </admin>
        </resources>
    </acl>
    <layout>
        <updates>
            <smsnotification>
                <file>smsnotification.xml</file>
            </smsnotification>
        </updates>
    </layout>   
    </adminhtml>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <VivasIndustries_SmsNotification before="Mage_Adminhtml">VivasIndustries_SmsNotification_Adminhtml</VivasIndustries_SmsNotification>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
</config>  

Here is what i have in: /app/code/community/VivasIndustries/SmsNotification/controllers/Adminhtml/SmsorderstatusesController.php:

<?php

class VivasIndustries_SmsNotification_Adminhtml_SmsorderstatusesController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction()
    {
        $this->_title($this->__('SMS Center'))->_title($this->__('SMS Center'));
        $this->loadLayout();
        $this->_setActiveMenu('vivassms');
        $this->_addContent($this->getLayout()->createBlock('smsnotification/adminhtml_sms_status'));
        $this->renderLayout();
    }

    public function gridAction()
    {
        $this->loadLayout();
        $this->getResponse()->setBody(
            $this->getLayout()->createBlock('smsnotification/adminhtml_sms_status_grid')->toHtml()
        );
    }

   public function newAction()
    {  
        $this->loadLayout();
        $this->_setActiveMenu('vivassms');
        $this->renderLayout();
    }  

    public function editAction()
    {  
        $this->_initAction();

        // Get id if available
        $id  = $this->getRequest()->getParam('id');
        $model = Mage::getModel('smsnotification/smsnotification');


        $this->_initAction()
            ->_addBreadcrumb($id ? $this->__('Edit Baz') : $this->__('New Baz'), $id ? $this->__('Edit Baz') : $this->__('New Baz'))
            ->_addContent($this->getLayout()->createBlock('smsnotification/adminhtml_sms_status_edit')->setData('action', $this->getUrl('*/*/save')))
            ->renderLayout();
    }

    protected function _initAction()
    {
        $this->loadLayout()
            // Make the active menu match the menu config nodes (without 'children' inbetween)
            ->_setActiveMenu('vivassms')
            ->_title($this->__('SMS Rule'))->_title($this->__('SMS Center'))
            ->_addBreadcrumb($this->__('SMS Rule'), $this->__('SMS Rule'));

        return $this;
    }


    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('sales/foo_bar_baz');
    }
}

Here is what i have in: /app/code/community/VivasIndustries/SmsNotification/Model/Smsnotification.php:

<?php
class VivasIndustries_SmsNotification_Model_Smsnotification extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('smsnotification/smsnotification');
    }

}

Here is what i have in: /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status.php:

<?php

class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    {
        $this->_blockGroup = 'smsnotification';
        $this->_controller = 'adminhtml_sms_status';
        $this->_headerText = Mage::helper('smsnotification')->__('Send SMS on Order Status Changes');
        $this->_addButtonLabel = Mage::helper('smsnotification')->__('Create new SMS Rule');
        parent::__construct();
    }

    protected function _prepareLayout()
    {
        $this->setChild( 'grid',
            $this->getLayout()->createBlock( $this->_blockGroup.'/' . $this->_controller . '_grid',
                $this->_controller . '.grid')->setSaveParametersInSession(true) );
        return parent::_prepareLayout();
    }



}

Here is what i have in: /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Grid.php:

<?php

class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId('smsnotification_grid');
        $this->setDefaultSort('id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
    }


    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('smsnotification/smsnotification_collection');
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }


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

          $this->addColumn('Receiver', array(
              'header'    => Mage::helper('smsnotification')->__('Receiver'),
              'align'     =>'left',
              'index'     => 'Receiver',
          ));

        $this->addColumn('Phone', array(
            'header'    => Mage::helper('smsnotification')->__('Phone'),
            'align'     =>'left',
            'index'     => 'Phone',
        ));

        $this->addColumn('Date', array(
            'header'    => Mage::helper('smsnotification')->__('Date'),
            'align'     =>'left',
            'index'     => 'Date',

        ));


        return parent::_prepareColumns();
    }

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

Here is what i have in: /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Edit.php:

<?php
class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    protected function _construct()
    {
        $this->_blockGroup = 'smsnotification';
        $this->_controller = 'adminhtml_sms_status';


        $this->_mode = 'edit';

        $newOrEdit = $this->getRequest()->getParam('id')
            ? $this->__('Edit')
            : $this->__('New');
        $this->_headerText =  $newOrEdit . ' ' . $this->__('SMS Rule');
    }
}

Here is what i have in: /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Edit/Form.php:

<?php
class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
        // Instantiate a new form to display our brand for editing.
        $form = new Varien_Data_Form(array(
            'id' => 'edit_form',
            'action' => $this->getUrl(
                'smsorderstatuses/edit',
                array(
                    '_current' => true,
                    'continue' => 0,
                )
            ),
            'method' => 'post',
        ));
        $form->setUseContainer(true);
        $this->setForm($form);

        // Define a new fieldset. We need only one for our simple entity.
        $fieldset = $form->addFieldset(
            'general',
            array(
                'legend' => $this->__('Brand Details')
            )
        );

        $brandSingleton = Mage::getSingleton(
            'smsnotification/smsnotification'
        );

        // Add the fields that we want to be editable.
        $this->_addFieldsToFieldset($fieldset, array(
            'Receiver' => array(
                'label' => $this->__('Receiver'),
                'input' => 'text',
                'required' => true,
            ),
            'Phone' => array(
                'label' => $this->__('Phone'),
                'input' => 'text',
                'required' => true,
            ),
            'Date' => array(
                'label' => $this->__('Date'),
                'input' => 'text',
                'required' => true,
            ),
        ));

        return $this;
    }

    protected function _addFieldsToFieldset(
        Varien_Data_Form_Element_Fieldset $fieldset, $fields)
    {
        $requestData = new Varien_Object($this->getRequest()
            ->getPost('smsnotificationData'));

        foreach ($fields as $name => $_data) {
            if ($requestValue = $requestData->getData($name)) {
                $_data['value'] = $requestValue;
            }

            // Wrap all fields with brandData group.
            $_data['name'] = "brandData[$name]";

            // Generally, label and title are always the same.
            $_data['title'] = $_data['label'];

            // If no new value exists, use the existing brand data.
            if (!array_key_exists('value', $_data)) {
                $_data['value'] = $this->_getSms()->getData($name);
            }

            // Finally, call vanilla functionality to add field.
            $fieldset->addField($name, $_data['input'], $_data);
        }

        return $this;
    }

    protected function _getSms()
    {
        if (!$this->hasData('brand')) {
            // This will have been set in the controller.
            $smsnotification = Mage::registry('current_brand');

            // Just in case the controller does not register the brand.
            if (!$smsnotification instanceof
                    VivasIndustries_SmsNotification_Model_Smsnotification) {
                $smsnotification = Mage::getModel(
                    'smsnotification/smsnotification'
                );
            }

            $this->setData('smsnotification', $smsnotification);
        }

        return $this->getData('smsnotification');
    }
}

I have two problem for which i need you to help me out please:

  1. Edit fields are not showing the data when they must show it and the save function is not working.
  2. When i edit a row the Delete function is not working. Where is my mistake?
  3. When i click Create new SMS Rule i'm redirected to blank page. The newAction function is totaly wrong. I can not insert a new data in the mysql table VivasIndustries_SmsNotification.

Please give me a detailed help response.

Thanks in advance!

5

As for your delete button not working, you forgot the deleteAction..

  public function deleteAction()
{
    $brand = Mage::getModel('smashingmagazine_branddirectory/brand');

    if ($brandId = $this->getRequest()->getParam('id', false)) {
        $brand->load($brandId);
    }

    if ($brand->getId() _getSession()->addError(
            $this->__('This brand no longer exists.')
        );
        return $this->_redirect(
            'smashingmagazine_branddirectory_admin/brand/index'
        );
    }

    try {
        $brand->delete();

        $this->_getSession()->addSuccess(
            $this->__('The brand has been deleted.')
        );
    } catch (Exception $e) {
        Mage::logException($e);
        $this->_getSession()->addError($e->getMessage());
    }

    return $this->_redirect(
        'smashingmagazine_branddirectory_admin/brand/index'
    );
}
  • Please edit your answer to work for my example. Thanks – Venelin Vasilev Feb 13 '15 at 20:09
  • Like this the deleteAction() is not working and i can not accept the answer – Venelin Vasilev Feb 13 '15 at 20:10
  • 4
    @TonyStark if you want me to edit my answer to work for your example - why not hire me to create your extension ;) – JELLEJ Feb 13 '15 at 20:11
1

Okay, so for the first issue:

  1. In the function addFieldToFieldset take a look at this line

    protected function _addFieldsToFieldset(
        Varien_Data_Form_Element_Fieldset $fieldset, $fields)
    {
        $requestData = new Varien_Object($this->getRequest()
            ->getPost('smsnotificationData')); //it needs 'smsnotificationData'
        ....
    

    This line is getting all the values sent through POST when the form is submitted. The values are wrapped in an array called 'smsnotificationData'. Later in that same function, you find these lines:

        // Wrap all fields with brandData group.
        $_data['name'] = "brandData[$name]";
    

    Change it to:

        // Wrap all fields with smsnotificationData group.
        $_data['name'] = "smsnotificationData[$name]";
    

    If you inspect the input elements in the form with your browser you'll that they're something like:

    <input type="text" name="smsnotificationData[field]" id="smsnotificationData[field]" />
    

For the second issue:

  1. You need to create the DeleteAction in your controller:

    public function deleteAction()
    {
        $smsnotification = Mage::getModel('vivasindustries_smsnotification/smsnotification');
    
        if ($smsnotificationId = $this->getRequest()->getParam('id', false)) {
            $smsnotification->load($smsnotificationId);
        }
    
        if (!$smsnotification->getId()) {
            $this->_getSession()->addError(
                $this->__('This smsnotification no longer exists.')
            );
            return $this->_redirect(
                '*/*/index'
            );
        }
    
        try {
            $smsnotification->delete();
    
            $this->_getSession()->addSuccess(
                $this->__('The smsnotification has been deleted.')
            );
        } catch (Exception $e) {
            Mage::logException($e);
            $this->_getSession()->addError($e->getMessage());
        }
    
        return $this->_redirect(
            '*/*/index'
        );
    }
    

For the third issue:

  1. The article uses edit action to add new records too. You're missing the getCreateUrl function in your Grid Container:

    public function getCreateUrl()
    {
        /**
         * When the "Add" button is clicked, this is where the user should
         * be redirected to - in our example, the method editAction of
         * SmsnotificationController.php in Smsnotification module.
         */
        return $this->getUrl(
            'vivasindustries_smsnotification_admin/smsnotification/edit'
        );
    }. 
    

You can check the url you are sent to when you click "Add New" and see if it matches any action in your controller. If you really want a separate newAction you'll need two form containers and two forms. AND an action to handle the form submission and save it. So that's why the article does it in one shot. It's repetitive code. Try and read the code in the article very carefully. I assure you it's okay because I have a module up and running based on this exact same example.

  • There is an error in the deleteAction on the line if ($smsnotification->getId() _getSession()->addError( with error: Parse error: syntax error, unexpected T_STRING in /public_html/store/app/code/community/VivasIndustries/SmsNotification/controllers/Adminhtml/SmsorderstatusesController.php – Venelin Vasilev Feb 14 '15 at 19:39
  • I corrected the code. Try again. – Vic Feb 14 '15 at 19:53
  • Thanks it seems it is fixing this error because now it showing me the GRID table like before without error. But still after i made everything else you say i still have the same problem. Empty fields in the edit page, no save method working, no delete method working.. I'm going to create a new question so you can check out what i have done :) – Venelin Vasilev Feb 14 '15 at 20:01
  • Please take a look here: magento.stackexchange.com/questions/56088/… I've pasted the code after your answers but i still have the same problem! – Venelin Vasilev Feb 14 '15 at 21:09
0

Looking at your editAction its code regarding the model:

$model = Mage::getModel('smsnotification/smsnotification');

you are not doing anything with that model (like loading data to display in the form) so the form is empty.

The original tutorial its editAction does have the required code to make all of this work:

(section "Creating Our Admin Controller")

    $brand = Mage::getModel('smashingmagazine_branddirectory/brand');

    if ($brandId = $this->getRequest()->getParam('id', false)) {
        $brand->load($brandId); // This is important

        if ($brand->getId() _getSession()->addError(
                $this->__('This brand no longer exists.')
            );
            return $this->_redirect(
                'smashingmagazine_branddirectory_admin/brand/index'
            );
        }
    }

    // [...]

    // Make the current brand object available to blocks.
    Mage::register('current_brand', $brand);

I would suggest taking another good look at the examples given in the tutorial, try to understand the code and adapt it to your needs.

  • Can you please edit this so it will work for my question. When i paste this in the editAction it is not working. Thanks! – Venelin Vasilev Feb 13 '15 at 20:11
  • There is an error, take a look at if ($brandId = $this->getRequest()->getParam('id', false)) {.... – Venelin Vasilev Feb 13 '15 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.