0

I'm creating a new admin module, when i click on save button in my form, he calls saveAction with all paramaters fields but he saves me NULL value. I think that the problem comes from saveAction() but I don't find what is wrong,

Here is a full code, and if you see somethings wrong somewhere, the corrections are welcome:

app/code/local/Sd/Menu/Block/Adminhtml.Menu.php

<?php
class Sd_Menu_Block_Adminhtml_Menu extends Mage_Adminhtml_Block_Widget_Grid_Container{

  public function __construct()
  {
    $this->_blockGroup     = 'sd_menu';
    $this->_controller     = 'adminhtml_menu';
    $this->_headerText     = $this->__('Gérer le Menu');
    $this->_addButtonLabel = $this->__('Ajouter');
    parent::__construct();
  }

}

app/code/local/Sd/Menu/Block/Adminhtml/Menu/Grid.php

<?php

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

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

    protected function _prepareColumns()
    {
        $this->addColumn('entity_id', array(
          'header'    => $this->__('Id'),
          'align'     =>'right',
          'width'     => '10px',
          'index'     => 'entity_id',
        ));

        $this->addColumn('name', array(
          'header'    => $this->__('Nom'),
          'align'     =>'left',
          'index'     => 'name',
          'width'     => '50px',
        ));


        $this->addColumn('address', array(
            'header'    => $this->__('Adresse'),
            'width'     => '150px',
            'index'     => 'address',
        ));
        return parent::_prepareColumns();
    }
}

app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit/Form.php

<?php
class Sd_Menu_Block_Adminhtml_Menu_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('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
                   '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->__('Informations menu')
            )
        );

        $menuSingleton = Mage::getSingleton('sd_menu/menu');

        // J'ajoute les fields éditables.
        $this->_addFieldsToFieldset($fieldset, array(
            'name' => array(
                'label' => $this->__('Nom'),
                'input' => 'text',
                'required' => true,
            ),
            'address' => array(
                'label' => $this->__('Adresse'),
                'input' => 'textarea',
                'required' => true,
            ),
            'email' => array(
                'label' => $this->__('Email'),
                'input' => 'text',
                'required' => true,
            ),
            'photo' => array(
                'label' => $this->__('Photo'),
                'input' => 'text',
                'required' => true,
            ),

        ));

        return $this;
    }

    /**
     * This method makes life a little easier for us by pre-populating
     * fields with $_POST data where applicable and wrapping our post data
     * in 'brandData' so that we can easily separate all relevant information
     * in the controller. You could of course omit this method entirely
     * and call the $fieldset->addField() method directly.
     */
    protected function _addFieldsToFieldset(
        Varien_Data_Form_Element_Fieldset $fieldset, $fields)
    {
        $requestData = new Varien_Object($this->getRequest()
            ->getPost('menuData'));

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

            // Wrap all fields with brandData group.
            $_data['name'] = "menuData[$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->_getMenu()->getData($name);
            }*/

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

        return $this;
    }

    /**
     * Retrieve the existing brand for pre-populating the form fields.
     * For a new brand entry, this will return an empty brand object.
     */
    protected function _getMenu()
    {
        if (!$this->hasData('menu')) {
            // This will have been set in the controller.
            $menu = Mage::registry('current_menu');

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

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

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

app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit/Tabs.php

<?php
class Sd_Menu_Block_Adminhtml_Menu_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs {

    public function __construct()
    {
        parent::__construct();
        $this->setId('menu_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle('Informations');
    }

    protected function _beforeToHtml()
    {
        $this->addTab('form_section', array(
            'label' => 'A propos',
            'title' => 'A propos',
            'content' => $this->getLayout()
                ->createBlock('sd_menu/adminhtml_menu_edit_tab_form')
                ->toHtml()
        ));

        return parent::_beforeToHtml();
    }
}

app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit/Tab/Form.php

<?php 
class Sd_Menu_Block_Adminhtml_Menu_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form {

    protected function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $this->setForm($form);
        $fieldset = $form->addFieldset('menu_form',
            array('legend'=>'Social network'));
        $fieldset->addField('facebook', 'text',
            array(
                'label' => 'Facebook',
                'class' => 'required-entry',
                'required' => false,
                'name' => 'facebook',
            ));

        if ( Mage::registry('menu_data') )
        {
            $form->setValues(Mage::registry('menu_data')->getData());
        }

        return parent::_prepareForm();
    }
}

app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit.php

<?php
class Sd_Menu_Block_Adminhtml_Menu_Edit extends Mage_Adminhtml_Block_Widget_Form_Container {

    protected function _construct() {

        $this->_blockGroup = 'sd_menu';
        $this->_controller = 'adminhtml_menu';
        $this->_updateButton('save', 'label', 'Sauvegarder');
        $this->_updateButton('delete', 'label', 'Supprimer');

        $this->_mode = 'edit';

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

app/code/local/Sd/Menu/controllers/Adminhtml/MenuController.php

<?php

class Sd_Menu_Adminhtml_MenuController extends Mage_Adminhtml_Controller_Action{

    public function indexAction() {
    $this->loadLayout()
        ->_setActiveMenu('menu1/menu')
        ->_title($this->__('Submenu1')); // for title
    $this->renderLayout();
}

public function listAction() {
    $this->loadLayout()
        ->_setActiveMenu('menu')
        ->_title($this->__('Submenu2'));
    $this->renderLayout();
}


public function editAction()
{
    $menuId = $this->getRequest()->getParam('id');
    $menuModel = Mage::getModel('menu/menu')->load($menuId);
    Mage::register('current_menu', $menuModel); // The add 

    if ($menuModel->getId() || $menuId == 0)
    {
        Mage::register('menu_data', $menuModel);
        $this->loadLayout();
        $this->_setActiveMenu('menu/set_time');
        $this->_addBreadcrumb('menu Manager', 'menu Manager');
        $this->_addBreadcrumb('Menu Description', 'Ingormations');
        $this->getLayout()->getBlock('head')
            ->setCanLoadExtJs(true);
        $this->_addContent($this->getLayout()
            ->createBlock('sd_menu/adminhtml_menu_edit'))
            ->_addLeft($this->getLayout()
                ->createBlock('sd_menu/adminhtml_menu_edit_tabs')
            );
        $this->renderLayout();
    }
    else
    {
        Mage::getSingleton('adminhtml/session')->addError('menu does not exist');
        $this->_redirect('*/*/');
    }
}

public function newAction()
{
    $this->loadLayout();
    $this->_setActiveMenu('menu1/menu');                                                            $this->_addContent($this->getLayout()->createBlock('sd_menu/adminhtml_menu_edit'))
     ->_addLeft($this->getLayout()->createBlock('sd_menu/adminhtml_menu_edit_tabs'));
    $this->renderLayout();
}

public function saveAction()
{
    if ($data = $this->getRequest()->getPost()) {
    //init model and set data
    $model = Mage::getModel('menu/menu');
    if ($id = $this->getRequest()->getParam('id')) {
        $model->load($id);
    }
    $model->addData($data);
    try{
        //try to save it
        $model->save();
        Mage::getSingleton('adminhtml/session')->addSuccess('Saved');
        //redirect to grid.
        $this->_redirect('*/*/'); 
    }
    catch (Exception $e){
        //if there is an error return to edit
        Mage::getSingleton('adminhtml/session')->addError('Not Saved. Error:'.$e->getMessage());
        Mage::getSingleton('adminhtml/session')->setExampleFormData($data);
        $this->_redirect('*/*/edit', array('id'=>$mode->getId(), '_current'=>true)); 
    }
    }
}

public function deleteAction()
{
    if($this->getRequest()->getParam('id') > 0)
    {
        try
        {
            $menuModel = Mage::getModel('menu/menu');
            $menuModel->setId($this->getRequest()->getParam('id'))->delete();
            Mage::getSingleton('adminhtml/session')->addSuccess('successfully deleted');
            $this->_redirect('*/*/');
        }
        catch (Exception $e)
        {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
        }
    }
    $this->_redirect('*/*/');
}

app/code/local/Sd/Menu/Model/Menu.php

<?php
class Sd_Menu_Model_Menu extends Mage_Core_Model_Abstract{

    /**
     * Le constructeur
     */
    public function _construct() {
        parent::_construct();
        $this->_init('menu/menu');
    }
}

app/code/local/Sd/Menu/Model/Resource/Menu.php

<?php

class Sd_Menu_Model_Resource_Menu extends Mage_Core_Model_Resource_Db_Abstract
{
    /**
     * Initialize resource model
     *
     */
    protected function _construct()
    {
        $this->_init('menu/menu', 'entity_id');
    }
}

app/code/local/Sd/Menu/Model/Resource/Menu/Collection.php

<?php
class Sd_Menu_Model_Resource_Menu_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{

    protected function _construct()
    {
        parent::_construct();
        $this->_init('menu/menu');
    }
}

app/code/local/Sd/Menu/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Sd_Menu>
            <version>0.1.0</version>
        </Sd_Menu>
    </modules>
    <global>

        <helpers>
            <sd_menu>
                <class>Sd_Menu_Helper</class>
            </sd_menu>
        </helpers>

        <blocks>
            <sd_menu>
                <class>Sd_Menu_Block</class>
            </sd_menu>
        </blocks>

        <models>
            <menu>
                <class>Sd_Menu_Model</class>
                <resourceModel>menu_resource</resourceModel> //the corercted add
            </menu>
            <menu_resource>
                <class>Sd_Menu_Model_Resource</class>
                <entities>
                    <menu>
                        <table>wlc_sd_menu</table>
                    </menu>
                </entities>
            </menu_resource>
        </models>

        <resources>
            <menu_setup>
                <setup>
                    <module>Sd_Menu</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </menu_setup>
        </resources>

    </global>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <sd_menu before="Mage_Adminhtml">Sd_Menu_Adminhtml</sd_menu>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <adminhtml>
        <layout>
            <updates>
                <sd_menu>
                    <file>sd_menu.xml</file>
                </sd_menu>
            </updates>
        </layout>
    </adminhtml>
</config>

app/code/local/Sd/Menu/etc/adminhtml.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <menu>
        <menu1 module="sd_menu" translate="title">
            <title>Menu 1</title>
            <sort_order>100</sort_order>
            <children>
                <item1 module="sd_menu" translate="title">
                    <title>Submenu 1</title>
                    <sort_order>1</sort_order>
                    <action>adminhtml/menu/index</action>
                </item1>
                <item2 module="sd_menu" translate="title">
                    <title>Submenu 2</title>
                    <sort_order>2</sort_order>
                    <action>adminhtml/menu/list</action>
                </item2>
            </children>
        </menu1>
    </menu>
    <acl>
        <resources>
            <admin>
                <children>
                    <menu1 translate="title" module="sd_menu">
                        <title>My Controller</title>
                        <sort_order>-100</sort_order>
                        <children>
                            <item1 translate="title">
                                <title>Index Action</title>
                                <sort_order>1</sort_order>
                            </item1>
                            <item2 translate="title">
                                <title>List Action</title>
                                <sort_order>2</sort_order>
                            </item2>
                        </children>
                    </menu1>
                </children>
            </admin>
        </resources>
    </acl>
</config>

app/design/adminhtml/default/default/layout/sd_menu.xml

<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
    <adminhtml_menu_index>
        <reference name="content">
            <block type="sd_menu/adminhtml_menu" name="menu"/>
        </reference>
    </adminhtml_menu_index>
</layout>

app/code/local/Sd/Menu/Helper/Data.php

<?php
class Sd_Menu_Helper_Data extends Mage_Core_Helper_Abstract
{

}

app/etc/modules/Sd_Menu.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Sd_Menu>
            <active>true</active>
            <codePool>local</codePool>
        </Sd_Menu>
    </modules>
</config>

app/code/local/Sd/Menu/sql/sd_menu_setup/mysql4-install-0.1.0

<?php

$installer = $this;
$installer->startSetup();
Mage::log('START SCRIPT install sd_menu 0.1.0');

try {
    $this->run("
        CREATE TABLE IF NOT EXISTS `wlc_sd_menu` (
          `entity_id` int(11) NOT NULL AUTO_INCREMENT,
          `name` text NOT NULL,
          `photo` varchar(255) DEFAULT NULL,
          `position` int(11) DEFAULT NULL,
          `address` varchar(255) NOT NULL,
          `email` varchar(255) NOT NULL,
          `facebook` varchar(255) DEFAULT NULL,
          `twitter` varchar(255) DEFAULT NULL,
          `linkedin` varchar(255) DEFAULT NULL,
          `instagram` varchar(255) DEFAULT NULL,
          `google_plus` varchar(255) DEFAULT NULL,
          `status` int(11) NOT NULL DEFAULT '1',
            PRIMARY KEY (`entity_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    ");
    Mage::log("Script OK!");
} catch (Exception $e) { Mage::log('Script KO: '.$e); }


Mage::log('END SCRIPT install sd_menu 0.1.0');
$installer->endSetup();
6
  • Where is your Form.php file? You need <form... in order to save data. May 1, 2017 at 23:22
  • Sorry I forgot it, I added: app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit/Form.php , app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit/Tabs.php and app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit/Tab/Form.php .look my update please.
    – PЯINCƎ
    May 2, 2017 at 4:39
  • Also, when I click on an item in the grid, there is nothing happening
    – PЯINCƎ
    May 2, 2017 at 4:47
  • print_r($data) in saveAction(); and check your data is there ? May 2, 2017 at 4:50
  • Yes, i have all my data with a form key
    – PЯINCƎ
    May 2, 2017 at 5:10

1 Answer 1

1

I still don't see your Edit.php file.

Your Edit.php file:

class Sd_Menu_Block_Adminhtml_Menu_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        $this->_objectId = 'id';
        $this->_blockGroup = 'sd_menu';
        $this->_controller = 'adminhtml_menu';
        $this->_mode = 'edit';

        parent::__construct();

        $this->setId('menu_edit');
    }
}

Now your app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit/Form.php

<?php
class Sd_Menu_Block_Adminhtml_Menu_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('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
                   '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->__('Informations menu')
            )
        );

        $menu = $menu = Mage::registry('current_menu'); //controller must return 'current_menu'

        //for editing
        if ($id = $menu->getId()) {
            $fieldset->addField('entity_id', 'hidden', array(
                'name' => 'entity_id',
                'value' => $id
            ));
        }

        $fieldset->addField('name', 'text', array(
            'label' => $this->__('Nom'),
            'name'  => 'name',
            'required' => true,
            'value' => $menu->getName()
        ));


        //add other fields
        //................
        //................

        $form->setValues($menu->getData());

        $form->setUseContainer(true);

        $this->setForm($form);

        return parent::_prepareForm();
    }
}

Now, app/code/local/Sd/Menu/Block/Adminhtml/Menu/Edit/Tab/Form.php

protected function _prepareForm()
{
    $form = new Varien_Data_Form();
    $fieldset = $form->addFieldset('menu_form',
        array('legend'=>'Social network'));
    $fieldset->addField('facebook', 'text',
        array(
            'label' => 'Facebook',
            'class' => 'required-entry',
            'required' => false,
            'name' => 'facebook',
        ));

    if ( Mage::registry('menu_data') )
    {
        $form->setValues(Mage::registry('menu_data')->getData());
    }

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

}

I haven't tested but this should work. Good luck.

Also for your grid add this function:

public function getGridUrl()
{
    return $this->getUrl('*/*/grid', array('_current'=>true));
}

UPDATE 1

Your controller file functions:

public function editAction()
{
    // 1. Get ID and create model
    $id = $this->getRequest()->getParam('id');
    $model = Mage::getModel('menu/menu');

    // 2. Initial checking
    if ($id) {
        $model->load($id);
        if (!$model->getId()) {
            Mage::getSingleton('adminhtml/session')->addError(
                Mage::helper('sd_menu')->__('This Menu no longer exists.'));
            $this->_redirect('*/*/');
            return;
        }
    }
    $this->_title($model->getName() ? $model->getName() : $this->__('New Menu'));

    // 3. Set entered data if was error when we do save
    $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
    if (! empty($data)) {
        $model->setData($data);
    }

    // 4. Register model to use later in blocks
    Mage::register('current_menu', $model);

    // 5. Build edit form
    $this->_initAction()
        ->_addContent($this->getLayout()->createBlock('sd_menu/adminhtml_menu_edit'))
        ->_addLeft($this->getLayout()
            ->createBlock('sd_menu/adminhtml_menu_edit_tabs')
        );
        ->renderLayout();
}

public function newAction()
{
    $this->_forward('edit');
}

UPDATE 2

For grid click:

/**
 * Retrieve Row Click callback URL
 *
 * @return string
 */
public function getRowUrl($row)
{
    return $this->getUrl('*/*/view', array('id' => $row->getId())); //you may need to change `id` based on your config
}
16
  • in Form.php I have Call to a member function getId() on a non-object in //for editing if ($id = $menu->getId()) { $fieldset->addField('entity_id', 'hidden', array( 'name' => 'entity_id', 'value' => $id )); } and also in 'value' => $menu->getName()
    – PЯINCƎ
    May 2, 2017 at 5:39
  • Inside your editAction() add this: Mage::register('current_menu', $menuModel); May 2, 2017 at 5:42
  • Tha same error, look my editAction please, and i have also error in 'value' => $menu->getName()
    – PЯINCƎ
    May 2, 2017 at 5:53
  • I have double $menu = $menu in form. Remove one. It should be $menu = Mage::registry('current_menu'); //controller must return 'current_menu' May 2, 2017 at 5:56
  • Yes i knew it was a mistake and i already removed it but i still have the same errors, about Edit.php I left my file
    – PЯINCƎ
    May 2, 2017 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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