Tut Magento 012: Magento form edit – tạo form edit trong backend Magento
Trong Tut Magento 012 này mình sẽ hướng dẫn các bạn tạo một form edit trong backend của Magento. Cụ thể hơn mình sẽ sử dụng extension Basetut_Salestaff mà các tut trước có dùng.
Mục đích: tạo ra form edit cho phép admin có thể thêm một staff mới thay đổi được thông tin của staff có sẵn.
1. Tạo button Add new staff trong trang hiển thị grid
Mặc định trong trang hiển thị grid dữ liệu sales staff có button Add Salestaff rồi nhưng trong những ví dụ trước để dễ nhìn mình đã dùng câu lệnh _removeButton để xóa nó đi. Giờ muốn hiển thị lại chỉ cần comment đoạn code đó trong app\code\local\Basetut\Salestaff\Block\Adminhtml\Staff.php
<!--?php class Basetut_Salestaff_Block_Adminhtml_Staff extends Mage_Adminhtml_Block_Widget_Grid_Container { public function __construct() { $this--->_controller = 'adminhtml_staff'; $this->_blockGroup = 'salestaff'; $this->_headerText = Mage::helper('salestaff')->__('Staff Manager'); parent::__construct(); /*$this->_removeButton('add');*/ } }
2. Chuyển action new sang edit
Mặc định khi click vào button “Add New” hệ thống sẽ chuyển sang url: http://yoursite.com/index.php/salestaffadmin/staff/new.
Tức là function newAction() trong controller app\code\local\Basetut\Salestaff\controllers\Adminhtml\StaffController.php được thực thi.
/*new action*/ public function newAction(){ $this->_forward('edit'); }
Function này cơ bản chỉ thực hiện chức năng forward đến action edit trong cùng controller Staff. Tuy nhiên để biết tại sao lại như thế thì ta sẽ giải thích kỹ hơn trong action này.
3. Thêm url vào cho các row grid trong trường hợp edit
Tại sao ta phải thêm url cho các row trong grid? Trong những Tut Magento trước mình đã hướng dẫn các bạn cách tạo ra một grid dữ liệu hiển thị nhưng mà đó là chưa đủ, admin còn muốn thay đổi thông tin của những bản ghi đó. Bởi vậy ta sẽ thêm vào những bản ghi trong grid một url dẫn tới trang edit.
Thêm hàm getRowUrl($row) vào trong file app\code\local\Basetut\Salestaff\Block\Adminhtml\Staff\Grid.php:
/** * get url for each row in grid * * @return string */ public function getRowUrl($row) { return $this->getUrl('*/*/edit', array('id' => $row->getId())); }
Như vậy bây giờ ta khi click vào một bản ghi bất kỳ hệ thống sẽ chuyển sang link: http://yoursite.com/salestaffadmin/staff/edit/id/$id.
Trong hàm getUrl ta truyền vào 2 tham số:
+ Tham số thứ nhất: action
*/*/edit: sẽ tương đương với salestaffadmin/staff/edit vì action hiện tại đang là salestaffadmin/staff/index
+ Tham số thứ hai: parameters
array(‘id’=>$row->getId)
4. Tạo edit action
Tạo hàm editAction() trong file: app\code\local\Basetut\Salestaff\controllers\Adminhtml\StaffController.php
/** * edit action */ public function editAction(){ $salestaffId = $this->getRequest()->getParam('id'); $model = Mage::getModel('salestaff/staff')->load($salestaffId); if ($model->getId() || $salestaffId == 0) { $data = Mage::getSingleton('adminhtml/session')->getFormData(true); if (!empty($data)) { $model->setData($data); } Mage::register('salestaff_data', $model); $this->loadLayout(); $this->_setActiveMenu('salestaff/salestaff'); $this->_addBreadcrumb( Mage::helper('adminhtml')->__('Staff Manager'), Mage::helper('adminhtml')->__('Staff Manager') ); $this->getLayout()->getBlock('head')->setCanLoadExtJs(true); $this->_addContent($this->getLayout()->createBlock('salestaff/adminhtml_staff_edit')) ->_addLeft($this->getLayout()->createBlock('salestaff/adminhtml_staff_edit_tabs')); $this->renderLayout(); } else { Mage::getSingleton('adminhtml/session')->addError( Mage::helper('salestaff')->__('Staff does not exist') ); $this->_redirect('*/*/'); } }
Hàm này có chức năng lấy ra staff cần edit và view thông tin của nó trong form cho phép chủ store có thể chỉnh sửa chúng.
5. Tạo form container
Form container này bao gồm một số button control như “Save”, “Save and Edit”, “Delete”. Form kế thừa từ class Mage_Adminhtml_Block_Widget_Form_Container.
File: app\code\local\Basetut\Salestaff\Block\Adminhtml\Staff\Edit.php
<!--?php class Basetut_Salestaff_Block_Adminhtml_Staff_Edit extends Mage_Adminhtml_Block_Widget_Form_Container { public function __construct() { parent::__construct(); $this--->_objectId = 'id'; $this->_blockGroup = 'salestaff'; $this->_controller = 'adminhtml_staff'; $this->_updateButton('save', 'label', Mage::helper('salestaff')->__('Save Staff')); $this->_updateButton('delete', 'label', Mage::helper('salestaff')->__('Delete Staff')); $this->_addButton('saveandcontinue', array( 'label' => Mage::helper('adminhtml')->__('Save And Continue Edit'), 'onclick' => 'saveAndContinueEdit()', 'class' => 'save', ), -100); $this->_formScripts[] = " function toggleEditor() { if (tinyMCE.getInstanceById('salestaff_content') == null) { tinyMCE.execCommand('mceAddControl', false, 'salestaff_content'); } else { tinyMCE.execCommand('mceRemoveControl', false, 'salestaff_content'); } } function saveAndContinueEdit(){ editForm.submit($('edit_form').action+'back/edit/'); } "; } }
6. Tạo tab “Staff Information”
Thực ra thì trong bài học này không nhất thiết phải sử dụng tab trong admin edit staff nhưng mình vẫn muốn đưa vào để các bạn có thể hình dung được và sử dụng nó trong những trường hợp cần thiết.
Tạo file: app\code\local\Basetut\Salestaff\Block\Adminhtml\Staff\Edit\Tabs.php
<!--?php class Basetut_Salestaff_Block_Adminhtml_Staff_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs { public function __construct() { parent::__construct(); $this--->setId('salestaff_tabs'); $this->setDestElementId('edit_form'); $this->setTitle(Mage::helper('salestaff')->__('Staff Information')); } /** * prepare before render block to html * * @return Basetut_Salestaff_Block_Adminhtml_Salestaff_Edit_Tabs */ protected function _beforeToHtml() { $this->addTab('form_section', array( 'label' => Mage::helper('salestaff')->__('Staff Information'), 'title' => Mage::helper('salestaff')->__('Staff Information'), 'content' => $this->getLayout() ->createBlock('salestaff/adminhtml_staff_edit_tab_form') ->toHtml(), )); return parent::_beforeToHtml(); } }
Trong hàm này ta có sử dụng câu lệnh:
$this->getLayout() ->createBlock('salestaff/adminhtml_staff_edit_tab_form') ->toHtml();
Block salestaff/adminhtml_staff_edit_tab_form chính là block chứa form hiển thị chính của page edit.
File code: app\code\local\Basetut\Salestaff\Block\Adminhtml\Staff\Edit\Tab\Form.php
7. Khởi tạo form với id là “edit_form”
Tạo file: app/code/local/Basetut/Salestaff/Block/Adminhtml/Staff/Edit/Form.php
class Basetut_Salestaff_Block_Adminhtml_Staff_Edit_Form extends Mage_Adminhtml_Block_Widget_Form { /** * prepare form's information for block * * @return Basetut_Salestaff_Block_Adminhtml_Staff_Edit_Form */ protected function _prepareForm(){ $form = new Varien_Data_Form(array( 'id' => 'edit_form', 'action' => $this->getUrl('*/*/save', array( 'id' => $this->getRequest()->getParam('id'), 'store' => $this->getRequest()->getParam('store'), )), 'method' => 'post', 'enctype' => 'multipart/form-data' )); $form->setUseContainer(true); $this->setForm($form); return parent::_prepareForm(); } }
File này có tác dụng tạo ra một form với id=”edit_form” và action là salestaffadmin/staff/save
8. Tạo form edit
Code file app\code\local\Basetut\Salestaff\Block\Adminhtml\Staff\Edit\Tab\Form.php:
<!--?php class Basetut_Salestaff_Block_Adminhtml_Staff_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form { /** * prepare tab form's information * * @return Basetut_Salestaff_Block_Adminhtml_Salestaff_Edit_Tab_Form */ protected function _prepareForm() { $form = new Varien_Data_Form(); $this--->setForm($form); if (Mage::getSingleton('adminhtml/session')->getSalestaffData()) { $data = Mage::getSingleton('adminhtml/session')->getSalestaffData(); Mage::getSingleton('adminhtml/session')->setSalestaffData(null); } elseif (Mage::registry('salestaff_data')) { $data = Mage::registry('salestaff_data')->getData(); } $fieldset = $form->addFieldset('salestaff_form', array( 'legend'=>Mage::helper('salestaff')->__('Staff information') )); /*Edit truong kieu text*/ $fieldset->addField('name', 'text', array( 'label' => Mage::helper('salestaff')->__('Name'), 'class' => 'required-entry', 'required' => true, 'name' => 'name', )); $fieldset->addField('email', 'text', array( 'label' => Mage::helper('salestaff')->__('Email'), 'class' => 'required-entry', 'required' => true, 'name' => 'email', )); $fieldset->addField('facebook_url', 'text', array( 'label' => Mage::helper('salestaff')->__('Facebook'), 'name' => 'facebook_url', )); /*Edit truong kieu date*/ $fieldset->addField('birthday', 'date', array( 'label' => Mage::helper('salestaff')->__('Birthday'), 'name' => 'birthday', 'format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT), 'image' => Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN).'/adminhtml/default/default/images/grid-cal.gif', )); /*Edit truong kieu select*/ $fieldset->addField('sex', 'select', array( 'label' => Mage::helper('salestaff')->__('Sex'), 'name' => 'sex', 'onclick' => "", 'onchange' => "", 'values' => array('-1'=>'Please Select..','1' => 'Male','2' => 'Female'), 'disabled' => false, 'readonly' => false, 'tabindex' => 1 )); /*View truong kieu note*/ if($this->getRequest()->getParam('id')){ $fieldset->addField('items_qty', 'note', array( 'label' => Mage::helper('salestaff')->__('Item qty'), 'name' => 'items_qty', 'text' => $data['items_qty'] )); } $form->setValues($data); return parent::_prepareForm(); } }
* Kết luận: ta vừa mới tạo được form dùng để add/edit dữ liệu salestaff. Tuy nhiên đây chỉ là form hiển thị/edit dữ liệu mà thôi và để hoạt động được chúng ta cần phải có action thao dữ liệu vừa edit nữa. Vì bài này đã tương đối dài rồi nên mình sẽ để phần đó cho bài sau. Mọi thắc mắc về các Tut Magento các bạn có thể post lên http://forum.basetut.com/index.php chúng tôi sẽ trả lời ngay lập tức. Chúc các bạn học Magento thật tốt!
Anh ơi tut hay lắm. Tiếp tục a nhé
Thanks 😀
Ok man! Cảm ơn vì đã ủng hộ!
Hey anh, Muốn tạo một cái collume để hiển thị hình anh trong manage product ở admin panel thì mình làm như thến nào ak, anh co thể hướng dẫn giúp em khoong ak
Chú có thể override cái block grid của product trong admin sau đó thêm 1 cột và viết renderer cho nó là ok chú à!
Sao phần form edit của mình nó lại hiển thị trong phần tab information nhỉ, ko thể nào cho nó hiển thị ở phần content đc,ai giúp với 🙁
done 😀
cậu làm kiểu gì để nó ra giữa vậy. của mình cũng bị hiển thị form edit bên Staff Information còn phần content thì hiển thị thông báo lỗi : Fatal error: Call to a member function setData() on a non-object in D:\wamp\www\magento\app\code\core\Mage\Adminhtml\Block\Widget\Form\Container.php on line 129
Cái lỗi 129 kia, bạn tạo 1 file form.php khai báo form ở trong thư mục \local\Basetut\Salestaff\Block\Adminhtml\Staff\Edit là đc. Còn cái lỗi hiển thị trong phần Tabs information, bạn xem lại file StaffController.php trong thư mục \local\Basetut\Salestaff\controllers\Adminhtml nhé. GL & HF 🙂
very good!
Mình bổ sung thêm nhé: Các bạn tạo thêm một file form.php theo đường dẫn: \local\Basetut\Salestaff\Block\Adminhtml\Staff\Edit và thêm đoạn code này vào trong file đó: <?php
class Cmsmart_Sellemployment_Block_Adminhtml_Staff_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{ }
Xin lỗi mình nhầm, vì để tên namespace và module khác
<?php
class Basetut_Salestaff_Block_Adminhtml_Staff_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{ }
Em làm thử cái action view theo kiểu edit như của anh nhưng hok được? e bị báo lỗi Fatal error: Call to a member function setData() on a non-object in Form\Container.php on line 129
Bác giúp e với
có ai sửa đc lỗi form bị nhảy sang bên left phía bên infornation đăng lên mn biết với.em bug mãi không ra lỗi ý:(
Mình cũng bị như bạn này, mới nghiên cứu hiện chưa bít cách sửa, bạn đã tìm ra cách sửa chưa, chỉ mình với. Thanks
Mình đã sửa dc lỗi này rồi, Thanks. Mod khỏi đưa comment này lên nhé
Sorry mọi người vì đã không reply sớm. Các bạn đã fix được lỗi này chưa? Nếu chưa thì mình sẽ hướng dẫn cách fix nhé!
e vẫn chưa fix dc,a giúp e fix nha,content vẫn hiên bên menu information
E vẫn chưa fix được lỗi này, a giúp e fix với
Bạn có thể mô tả thật rõ vấn đề ra không? Mình sẽ giúp bạn giải quyết vấn đề.
Hướng dẫn cách fix đi mod ơi, mình vẫn chưa fix được!!
Mình vẫn bị lỗi cái form nó nằm bên trái trong mục tab luôn, click vào tab thì nó hiện ra cái form bên cột trái, Mong được giúp đỡ!!1
Bạn ơi mình vừa mới update bài viết rồi nhé! Bạn thêm file app/code/local/Basetut/Salestaff/Block/Adminhtml/Staff/Edit/Form.php (phần 7)
rồi chạy lại xem chạy được chưa nhé! Rất xin lỗi vì code của mình vẫn thiếu file.
Thêm file Form vào mình vẫn bị lỗi đó, click vào tab nó hiện ra cái form bên tab left mà không hiện ra content. Mình có thay đổi 1 số chỗ bên hiển thị layout bên file StaffController: $this->_addContent($this->getLayout()->createBlock(‘salestaff/adminhtml_staff_edit’));
$this->_addLeft($this->getLayout()->createBlock(‘salestaff/adminhtml_staff_edit_tabs’));
$this->_addContent($this->getLayout()->createBlock(‘salestaff/adminhtml_staff_edit_tab_form’));
Sau khi thay đổi thì form đã hiện ra ở content nhưng vẫn còn 1 form bên tableft.
Bạn add skype mình nhé! doanhbk. Mình sẽ teamview giúp bạn giải quyết vấn đề này sau đó update lại bài viết.
Chạy tốt. Thank a nhé. Bài viết rất hay.