Wanting to add a custom Model to be rendered in a custom Magento admin form. Just cant seem to get the source model to render any of the options. Couldn't really find anything on google as it was mostly to do with system/config source model examples. See code below
Model File (My/Module/Model/MyModel.php)
<?php
class My_Module_Model_MyModel extends Mage_Core_Model_Abstract
{
static public function getOptionArray()
{
$allow = array(
array('value' => '1', 'label' => 'Enable'),
array('value' => '0', 'label' => 'Disable'),
);
return $allow;
}
}
and my form tab file - Tab shows up with multiselect field, but its blank (My/Module/Block/Adminhtml/Module/Edit/Tab/Data.php)
<?php
class My_Module_Block_Adminhtml_Module_Edit_Tab_Data extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm(){
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('module_form', array('legend'=>Mage::helper('module')->__('Module Information')));
$object = Mage::getModel('module/module')->load( $this->getRequest()->getParam('module_id') );
echo $object;
$fieldset->addField('module_enabled', 'multiselect', array(
'label' => Mage::helper('module')->__('Allowed Module'),
'class' => 'required-entry',
'required' => true,
'name' => 'module_enabled',
'source_model' => 'My_Module_Model_MyModel',
'after_element_html' => '<small>Select Enable to Allow</small>',
'tabindex' => 1
));
if ( Mage::getSingleton('adminhtml/session')->getModuleData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getModuleData());
Mage::getSingleton('adminhtml/session')->setModuleData(null);
} elseif ( Mage::registry('module_data') ) {
$form->setValues(Mage::registry('module_data')->getData());
}
return parent::_prepareForm();
}
}
So I have other fields, tabs that all save the data etc but just cant get the values to render using a custom model inside the multiselect field.
Looks like method name in the source model is incorrect. Also, you probably don't need to extend Mage_Core_Model_Abstract in source models.
Try this:
<?php
class My_Module_Model_MyModel
{
public function toOptionArray()
{
return array(
array('value' => '1', 'label' => Mage::helper('module')->__('Enable')),
array('value' => '0', 'label' => Mage::helper('module')->__('Disable')),
);
}
}
OP's solution migrated from the question to an answer:
updated the MyModel.php to get a foreach in a collection (CMS Pages
for example)
<?php
class My_Module_Model_MyModel
{
public function toOptionArray($withEmpty = false)
{
$options = array();
$cms_pages = Mage::getModel('cms/page')->getCollection();
foreach ($cms_pages as $value) {
$data = $value->getData();
$options[] = array(
'label' => ''.$data['title'].'('.$data['identifier'].')',
'value' => ''.$data['identifier'].''
);
}
if ($withEmpty) {
array_unshift($options, array('value'=>'', 'label'=>Mage::helper('module')->__('-- Please Select --')));
}
return $options;
}
and within My/Module/Block/Adminhtml/Module/Edit/Tab/Data.php I just
removed "source_model" and replaced it with
'values' => Mage::getModel('module/mymodel')->toOptionArray(),
Just to add, also had the issue of multiselect values not
saving/updating the multiselect field on refresh/save on the edit
page. To get this working, I edited the admin controller under the
saveAction (or the action name to save the form data). See below my
saveAction in the controller for the admin/backend located in
My/Module/controllers/Adminhtml/ModuleController.php
public function saveAction() {
$model = Mage::getModel('module/module');
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('module/module');
$model->setData($data)
->setModuleId($this->getRequest()->getParam('module_id'));
try {
if ($model->getCreatedTime() == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$ModuleEnabled = $this->getRequest()->getParam('module_enabled');
if (is_array($ModuleEnabled))
{
$ModuleEnabledSave = implode(',',$this->getRequest()->getParam('module_enabled'));
}
$model->setModuleEnabled($ModuleEnabledSave);
//save form data/values per field
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('module')->__('Item
was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('module_id' => $model->getModuleId()));
return;
}
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('module_id' => $this->getRequest()->getParam('module_id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('module')->__('Unable
to find item to save'));
$this->_redirect('*/*/');
}
This saves an imploded array (ie 2, 3 ,6, 23, 28,) into the database
value and renders the selected multiselect fields on the corresponding
tab on refresh/update/save
Related
I am new to mangeto framework and i am learning to create a form in admin area section. However, it has been over hours that I could not figure out the error i am receiving:
Recoverable Error: Argument 1 passed to Mage_Adminhtml_Controller_Action::_addContent() must be an instance of Mage_Core_Block_Abstract, boolean given, called in /vagrant/magento/app/code/local/MasteringMagento/Example/controllers/Adminhtml/EventController.php on line 12.
The following is my Edit.php file as well as my Form.php file
Edit.php:
class MasteringMagento_Example_Adminhtml_EventController extends Mage_Adminhtml_Controller_Action{
public function indexAction(){
$this->loadLayout();
$this->_addContent(
$this->getLayout()->createBlock('example/adminhtml_event_edit'));
//go straight to the php file to render the form. otherwise this will not perfomed.
$this->renderLayout();
}
public function saveAction(){
$eventID = $this->getRequest()->getParam('event_id');
$eventModel = Mage::getModel('example/event')->load($eventID);
if($data = $this->getRequest()->getPost()){
try{
$eventModel->addData($data)->save();
Mage::getSingleton('adminhtml/session')->addSuccess(
$this->__('Your event has been saved')
);
}catch(Exception $e){
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
$this->_redirect('*/*/index');
}
}
}
and Form.php file:
class MasteringMagento_Example_Block_Adminhtml_Event_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'));
$fieldset = $form->addFieldset('base_fieldset',
array('legend'=>Mage::helper('example')->__('General Information'),
'class'=>'fieldset-wide'));
$fieldset->addField('name', 'text', array(
'name' => 'name',
'label' => Mage::helper('example')->__('Event Name'),
'title' => Mage::helper('example')->__('Event Name'),
'required' => true
));
$dateFormatIso = Mage::app()->getLocale()->getDateFormat(
Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('start', 'date', array(
'name' => 'start',
'format' => $dateFormatIso,
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'label' => Mage::helper('example')->__('Start Date'),
'title' => Mage::helper('example')->__('Start Date'),
'required' => true
));
$fieldset->addField('end', 'date', array(
'name' => 'end',
'format' => $dateFormatIso,
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'label' => Mage::helper('example')->__('End Date'),
'title' => Mage::helper('example')->__('End Date'),
'required' => true
));
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
The error i think is from my Controller. However, if i direct the url link to the form, it will display. But if i direct to its container which is Edit.php, the error above would occurs:
class MasteringMagento_Example_Adminhtml_EventController extends Mage_Adminhtml_Controller_Action{
public function indexAction(){
$this->loadLayout();
$this->_addContent(
$this->getLayout()->createBlock('example/adminhtml_event_edit'));
//go straight to the php file to render the form. otherwise this will not perfomed.
$this->renderLayout();
}}
This is my config.xml. I did include the base class for Magento Blocks:
<blocks>
<example>
<class>MasteringMagento_Example_Block</class>
</example>
</blocks>
Please help me to identify the problem. Thanks
createBlock() is an abstract factory pattern for Blocks inside of Magento. Whenever Magento cannot resolve a factory class from this method, a boolean is returned... which is the case in your example, as the error message says.
Check your class MasteringMagento_Example_Block_Adminhtml_Event_Edit for spelling, casing, or class related errors. Also ensure that your class file is located at app/code/local/MasteringMagento/Example/Block/Adminhtml/Event/Edit.php.
In magento, every admin form block is loaded first by a form container.
Here, you call MasteringMagento_Example_Block_Adminhtml_Event_Edit class :
$this->getLayout()->createBlock('example/adminhtml_event_edit')
This class, located in app/code/local/MasteringMagento/Example/Block/Adminhtml/Post/Edit.php, should look to something like this :
<?php
/**
* MasteringMagento_Example_Block_Adminhtml_Post_Edit
*/
class MasteringMagento_Example_Block_Adminhtml_Post_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
// $this->_objectId = 'id';
parent::__construct();
$this->_blockGroup = 'example';
$this->_controller = 'adminhtml_post';
$this->_mode = 'edit';
$modelTitle = $this->_getModelTitle();
$this->_updateButton('save', 'label', $this->_getHelper()->__("Save $modelTitle"));
$this->_addButton('saveandcontinue', array(
'label' => $this->_getHelper()->__('Save and Continue Edit'),
'onclick' => 'saveAndContinueEdit()',
'class' => 'save',
), -100);
$this->_formScripts[] = "
function saveAndContinueEdit(){
editForm.submit($('edit_form').action+'back/edit/');
}
";
}
protected function _getHelper(){
return Mage::helper('example');
}
protected function _getModel(){
return Mage::registry('exemple_youmodel');
}
protected function _getModelTitle(){
return 'Post';
}
public function getHeaderText()
{
$model = $this->_getModel();
$modelTitle = $this->_getModelTitle();
if ($model && $model->getId()) {
return $this->_getHelper()->__("Edit $modelTitle (ID: {$model->getId()})");
}
else {
return $this->_getHelper()->__("New $modelTitle");
}
}
/**
* Get URL for back (reset) button
*
* #return string
*/
public function getBackUrl()
{
return $this->getUrl('*/*/index');
}
public function getDeleteUrl()
{
return $this->getUrl('*/*/delete', array($this->_objectId => $this->getRequest()->getParam($this->_objectId)));
}
}
As you can see, all your buttons are set in the __construct() method.
Hope it helps.
I'm editing a custom plugin in magento in which I need add a field to upload an image and save it's path in the database together with other data. The form works fine with the additional data, as well as the database recording. However, it seems that the $_FILES variable always return empty. What is more curious is that an file called "cache_2ca019d1e2db75b611e5f3aa5c932970" is always generated in the media directory every time I try to upload an image in my module.
I've found people with similar problems here, but none of the presented solutions worked for me. I'm lost =/
This is my Form file:
<?php
class SmashingMagazine_BrandDirectory_Block_Adminhtml_Brand_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(
'smashingmagazine_branddirectory_admin/brand/edit',
array(
'_current' => true,
'continue' => 0,
)
),
'method' => 'post',
'enctype' => 'multipart/form-data'
));
$form->setUseContainer(true);
$this->setForm($form);
// define a new fieldset, we only need one for our simple entity
$fieldset = $form->addFieldset(
'general',
array(
'legend' => $this->__('Brand Details')
)
);
$brandSingleton = Mage::getSingleton(
'smashingmagazine_branddirectory/brand'
);
// add the fields we want to be editable
$this->_addFieldsToFieldset($fieldset, array(
'name' => array(
'label' => $this->__('Name'),
'input' => 'text',
'required' => true,
),
'url_key' => array(
'label' => $this->__('URL Key'),
'input' => 'text',
'required' => true,
),
'image' => array(
'label' => $this->__('Image'),
'input' => 'image',
'required' => true,
'disabled' => false,
'readonly' => true,
),
'visibility' => array(
'label' => $this->__('Visibility'),
'input' => 'select',
'required' => true,
'options' => $brandSingleton->getAvailableVisibilies(),
),
/**
* Note: we have not included created_at or updated_at,
* we will handle those fields ourself in the Model before save.
*/
));
return $this;
}
/**
* This method makes life a little easier for us by pre-populating
* fields with $_POST data where applicable and wraps our post data in
* 'brandData' so we can easily separate all relevant information in
* the controller. You can 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('brandData'));
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 always the same
$_data['title'] = $_data['label'];
// if no new value exists, use existing brand data
if (!array_key_exists('value', $_data)) {
$_data['value'] = $this->_getBrand()->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 _getBrand()
{
if (!$this->hasData('brand')) {
// this will have been set in the controller
$brand = Mage::registry('current_brand');
// just in case the controller does not register the brand
if (!$brand instanceof
SmashingMagazine_BrandDirectory_Model_Brand) {
$brand = Mage::getModel(
'smashingmagazine_branddirectory/brand'
);
}
$this->setData('brand', $brand);
}
return $this->getData('brand');
}
}
And this is my Controller File:
<?php
class SmashingMagazine_BrandDirectory_Adminhtml_BrandController
extends Mage_Adminhtml_Controller_Action
{
/**
* Instantiate our grid container block and add to the page content.
* When accessing this admin index page we will see a grid of all
* brands currently available in our Magento instance, along with
* a button to add a new one if we wish.
*/
public function indexAction()
{
// instantiate the grid container
$brandBlock = $this->getLayout()
->createBlock('smashingmagazine_branddirectory_adminhtml/brand');
// add the grid container as the only item on this page
$this->loadLayout()
->_addContent($brandBlock)
->renderLayout();
}
/**
* This action handles both viewing and editing of existing brands.
*/
public function editAction()
{
/**
* retrieving existing brand data if an ID was specified,
* if not we will have an empty Brand entity ready to be populated.
*/
$brand = Mage::getModel('smashingmagazine_branddirectory/brand');
if ($brandId = $this->getRequest()->getParam('id', false)) {
$brand->load($brandId);
if ($brand->getId() < 1) {
$this->_getSession()->addError(
$this->__('This brand no longer exists.')
);
return $this->_redirect(
'smashingmagazine_branddirectory_admin/brand/index'
);
}
}
// process $_POST data if the form was submitted
if ($postData = $this->getRequest()->getPost('brandData')) {
try {
// image upload
if(isset($_FILES['image']['name']) and (file_exists($_FILES['image']['tmp_name'])))
{
try
{
$path = Mage::getBaseDir('media') . DS . 'banner' . DS;
$uploader = new Varien_File_Uploader('image');
$uploader
->setAllowedExtensions(array('jpg','png','gif','jpeg'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$destFile = $path.$_FILES[$image]['name'];
$filename = $uploader->getNewFileName($destFile);
$uploader->save($path, $filename);
$data['img'] = $_FILES['image']['name'];
}
catch(Exception $e)
{
}
}
else
{
if(isset($data['image']['delete']) && $postData['image']['delete'] == 1)
$data['image'] = '';
else
unset($data['image']);
}
// continue
$brand->addData($postData);
$brand->save();
$this->_getSession()->addSuccess(
$this->__($_FILES['image']['name'])
);
// redirect to remove $_POST data from the request
return $this->_redirect(
'smashingmagazine_branddirectory_admin/brand/edit',
array('id' => $brand->getId())
);
} catch (Exception $e) {
Mage::logException($e);
$this->_getSession()->addError($e->getMessage());
}
/**
* if we get to here then something went wrong. Continue to
* render the page as before, the difference being this time
* the submitted $_POST data is available.
*/
}
// make the current brand object available to blocks
Mage::register('current_brand', $brand);
// instantiate the form container
$brandEditBlock = $this->getLayout()->createBlock(
'smashingmagazine_branddirectory_adminhtml/brand_edit'
);
// add the form container as the only item on this page
$this->loadLayout()
->_addContent($brandEditBlock)
->renderLayout();
}
public function deleteAction()
{
$brand = Mage::getModel('smashingmagazine_branddirectory/brand');
if ($brandId = $this->getRequest()->getParam('id', false)) {
$brand->load($brandId);
}
if ($brand->getId() < 1) {
$this->_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'
);
}
/**
* Thanks to Ben for pointing out this method was missing. Without
* this method the ACL rules configured in adminhtml.xml are ignored.
*/
protected function _isAllowed()
{
/**
* we include this switch to demonstrate that you can add action
* level restrictions in your ACL rules. The isAllowed() method will
* use the ACL rule we have configured in our adminhtml.xml file:
* - acl
* - - resources
* - - - admin
* - - - - children
* - - - - - smashingmagazine_branddirectory
* - - - - - - children
* - - - - - - - brand
*
* eg. you could add more rules inside brand for edit and delete.
*/
$actionName = $this->getRequest()->getActionName();
switch ($actionName) {
case 'index':
case 'edit':
case 'delete':
// intentionally no break
default:
$adminSession = Mage::getSingleton('admin/session');
$isAllowed = $adminSession
->isAllowed('smashingmagazine_branddirectory/brand');
break;
}
return $isAllowed;
}
}
Thanks in advance.
// add the fields we want to be editable
$this->_addFieldsToFieldset($fieldset, array(
'name' => array(
'label' => $this->__('Name'),
'input' => 'text',
'required' => true,
),
'url_key' => array(
'label' => $this->__('URL Key'),
'input' => 'text',
'required' => true,
),
'image' => array(
'label' => $this->__('Image'),
'input' => 'image',
'name' => 'image',
'required' => true,
'disabled' => false,
),
'visibility' => array(
'label' => $this->__('Visibility'),
'input' => 'select',
'required' => true,
'options' => $brandSingleton->getAvailableVisibilies(),
),
/**
* Note: we have not included created_at or updated_at,
* we will handle those fields ourself in the Model before save.
*/
));
Try this by adding name attribute on image.
I've created an admin module based off of the tutorial here. I'm attempting to change two of my form inputs to wysiwyg editors based off of information found here. However, whenever I load the edit page I get an error Call to a member function setCanLoadTinyMce() on a non-object. $this->getLayout()->getBlock('head') var_dumps to false.
Namespace/Slides/Block/Adminhtml/Slide/Edit.php looks as follows
class Namespace_Slides_Block_Adminhtml_Slide_Edit
extends Mage_Adminhtml_Block_Widget_Form_Container
{
protected function _prepareLayout()
{
parent::_prepareLayout();
if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
}
}
protected function _construct()
{
//... Construction stuff
}
}
Namespace/Slides/Block/Adminhtml/Slide/Edit/Form.php
class Cfw_Slides_Block_Adminhtml_Slide_Edit_Form
extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
//...Do some things first, like create the fieldset..
//Add the editable fields
$this->_addFieldsToFieldset($fieldset, array(
'foreground_image' => array(
'label' => $this->__('Foreground Image'),
'input' => 'image',
'required' => false,
),
'background_image' => array(
'label' => $this->__('Background Image'),
'input' => 'editor',
'required' => true,
'config' => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
'wysiwyg' => true,
),
'description' => array(
'label' => $this->__('Text Overlay'),
'input' => 'editor',
'required' => false,
'config' => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
'wysiwyg' => true,
)
));
return $this;
}
protected function _addFieldsToFieldset(
Varien_Data_Form_ElementFieldset $fieldset, $fields)
{
$requestData = new Varien_Object($this->getRequest()->getPost('slideData'));
foreach ($fields as $name => $_data) {
if ($requestValue = $requestData->getData($name)) {
$_data['value'] = $requestValue;
}
//Wrap all fields with slideData group
$_data['name'] = "slideData[$name]";
//Generally, label and title are always the same
$_data['title'] = $_data['label'];
//If no new value exists, use the existing slide data.
if (!array_key_exists('value', $_data)) {
$_data['value'] = $this->_getSlide()->getData($name);
}
//Finally, call vanilla funcctionality to add field.
$fieldset->addField($name, $_data['input'], $_data);
}
return $this;
}
}
I'm not sure if you need it, but here's my file structure as well
Namespace
-Slides
--Block
---Adminhtml
----Slide
-----Edit
------Form.php
-----Edit.php
-----Grid.php
----Slide.php
--controllers
---Adminhtml
----SlideConroller.php
--etc
---config.xml
--Helper
---Data.php
--Model
---Resource
----Slide
-----Collection.php
----Slide.php
---Slide.php
--sql
---namespace_slides_setup
----install-0.0.1.php
The issue is that Magento cannot find your head block.
Instead of using:
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
Try calling it like this:
Mage::app()->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
If that doesn't work, it's a different issue but the problem is still that Magento can't find the head block.
I imagine you no longer need a solution for this, but I ran into the same issue using the same tutorial that you did.
The 'head' block (and thus setCanLoadTinyMce()) was unavailable in the Edit.php and the Form.php via the _prepareLayout() function.
The 'head' block was available in the controller(SlideController.php in your case) between $this->loadLayout() and $this->renderLayout within the editAction() function.
In SlideController.php change
$this->loadLayout()
->_addContent($brandBlock)
->renderLayout();
to
$this->loadLayout() ;
$this->_addContent($brandBlock);
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
$this->renderLayout();
I am working on an edit screen for my grid row. This is what I have so far for this form:
<?php
class Intellibi_Integration_Block_Adminhtml_Manageasendiapickinglists_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('integration_form', array(
'legend' => Mage::helper('integration')->__('Asendia Pick Information')
));
$fieldset->addField('order_number', 'label', array(
'label' => Mage::helper('integration')->__('Order Number'),
'name' => 'order_number'
));
// snipped
$fieldset->addField('pick_status', 'select', array(
'required' => false,
'class' => 'required-entry',
'label' => Mage::helper('integration')->__('Pick Status'),
'name' => 'pick_status',
'values' => Mage::getSingleton('ibi/asendiapickstatus')->getOptionArray(),
'readonly' => 'readonly'
));
// snipped
return parent::_prepareForm();
}
}
This produces the following output in the admin backend:
What I would like to do is change the pick_status column from a select to a label. When I do this, instead of showing the status value "New" it shows the array index like this:
My option array for asendiapickstatus is defined like this in my model:
class Intellibi_Integration_Model_Asendiapickstatus extends Varien_Object
{
const PICK_STATUS_NEW = 1;
const PICK_STATUS_SENT = 2;
const PICK_STATUS_SHIPPED = 3;
static public function getOptionArray()
{
return array(
self::PICK_STATUS_NEW => Mage::helper('integration')->__('New'),
self::PICK_STATUS_SENT => Mage::helper('integration')->__('Sent'),
self::PICK_STATUS_SHIPPED => Mage::helper('integration')->__('Shipped')
);
}
}
So my question is; on the edit form fieldset builder, how do I show the dropdown field "pick_status" value, rather than the current index it's at? So the output will say "New" instead of "1" as shown above. Will I need a custom renderer?
I've solved it like this (with a custom form rendered element):
Added custom fieldset type
$fieldset->addType('pickstatus', 'Intellibi_Integration_Block_Adminhtml_Manageasendiapickinglists_Edit_Tab_Form_Renderer_Fieldset_Pickstatus');
Used the fieldset like this
$fieldset->addField('pick_status', 'pickstatus', array(
'label' => Mage::helper('integration')->__('Pick Status'),
'name' => 'pick_status',
));
Coded the rendered like this
class Intellibi_Integration_Block_Adminhtml_Manageasendiapickinglists_Edit_Tab_Form_Renderer_Fieldset_Pickstatus extends Varien_Data_Form_Element_Abstract
{
protected $_element;
public function getElementHtml()
{
// Load Pick Status
$pick_status = (int)$this->getValue();
$pick_status_list = Mage::getSingleton('ibi/asendiapickstatus')->getOptionArray();
// Finish
return array_key_exists($pick_status, $pick_status_list) ? $pick_status_list[$pick_status] : 'Unknown';
}
}
And it renders like this
Having some trouble with CGridView on Yii Framework...
I'm looking to replace the contents of a column based on the value it holds.
I need to handle special cases so I added a function into the model to return a value to the GridView.
I get the resulting error " Undefined variable: model ".
I'm sure it's likely something simple. Is it because my dataProvider is not model?
Here is a shortened version of my code:
<?php
/* #var $this BookController */
/* #var $dataProvider CActiveDataProvider */
/* #var $model Book */
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'book-grid',
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'name'=>'userName',
'header'=>'Name',
),
array(
'name'=>'status',
'header'=>'Status',
'type'=>'raw',
'value'=>array($model, 'statusText')
),
)
));
?>
And here is code in models/Book.php
class Book extends CActiveRecord
{
...
...
public function statusText($data, $row) {
$content = '';
if (CHtml::encode($data->status) == "processed") {
$content = "Process completed";
}
else if ($data->status=="") {
$content = "Queued for Processing";
}
else {
$content = CHtml::encode($data->status);
}
return $content;
}
...
...
}
Here is a simplified example from my current project;
<?php
//My controller
class NewsController extends CController {
//The admin action
public function actionAdmin() {
$model = new News;
$this->render('admin', array(
'model' => $model
));
}
}
//In my view file
$this->widget('ext.widgets.MyTbGridView', array(
'dataProvider' => $model->search(),
'columns' => array(
array(
'name' => 'id',
'filter' => false,
),
array(
'name' => 'title',
),
array(
'value' => array($model, 'gridDate')
),
),
));
//My model function
class News extends CActiveRecord {
public function gridDate($data, $row) {
return 'Date formatted!';
}
}
?>
The code 'value' => array($model, 'gridFormatDate'), is important. there are two possibilities here. The function can reside in the controller, in which case it should be 'value' => array($this, 'gridFormatDate'), or it can be in the model, in which case the correct code is given
In stead of array($model, 'statusText'), try '$data->statusText'.
The method in your model should be like this:
public function getStatusText() {
$content = '';
if (CHtml::encode($this->status) == "processed") {
$content = "Process completed";
}
else if ($this->status=="") {
$content = "Queued for Processing";
}
else {
$content = CHtml::encode($this->status);
}
return $content;
}