magento custom admin module save action not working - magento

All I have created magento 1.8 custom module for admin.
It has grid and the add item option. In database table it has 2 fields ID [Auto increment] and NAME.
Everything working fine but when I click on save button it shows the success message but the name field data not saving to the database. only ID is incrementing and shown in the grid
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('fondation_form', array('legend'=>Mage::helper('fondation')->__('Item information')));
$fieldset->addField('Name', 'text', array(
'label' => Mage::helper('fondation')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
));
if (Mage::getSingleton('adminhtml/session')->getFondationData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getFondationData());
Mage::getSingleton('adminhtml/session')->setFondationData(null);
} elseif (Mage::registry('fondation_data')) {
$form->setValues(Mage::registry('fondation_data')->getData());
}
return parent::_prepareForm();
}
my saveAction function
public function saveAction()
{
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('fondation/fondation');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('fondation')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
$this->_redirect('*/*/');
return;
} 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(Mage::helper('fondation')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}

Your code is correct. if you have the field name "Name" in database table then use this code
$fieldset->addField('Name', 'text', array(
'label' => Mage::helper('fondation')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'Name',
));

Related

save and delete buttons are missing from magento adminpanel form and also position of form is left?

i have been following this to create an admin grid view. Grid works fine but when i try to load form to edit or delete or save my entries there is no save and delete button in my form container see here https://www.dropbox.com/s/odk79gsvufpj9j9/Screenshot%20from%202015-08-28%2014%3A37%3A08.png?dl=0
here is my Edit.php
class Best_Test_Block_Adminhtml_Test_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::_construct();
$this->_objectId = 'id';
$this->_blockGroup = 'test';
$this->_controller = 'adminhtml_test';
$this->_updatebutton('save', 'label', 'save user');
$this->_updatebutton('delete', 'label', 'delete user');
}
public function getHeaderText()
{
if (Mage::registry('test_data')&&Mage::registry('test_data')->getId()) {
return 'Edit user '.$this->htmlEscape(Mage::regisrty('test_data')->getTitle()).'<br/>';
}else{
return 'Add a user';
}
}
}
here is my indexController.php in Adminhtml
class Best_Test_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()->_setActiveMenu('test/set_time')->_addBreadcrumb('test Manager', 'test Manager');
return $this;
}
public function indexAction()
{
$this->_initAction();
$this->renderLayout();
}
public function editAction()
{
$testId = $this->getRequest()->getParam('id');
$testModel = Mage::getModel('test/test')->load($testId);
if ($testModel->getId() || $testId == 0) {
Mage::register('test_data', $testModel);
$this->loadLayout();
$this->_setActiveMenu('test/set_time');
$this->_addBreadcrumb('test Manager', 'test Manager');
$this->_addBreadcrumb('Test Description', 'Test Description');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('test/adminhtml_test_edit'))->_addLeft($this->getLayout()->createBlock('test/adminhtml_test_edit_tabs'));
$this->renderLayout();
}else{
Mage::getSingleton('adminhtml/session')->addError('Test does not exist!');
$this->_redirect('*/*/');
}
}
public function newAction()
{
$this->_forward('edit');
}
public function saveAction()
{
if ($this->getRequest()->getPost()) {
try{
$postData = $this->getRequest()->getPost();
$testModel = Mage::getModel('test/test');
if ($this->getRequest()->getParam('id') <= 0) {
$testModel->setCreatedTime(Mage::getSingleton('core/date')->gmtDate());
$testModel->addData($postData)->setUpdateTime(Mage::getSingleton('core/date')->gmtDate())->setId($this->getRequest()->getParam('id'))->save();
Mage::getSingleton('adminhtml/session')->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')->settestData(false);
$this->_redirect('*/*/');
return;
}
} catch (Exception $e){
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->settestData($this->getRequest()->getPost());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return ;
}
}
$this->_redirect('*/*/');
}
public function deleteAction()
{
if ($this->getRequest()->getParam('id') > 0) {
try{
$testModel = Mage::getModel('test/test');
$testModel->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('*/*/');
}
}
here is Form.php in Adminhtml/Test/Edit
class Best_Test_Block_Adminhtml_Test_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',
)
);
$form->setUseContainer(true);
$form->setForm($form);
return parent::_prepareForm();
}
}
here is Tabs.php in Adminhtml/Test/Edit
class Best_Test_Block_Adminhtml_Test_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId('test_tabs');
$this->setDestElementId('edit_form');
$this->setTitle('Information of User');
}
protected function _beforeToHtml()
{
$this->addTab('form_section', array(
'label' => 'User information',
'title' => 'User information',
'content' => $this->getLayout()->createBlock('test/adminhtml_test_edit_tab_form')->toHtml()
));
return parent::_beforeToHtml()
; }
}
here is Form.php in Adminhtml/Test/Edit/Tab
class Best_Test_Block_Adminhtml_Test_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareform()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('test_form', array('legend'=>'ref information'));
$fieldset->addField('name', 'text', array(
'label' => 'name',
'class' => 'required-entry',
'required' => 'true',
'name' => 'name',
));
$fieldset->addField('email', 'text', array(
'label' => 'email',
'class' => 'required-entry',
'required' => 'true',
'name' => 'email',
));
$fieldset->addField('password', 'password', array(
'label' => 'password',
'class' => 'required-entry',
'required' => 'true',
'name' => 'password',
));
if (Mage::registry('test_data')) {
$form->setValues(Mage::registry('test_data')->getData());
}
return parent::_prepareform();
}
}
And here is my test.xml in app/design/adminhtml/default/default/layout
<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
<test_adminhtml_index_index>
<reference name="content">
<block type="test/adminhtml_grid" name="test" />
</reference>
</test_adminhtml_index_index>
</layout>
why is save and delete missing from my form container?
Sorry if question is not well phrased, i am a noob magento user.

Magento - How to Save entire grid using mass action

I have a warehouse grid in my module. My warehouse contains a lot of products, so when i am going to edit the warehouse, i added a products grid in warehouse edit tab. But, i confused about how to save the entire products grid to database. Really need help.
Here is my Grid
public function __construct() {
parent::__construct();
$this->setId('UnicornInventoryGrid');
$this->setDefaultSort('id_warehouse');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
protected function _prepareCollection() {
$collection = Mage::getModel('inventory/warehouse')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns() {
$this->addColumn('id_warehouse', array(
'header' => Mage::helper('inventory')->__('id_warehouse'),
'filter_index' => 'main_table.id_warehouse',
'index' => 'id_warehouse',
'width' => '5px',
));
$this->addColumn('warehouse_name', array(
'header' => Mage::helper('inventory')->__('Warehouse Name'),
'filter_index' => 'main_table.warehouse_name',
'index' => 'warehouse_name',
'editable' => 'TRUE',
'width' => '5px',
));
$this->addColumn('created_by', array(
'header' => Mage::helper('inventory')->__('Created By'),
'filter_index' => 'main_table.created_by',
'index' => 'created_by',
'width' => '5px',
'editable' => 'TRUE',
));
$this->addColumn('manager_email', array(
'header' => Mage::helper('inventory')->__('Manager\'s Email'),
'filter_index' => 'main_table.manager_email',
'index' => 'manager_email',
'width' => '5px',
'editable' => 'TRUE',
));
$this->addColumn('phone', array(
'header' => Mage::helper('inventory')->__('Phone'),
'filter_index' => "main_table.phone",
'index' => "phone",
'editable' => 'TRUE',
));
$this->addColumn('street', array(
'header' => Mage::helper('inventory')->__('Street'),
'filter_index' => "ce3.street",
'index' => "street",
'editable' => 'TRUE',
));
$this->addColumn('city', array(
'header' => Mage::helper('inventory')->__('City'),
'filter_index' => 'main_table.city',
'index' => 'city',
'editable' => 'TRUE',
));
$this->addColumn('country', array(
'header' => Mage::helper('inventory')->__('Country'),
'filter_index' => 'main_table.country',
'index' => 'country',
'type' => 'options',
'editable' => 'TRUE',
'options' => array("" => "All Countries" , "Indonesia" => "Indonesia", "US" => "US")
));
$this->addColumn('status', array(
'header' => Mage::helper('inventory')->__('Status'),
'filter_index' => 'main_table.status',
'index' => 'phone',
));
// $this->addColumn('action',
// array(
// 'header' => Mage::helper('inventory')->__('Action'),
// 'width' => '100',
// 'type' => 'action',
// 'getter' => 'getId',
// 'actions' => array(
// array(
// 'caption' => Mage::helper('inventory')->__('Edit'),
// 'url' => array('base'=> '*/*/edit'),
// 'field' => 'id'
// )
// ),
// 'filter' => false,
// 'sortable' => false,
// 'index' => 'stores',
// 'is_system' => true,
// ));
$this->addExportType('*/*/exportCsv', Mage::helper('inventory')->__('CSV'));
$this->addExportType('*/*/exportXml', Mage::helper('inventory')->__('XML'));
return parent::_prepareColumns();
}
protected function _prepareMassaction() {
$this->setMassactionIdField('id');
$this->getMassactionBlock()->setFormFieldName('inventory_warehouse_mass_action');
$this->getMassactionBlock()->addItem('save', array(
'label' => Mage::helper('inventory')->__('Save'),
'url' => $this->getUrl('*/*/massSaveProduct'),
'confirm' => Mage::helper('inventory')->__('Are you sure?')
));
return $this;
}
public function getRowUrl($row) {
return $this->getUrl('*/*/edit', array('id' => $row->getIdWarehouse()));
}
and here is my controller
public function indexAction(){
$this->loadLayout();
$this->renderLayout();
// die("sadfsaf");
}
public function newAction() {
$id = $this->getRequest()->getParam('id');
if(empty($id)) $this->_title($this->__('Admin'))->_title($this->__('Add Warehouse'));
else $this->_title($this->__('Admin'))->_title($this->__('Edit Warehouse'));
$model = Mage::getModel('inventory/warehouse')->load($id);
if ($model->getId() || empty($id)) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data))
$model->setData($data);
Mage::register('warehouse_warehouse_data', $model);
$this->loadLayout();
$this->_setActiveMenu('unicorn_inventory');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit'))
->_addLeft($this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__('Warehouse does not exist.'));
$this->_redirect('*/*/');
}
}
public function editAction() {
$id = $this->getRequest()->getParam('id');
if(empty($id)) $this->_title($this->__('Admin'))->_title($this->__('Add Warehouse'));
else $this->_title($this->__('Admin'))->_title($this->__('Edit Warehouse'));
$model = Mage::getModel('inventory/warehouse')->load($id);
if ($model->getId() || empty($id)) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data))
$model->setData($data);
Mage::register('inventory_warehouse_data', $model);
$this->loadLayout();
$this->_setActiveMenu('unicorn_warehouse');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit'))
->_addLeft($this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__('Warehouse does not exist.'));
$this->_redirect('*/*/');
}
}
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('inventory/warehouse');
$model->setData($data)
->setData('id_warehouse' , $this->getRequest()->getParam('id'));
try {
$collection = Mage::getModel('inventory/warehouse')->getCollection();
foreach($collection as $item){
if(($item->getIdWarehouse() == $model->getIdWarehouse()) && ($model->isObjectNew())){
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__("Id '" . $model->getIdWarehouse(). "' already assigned."));
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/new');
return;
}
}
// echo "<pre>";
// var_dump($data);
// echo "</pre>";
// die();
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('inventory')->__('Warehouse telah disimpan'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
if ($this->getRequest()->getParam('backandnew')) {
$this->_redirect('*/*/new');
return;
}
$this->_redirect('*/*/');
return;
} 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(Mage::helper('inventory')->__('Unable to find warehouse to save.'));
$this->_redirect('*/*/');
}
/**
* mass save item(s) action
*/
public function massSaveProductAction() {
$dataIds = $this->getRequest()->getParam('inventory_warehouse_mass_action');
if (!is_array($dataIds)) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__('Please select item(s)'));
} else {
try {
foreach ($dataIds as $dataId) {
// $model = Mage::getModel('inventory/wareproduct')->load($dataId);
$model = Mage::getModel('inventory/wareproduct');
$model->delete();
}
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('supplier')->__('Total of %d record(s) were successfully deleted.', count($dataIds)));
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
/**
* export grid item to CSV type
*/
public function exportCsvAction() {
$fileName = 'Unicorn_Inventory.csv';
$content = $this->getLayout()->createBlock('warehouse/adminhtml_warehouse_grid')->getCsv();
$this->_prepareDownloadResponse($fileName, $content);
}
/**
* export grid item to XML type
*/
public function exportXmlAction() {
$fileName = 'warehouse_warehouse.xml';
$content = $this->getLayout()->createBlock('warehouse/adminhtml_warehouse_grid')->getXml();
$this->_prepareDownloadResponse($fileName, $content);
}
public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit_tab_product')->toHtml()
);
}
So, what should we do, so every row in the grid can submitted and saved to database. Thx a lot for your attention.
In
massSaveProductAction
exchange the lines
$model = Mage::getModel('inventory/wareproduct');
$model->delete();
with
$model = Mage::getModel('inventory/wareproduct');
$model->setData('your_attribute_code',"YOUR_VALUE");
$model->save();
Answer for second question:
Get a collection of whatever entity type you have...
$collection->addFieldToFilter('YOUR_GRID_ID_FIELD', array('in'=>array($gridIds)))
and you have the collection. Iterate over the collection and do whatever is needed...

add tab in admin dashboard magento 1.7.0.2

Copy Ordered.php
From
app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products
to
app/code/local/Mage/Adminhtml/Block/Dashboard/Tab/Products
Rename New.php
I have modified the following code:
class Mage_Adminhtml_Block_Dashboard_Tab_Products_New extends Mage_Adminhtml_Block_Dashboard_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('productsNewGrid');
}
protected function _prepareCollection()
{
if (!Mage::helper('core')->isModuleEnabled('Mage_Sales')) {
return $this;
}
if ($this->getParam('website')) {
$storeIds = Mage::app()->getWebsite($this->getParam('website'))->getStoreIds();
$storeId = array_pop($storeIds);
} else if ($this->getParam('group')) {
$storeIds = Mage::app()->getGroup($this->getParam('group'))->getStoreIds();
$storeId = array_pop($storeIds);
} else {
$storeId = (int)$this->getParam('store');
}
$todayStartOfDayDate = Mage::app()->getLocale()->date()
->setTime('00:00:00')
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$todayEndOfDayDate = Mage::app()->getLocale()->date()
->setTime('23:59:59')
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$collection
->addStoreFilter()
->addAttributeToFilter('news_from_date', array('or'=> array(
0 => array('date' => true, 'to' => $todayEndOfDayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter('news_to_date', array('or'=> array(
0 => array('date' => true, 'from' => $todayStartOfDayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter(
array(
array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
)
);
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('name', array(
'header' => $this->__('Product Name'),
'sortable' => false,
'index' => 'product_name'
));
$this->addColumn('price', array(
'header' => $this->__('Price'),
'width' => '120px',
'type' => 'currency',
'currency_code' => (string) Mage::app()->getStore((int)$this->getParam('store'))->getBaseCurrencyCode(),
'sortable' => false,
'index' => 'product_price'
));
$this->addColumn('ordered_qty', array(
'header' => $this->__('Quantity Ordered'),
'width' => '120px',
'align' => 'right',
'sortable' => false,
'index' => 'qty_ordered',
'type' => 'number'
));
$this->setFilterVisibility(false);
$this->setPagerVisibility(false);
return parent::_prepareColumns();
}
/*
* Returns row url to show in admin dashboard
* $row is bestseller row wrapped in Product model
*
* #param Mage_Catalog_Model_Product $row
*
* #return string
*/
public function getRowUrl($row)
{
// getId() would return id of bestseller row, and product id we get by getProductId()
$productId = $row->getProductId();
// No url is possible for non-existing products
if (!$productId) {
return '';
}
$params = array('id' => $productId);
if ($this->getRequest()->getParam('store')) {
$params['store'] = $this->getRequest()->getParam('store');
}
return $this->getUrl('*/catalog_product/edit', $params);
}
}
Then Copy Grids.php
From
app/code/core/Mage/Adminhtml/Block/Dashboard/
to
app/code/local/Mage/Adminhtml/Block/Dashboard/
added the following code:
$this->addTab('new_products', array(
'label' => $this->__('New Product'),
'content' => $this->getLayout()->createBlock('adminhtml/dashboard_tab_products_new')->toHtml(),
'class' => 'ajax'
));
I want to add a new product tab in admin dashboard,beside customers.I don't know what wrong with the New.php.I click the new product tab,it's not working.How to fix it?
I have managed to get this working with only a few more lines to change.
Update the Dashboard controller Mage_Adminhtml_DashboardController to add the new action
public function productsNewAction()
{
$this->loadLayout();
$this->renderLayout();
}
Update the admin layout.xml design\adminhtml\default\default\layout\main.xml to add the new section
<adminhtml_dashboard_productsnew>
<block type="core/text_list" name="root" output="toHtml">
<block type="adminhtml/dashboard_tab_products_new" name="adminhtml.dashboard.tab.products.new"/>
</block>
</adminhtml_dashboard_productsnew>
The you would just need to update your code in the Grids.php to the following.
$this->addTab('new_products', array(
'label' => $this->__('New Product'),
'url' => $this->getUrl('*/*/productsNew', array('_current'=>true)),
'class' => 'ajax'
));
This should then work using a call to the url rather than the block content.
You then need to select the attributes you want to show. You can do this by selecting all or by attribute code.
$collection->addAttributeToSelect('*')
$collection->addAttributeToSelect('name');
Important is the column index defined in _prepareColumns match these attribute codes Otherwise you will just get an empty row.
I would suggest packaging these changes into a new module with a controller, layout.xml and block files. There are lots of great tutorials around on how to do this, but obviously you don't have to :)

Custom image field within CMS Magento

I am attempting to create a custom image field within Magento CMS pages.
This is the steps I have taken,
Created an additional column with cms_page within the database called 'banner' - this is a varchar (255).
Amended "app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php" with the uploader code (see at bottom).
Amended "app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php" to add the new field called 'banner' of which is a field type of 'image'.
Deleted everything within "var/cache/" and "var/session/"
It's just simply not uploading/saving the filename within the database. To try and diagnose what's going on I added print_r($_FILES) just below saveAction() and it returned an empty array.
Am I missing a crucial step?
Here is the relevant code,
app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php -
public function saveAction()
{
if ($data = $this->getRequest()->getPost()) {
$data = $this->_filterPostData($data);
//init model and set data
$model = Mage::getModel('cms/page');
if(isset($data['banner']['delete']) && $data['banner']['delete']=='1'){
if(!empty($data['banner']['value'])){
$path = Mage::getBaseDir('media') . DS;
if(#unlink($path.$data['banner']['value'])){
$data['banner']='';
}
}
}
if(isset($_FILES['banner']['name']) && !empty($_FILES['banner']['name'])) {
try {
$uploader = new Varien_File_Uploader('banner');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(true);
// setAllowRenameFiles(true) -> move your file in a folder the magento way
// setAllowRenameFiles(false) -> move your file directly in the $path folder
$uploader->setFilesDispersion(true);
$path = Mage::getBaseDir('media') . DS;
//$uploader->saveresized($path, $_FILES['nfile']['name'],100,72);
//$_tmp_nfilethumb = $uploader->getUploadedFileName();
$uploader->save($path, $_FILES['banner']['name']);
$_tmp_nfile = $uploader->getUploadedFileName();
//$data['nfilethumb'] = $_tmp_nfilethumb;
$data['banner'] = $_tmp_nfile;
}catch(Exception $e) {
}
}elseif(isset($data['banner']['value']) && !empty($data['banner']['value'])){
$data['banner']=$data['banner']['value'];
}
if ($id = $this->getRequest()->getParam('page_id')) {
$model->load($id);
}
$model->setData($data);
Mage::dispatchEvent('cms_page_prepare_save', array('page' => $model, 'request' => $this->getRequest()));
//validating
if (!$this->_validatePostData($data)) {
$this->_redirect('*/*/edit', array('page_id' => $model->getId(), '_current' => true));
return;
}
// try to save it
try {
// save the data
$model->save();
// display success message
Mage::getSingleton('adminhtml/session')->addSuccess(
Mage::helper('cms')->__('The page has been saved.'));
// clear previously saved data from session
Mage::getSingleton('adminhtml/session')->setFormData(false);
// check if 'Save and Continue'
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('page_id' => $model->getId(), '_current'=>true));
return;
}
// go to grid
$this->_redirect('*/*/');
return;
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
catch (Exception $e) {
$this->_getSession()->addException($e,
Mage::helper('cms')->__('An error occurred while saving the page.'));
}
$this->_getSession()->setFormData($data);
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id')));
return;
}
$this->_redirect('*/*/');
}
app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php -
protected function _prepareForm()
{
$model = Mage::registry('cms_page');
/*
* Checking if user have permissions to save information
*/
if ($this->_isAllowedAction('save')) {
$isElementDisabled = false;
} else {
$isElementDisabled = true;
}
$form = new Varien_Data_Form();
$form->setHtmlIdPrefix('page_');
$fieldset = $form->addFieldset('content_fieldset', array('legend'=>Mage::helper('cms')->__('Content'),'class'=>'fieldset-wide'));
$wysiwygConfig = Mage::getSingleton('cms/wysiwyg_config')->getConfig(
array('tab_id' => $this->getTabId())
);
$fieldset->addField('content_heading', 'text', array(
'name' => 'content_heading',
'label' => Mage::helper('cms')->__('Content Heading'),
'title' => Mage::helper('cms')->__('Content Heading'),
'disabled' => false,
));
$content999Field = $fieldset->addField('banner', 'image', array(
'name' => 'banner',
'label' => Mage::helper('cms')->__('Banner'),
'title' => Mage::helper('cms')->__('Banner'),
));
$contentField = $fieldset->addField('content', 'editor', array(
'name' => 'content',
'label' => Mage::helper('cms')->__('Layout 1'),
'title' => Mage::helper('cms')->__('Layout 1'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
$content2Field = $fieldset->addField('content2', 'editor', array(
'name' => 'content2',
'label' => Mage::helper('cms')->__('Layout 2'),
'title' => Mage::helper('cms')->__('Layout 2'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
$content3Field = $fieldset->addField('content3', 'editor', array(
'name' => 'content3',
'label' => Mage::helper('cms')->__('Content'),
'title' => Mage::helper('cms')->__('Content'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
// Setting custom renderer for content field to remove label column
//$renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset_element')
// ->setTemplate('cms/page/edit/form/renderer/content.phtml');
// $contentField->setRenderer($renderer);
$form->setValues($model->getData());
$this->setForm($form);
Mage::dispatchEvent('adminhtml_cms_page_edit_tab_content_prepare_form', array('form' => $form));
return parent::_prepareForm();
}
Try to add this line below $form->setValues($model->getData());:
$form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
I added,
'enctype' => 'multipart/form-data' within the Form.php and it fixed it.
class Mage_Adminhtml_Block_Cms_Page_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(array('id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post', 'enctype' => 'multipart/form-data'));
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}

Magento admin issue

Hi I'm creating my first admin section for my extension. I've created a menu which links to a page displaying a grid. The problem is when you click through to edit the record, its displaying this error
Fatal error: Call to a member function setData() on a non-object in /Applications/MAMP/htdocs/theBookClub/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php on line 129
For the life of me I can't see any reference in any of the relevant files
class Namespace_Bookshelf_Block_Adminhtml_Bookshelf_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::__construct();
$this->_objectId = 'id';
$this->_blockGroup = 'bookshelf';
$this->_controller = 'bookshelf_admin';
$this->_mode = 'edit';
$this->_addButton('save_and_continue', array(
'label' => Mage::helper('adminhtml')->__('Save And Continue Edit'),
'onclick' => 'saveAndContinueEdit()',
'class' => 'save',
), -100);
$this->_updateButton('save', 'label', Mage::helper('bookshelf')->__('Save Example'));
$this->_formScripts[] = "
function toggleEditor() {
if (tinyMCE.getInstanceById('form_content') == null) {
tinyMCE.execCommand('mceAddControl', false, 'edit_form');
} else {
tinyMCE.execCommand('mceRemoveControl', false, 'edit_form');
}
}
function saveAndContinueEdit(){
editForm.submit($('edit_form').action+'back/edit/');
}
";
}
public function getHeaderText()
{
if (Mage::registry('example_data') && Mage::registry('example_data')->getId())
{
return Mage::helper('bookshelf')->__('Edit Example "%s"', $this->htmlEscape(Mage::registry('example_data')->getName()));
} else {
return Mage::helper('bookshelf')->__('New Example');
}
}
and this
class Namespace_Bookshelf_Block_Adminhtml_Bookshelf_Grid extends Mage_Adminhtml_Block_Widget_Grid {
public function __construct() {
parent::__construct();
$this->setId('bookshelf_grid');
$this->setDefaultSort('bookshelf_id');
$this->setDefaultDir('desc');
$this->setSaveParametersInSession(true);
}
protected function _prepareCollection() {
$collection = Mage::getModel('bookshelf/bookshelf')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns() {
$this->addColumn('bookshelf_id', array(
'header' => Mage::helper('bookshelf')->__('ID'),
'align' => 'right',
'width' => '50px',
'index' => 'bookshelf_id',
));
$this->addColumn('customer_id', array(
'header' => Mage::helper('bookshelf')->__('Name'),
'align' => 'left',
'index' => 'customer_id',
));
$this->addColumn('bookshelf_name', array(
'header' => Mage::helper('bookshelf')->__('Name'),
'align' => 'left',
'index' => 'bookshelf_name',
));
return parent::_prepareColumns();
}
public function getRowUrl($row) {
return $this->getUrl('*/*/edit', array('id' => $row->getId()));
}
}
and this
class Newdaymedia_Bookshelf_Block_Adminhtml_Bookshelf extends
Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct()
{
$this->_controller = 'bookshelf_admin';
$this->_blockGroup = 'bookshelf';
$this->_headerText = Mage::helper('bookshelf')->__('Item Manager');
$this->_addButtonLabel = Mage::helper('bookshelf')->__('Add Item');
parent::__construct();
}
protected function _prepareLayout()
{
$this->setChild( 'grid',
$this->getLayout()->createBlock( $this->_blockGroup.'/' . $this->_controller . '_grid',
$this->_controller . '.grid')->setSaveParametersInSession(true) );
return parent::_prepareLayout();
}
}
Any help would be gratefully received!
NEW
class Namespace_Bookshelf_Block_Adminhtml_Bookshelf_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
if (Mage::getSingleton('adminhtml/session')->getExampleData())
{
$data = Mage::getSingleton('adminhtml/session')->getExamplelData();
Mage::getSingleton('adminhtml/session')->getExampleData(null);
}
elseif (Mage::registry('example_data'))
{
$data = Mage::registry('example_data')->getData();
}
else
{
$data = array();
}
Mage::log("this is the form class");
$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);
$fieldset = $form->addFieldset('example_form', array(
'legend' =>Mage::helper('bookshelf')->__('Example Information')
));
$fieldset->addField('name', 'text', array(
'label' => Mage::helper('bookshelf')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'name',
'note' => Mage::helper('awesome')->__('The name of the example.'),
));
$fieldset->addField('description', 'text', array(
'label' => Mage::helper('bookshelf')->__('Description'),
'class' => 'required-entry',
'required' => true,
'name' => 'description',
));
$fieldset->addField('other', 'text', array(
'label' => Mage::helper('bookshelf')->__('Other'),
'class' => 'required-entry',
'required' => true,
'name' => 'other',
));
$form->setValues($data);
return parent::_prepareForm();
}
}
This might solve your issue:
In your form container class:
Namespace_Bookshelf_Block_Adminhtml_Bookshelf_Edit
extends Mage_Adminhtml_Block_Widget_Form_Container
If you add these test lines, you'll see which Form class Magento is trying to load
$form_block = $this->_blockGroup . '/' .
$this->_controller . '_' .
$this->_mode .
'_form';
echo $form_block;
For this to work with your code (above), your class:
Namespace_Bookshelf_Block_Adminhtml_Bookshelf_Edit_Form
should echo a test value of:
bookshelf/adminhtml_bookshelf_edit_form
and should be in the following filepath:
app/code/local/Namespace/Bookshelf/Block/Adminhtml/Bookshelf/Edit/Form.php
You might have to adjust the class name(s), or the filepath, or both, in order to get it working.
Good luck!
You need to have a helper created for your module (even if it does nothing). In your module's helper directory create a file called Data.php and create a class in there called Namespace_Module_Helper_Data that extends Mage_Core_Helper_Abstract.
I think that should help clear the problem up.
Assuming your Adminhtml controller is under
Namespace/ModuleName/controllers/Adminhtml/BookshelfController.php
try $this->_controller = 'adminhtml_bookshelf'; on Your Form Container.
It is important to clarify that $this->_controller is not the actual controller name but the block class name and $this->_blockGroup is actually the module name.
so try:
$this->_blockGroup = 'namespace_bookshelf';
$this->_controller = 'adminhtml_bookshelf';

Resources