Form Field

Posted Almost 9 years ago. Visible to the public.

A sample of different options to add field in Mage_Adminhtml_Block_Widget_Form

Ref Varien_Data_Form_Element_Abstract lib\Varien\Data\Form\Element\Abstract.php

Add Suffix to Element Names

$form = new Varien_Data_Form(['field_name_suffix' => 'ihe']);

Date and Date-time Fields

$dateFormatIso = Mage::app()->getLocale()->getDateFormat(
    Mage_Core_Model_Locale::FORMAT_TYPE_SHORT
);        
$fieldset->addField('established_at', 'date', [
    'name'      => 'established_at',
    'image'     => $this->getSkinUrl('images/grid-cal.gif'),
    'format'    => $dateFormatIso,
    'label'     => $helper->__('Established At'),
    'disabled'  => '1',
]);

$dateTimeFormatIso = Mage::app()->getLocale()->getDateTimeFormat(
    Mage_Core_Model_Locale::FORMAT_TYPE_SHORT
);
$fieldset->addField('mc_scheduled_at', 'datetime', [
    'name'      => 'mc_scheduled_at',
    'image'     => $this->getSkinUrl('images/grid-cal.gif'),
    'format'    => $dateTimeFormatIso,
    'time'      => true,
    'label'     => $helper->__('Appointment Date')
]);

See lib\Varien\Data\Form\Element\Date.php, there is a locale property to specify ~~timezone~~.

In controller save action:

$data = $this->getRequest()->getPost();
$data = $this->_filterDates($data, ['established_at']);
$data = $this->_filterDateTime($data, ['mc_scheduled_at']);

Select Fields

$fieldset->addField('enabled', 'select', [
    'name'      => 'enabled',
    'label'     => $helper->__('Enabled'),
    'required'  => true,
    'options'   => Mage::getSingleton('adminhtml/system_config_source_yesno')->toArray(),
]);

$fieldset->addField('enabled', 'select', [
    'name'      => 'enabled',
    'label'     => $helper->__('Enabled'),
    'required'  => true,
    'options'   => array(
        0 => Mage::helper('adminhtml')->__('No'),
        1 => Mage::helper('adminhtml')->__('Yes'),
    ),
]);

$fieldset->addField('enabled', 'select', [
    'name'      => 'enabled',
    'label'     => $helper->__('Enabled'),
    'required'  => true,
    'values'    => array(
        array('value' => 1, 'label'=>Mage::helper('adminhtml')->__('Yes')),
        array('value' => 0, 'label'=>Mage::helper('adminhtml')->__('No')),
    ),
    'value'     => 1 // set default to Yes
]);

$options = [0,1,2,3,4,5,6];  
$fieldset->addField('setara', 'select', [
    'name'      => 'setara',
    'label'     => $helper->__('SETARA'),
    'options'   => $options,
    'required'  => true,
]);

Multiselect

Multiselect must use config key values.

$fieldset->addField('a_required_subject', 'multiselect', [
    'name'      => 'a_required_subject',
    'label'     => Mage::helper('course')->__('Required Subjects'),
    'values'    => $options
]);

/** @var Sxix_Provider_Model_Source_Benefit $source */
$source = Mage::getSingleton('provider/source_benefit');
$fieldset->addField('benefit_id', 'multiselect', [
    'name'      => 'benefit_id',
    'label'     => $helper->__('Benefit'),
    'values'    => $source->toOptionArray(false)
]);

Label Field

To add as a label to show info, no editing:

$fieldset->addField('patient_name', 'label', [
    'label'     => Mage::helper('medical')->__('Patient Fullname'),
    'bold'      => true
]);
$form->setValues($model->getData());

// If there is no $form->setValues()
$fieldset->addField('name', 'label', [
    'label'     => Mage::helper('medical')->__('Fullname'),
    'bold'      => true,
    'value'     => 'Joe Smith'
]);

// Render HTML
$fieldset->addField('status', 'label', [
    'label'     => $helper->__('Status'),
    'after_element_html' => "<span title=\"{$order->getStatus()}\"><strong>{$order->getStatusLabel()}</strong></span>"
]);

Renderer - Add additional block

$fieldset = $form->addFieldset('location_map', array(
    'legend'=>Mage::helper('documentcontrol')->__('Location Map')
));

$fieldset->addField('lat', 'text', array(
    'name'      => 'lat',
    'label'     => Mage::helper('documentcontrol')->__('Latitude'),            
));

$fieldset->addField('lng', 'text', array(
    'name'      => 'lng',
    'label'     => Mage::helper('documentcontrol')->__('Longitude'),            
)); 
       
$mapField = $fieldset->addField('geocode', 'note', array(
    'name'      => 'geocode',
    'text'      => '',           
));
$renderer = $this->getLayout()->createBlock('documentcontrol/adminhtml_ihe_edit_tab_renderer_map');
$mapField->setRenderer($renderer); 

Checkbox Field

$fieldset->addField('to_check_sticker', 'checkbox', [
    'label'             => Mage::helper('documentcontrol')->__('Check Sticker'),
    'onclick'           => 'this.value = this.checked ? 1 : 0;',
    'name'              => 'to_check_sticker',
]); 

Add JS

$fieldset->addField('status', 'select', [
    'name'      => 'status',
    'label'     => $helper->__('Status'),
    'options'   => $source->toOptionHash(),
    'onchange'  => "this.selectedIndex?$('comment').up('tr').show():$('comment').up('tr').hide();"
]);

$fieldset->addField('comment', 'text', [
    'name'      => 'comment',
    'label'     => $helper->__('Comment'),
    'after_element_html' => "<script>$('comment').up('tr').hide();</script>"
]);

$fieldset->addField('sns', 'textarea', [
    'name'      => 'sns',  
    'required'  => true,
    'note'      => $helper->__('<b>IMPORTANT</b>: Separate each S/N with comma, without space.'),
    'after_element_html' => "<script>$('sns').up('td').previous('td').remove();$('sns').up('td').colspan=2;</script>"
]);

Add Custom Field Element Type

Add custom element type apply.

$fieldset->addField('apply_to', 'apply', array(
    'name'        => 'apply_to[]',
    'label'       => Mage::helper('extendedcustomer')->__('Apply To'),            
    'values'      => Mage::helper('extendedcustomer')->getCustomerGroupOptionArray(),
    'mode_labels' => array(
        'all'     => Mage::helper('extendedcustomer')->__('All Customer Groups'),
        'custom'  => Mage::helper('extendedcustomer')->__('Selected Customer Groups')
    ),
    'required'    => true
), 'frontend_class');
        

Define the type name and class name:

/**
 * Retrieve additional element types for customer attributes - reuse catalog_product
 *
 * @return array
 */
protected function _getAdditionalElementTypes()
{
    return array(
        'apply' => Mage::getConfig()->getBlockClassName('adminhtml/catalog_product_helper_form_apply')
    );
}

The custom element type can be added in 2 ways:

  1. By calling $this->_addElementTypes($fieldset); after declaring $fieldset and before $fieldset->addField().
  2. In Mage_Adminhtml_Block_Widget_Form::_setFieldset().

Text Field


$fieldset->addField('toefl_pbt', 'text', [
    'name'      => 'toefl_pbt',
    'label'     => Mage::helper('course')->__('TOEFL PBT'),
    'class'     =>'validate-number-range number-range-310-677',
    'note'      => Mage::helper('course')->__('Lowest TOEFL PBT score is 310, highest is 677.'),
]);

$fieldset->addField('additional_emails', 'text', array (
    'name'      => 'additional_emails',
    'maxlength' => '255',
    'label'     => Mage::helper('documentcontrol')->__('Additional Emails'),
    'note'      => Mage::helper('documentcontrol')->__('Separate each email with a comma, wothout space (CSV)')
));

$fieldset->addField('contact_email', 'text', array(
    'name'      => 'contact_email',
    'label'     => Mage::helper('swms')->__('Contact Email'),
    'class'     => 'validate-email'
)); 
 

$fieldset->addField('nec', 'text', array(
    'name'      => 'nec',
    'label'     => Mage::helper('course')->__('NEC'),
    'note'      => Mage::helper('course')->__('3 alphanumeric charaters only'),
    'required'  => true,
    'class'     => 'validate-alphanum validate-length maximum-length-3 minimum-length-3 '
));

$fieldset->addField($input['attribute_code'], $input['frontend_input'], [
    'name'      => $input['attribute_code'],
    'label'     => $input['store_label'],
    'class'     => $input['frontend_class'] ?? '',
    'required'  => $input['is_required'],
    'note'      => $input['note'],
    'title'     => $input['store_label'].' ":value="item.'.$input['attribute_code'] // vue.js hack
]); 

Link Field

        /** @see Varien_Data_Form_Element_Link */
        $fieldset->addField('billing_iid', 'link', [
            'label'     => $helper->__('Billing iId'),
            'href'      => $this->getUrl('*/billing/view', ['id' => $model->getBillingId()]),
        ]);

To make the attribute in customer page read only:

UPDATE `eav_attribute` SET `note` = 'Read only<script type="text/javascript">$(''_extendedattendance'').readOnly=true</script>' WHERE `attribute_id` = 218;

Input Name Array

Group input elements by array.

        $form = new Varien_Data_Form();
        $form->setFieldNameSuffix('user');
        $this->setForm($form);
        
        //...
        
        $fieldset->addField('username', 'text', [
            'name'      => 'username',
            'label'     => $helper->__('User Name'),
            'required'  => true,
        ]);
<input id="username" name="user[username]" value="" type="text" class=" input-text required-entry">
kiatng
Last edit
9 months ago
kiatng
Tags
Posted by kiatng to OpenMage (2015-08-05 10:11)