In Depth Magento System Configuration(magento system.xml说明)

Like this article? Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Last time we talked about Magento’s System Configuration system. If you missed it, you’ll want to go back and catch up. So, we glossed over a lot of the tags you could use within an individual field.


    
    
        
        text
        2
        1
        1
        0
    
    

Consider the rest of this article a thorough de-glossing.

These tags allow you to set end-user facing text for your System Configuration field.

A label appears to the left of your form field, while a comment will appear directly under the field.

A label appears to the left of your form field, while a comment will appear directly under the field.

, ,

These are boolean fields with a value of 1 or 0. They indicate if the field will show up when viewing the System Configuration in the default view, the website view, or the store view.

The implicit assumption is that they also control what options are configurable at each level. However, there’s nothing on the backend enforcing this assumption. That is, a field may be configured to with the following

 0 

but it will still be possible (although not advisable) to set and retrieve this field’s value at the store level via programatic means.

The  is a numerical value that’s used to determine the order of the fields within their group container. The higher the number, the lower the field will sort on the screen.

 determines the type of field that will be used to collect the configuration value. Values supported in Magento 1.4 Community Edition are

  1. allowspecific
  2. export
  3. image
  4. import
  5. label
  6. multiselect
  7. obscure
  8. password
  9. select
  10. text
  11. textarea
  12. time


The value of this field is used in a Factory style pattern to instantiate a class with a format of

Varien_Data_Form_Element_Type

where “Type” is the value of the ’s text node. This happens in the addField method of theVarien_Data_Form_Element_Abstract class, as seen below

class Varien_Data_Form_Abstract extends Varien_Object
{
    //...
    public function addField($elementId, $type, $config, $after=false)
    {
        if (isset($this->_types[$type])) {
            $className = $this->_types[$type];
        }
        else {
            $className = 'Varien_Data_Form_Element_'.ucfirst(strtolower($type));
        }

        $element = new $className($config);
        $element->setId($elementId);
        if ($element->getRequired()) {
            $element->addClass('required-entry');
        }
        $this->addElement($element, $after);
        return $element;
    }
}

Don’t be fooled,  is not a Grouped Class Name. The  tag can be used to modify the class attribute of the form element tag that’s generated for your field. That is, this config field allows you to add a Cascading Stylesheet Class (i.e. “frontend” class) to the generated form element.

For example, a field configured with the following

select
free-method

will render as


As with much of Magento, there’s more going on here. The presence of this CSS class will trigger the system’s client-side validation routines. For example, the above code would cause a javascript email validation to be run against the field. If the field fails the validation test, the end-user won’t be able to submit the configuration form.

You can take a look at the available validation routines in

js/prototype/validation.js

and here’s the above mentioned email validation routine from the same file

['validate-email', 'Please enter a valid email address. For example [email protected].', function (v) {
            return Validation.get('IsEmpty').test(v) || /^[a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]+(\.[a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})/i.test(v)
        }],

which looks to be a monstrous, but useful, regular expression.

The  tag is used with multiselect fields. The short version is, if you wish to a allow “no selection” to be a valid configuration, use this field.

What happens behind the scenes is if can_be_empty is true, the system renders a hidden field on the System Configuration page

File: lib/Varien/Data/Form/Element/Multiselect.php

if ($this->getCanBeEmpty()) {
    $html .= '';
}

which ensure the form processing code will accept an empty selection.

 allows you specify that your configuration field should only be displayed when another confgiruation field in the same group has a specific value.

For example, the Paypal Express System Configuration has the following select defined.


    
    multiselect
    110
    adminhtml/system_config_source_country
    1
    1
    0
    1

You’ll notice the

1

This is telling the system that if the  field (defined with the following)


   
   select
   100    adminhtml/system_config_source_payment_allspecificcountries
   1
   1
   0

has a value of “1”, then the  field should be displayed. This happens instantly via some behind the scenes Javascript.

While it appears to work with any fields that send out on onchange event, the core Magento system only uses this function where the parent field is a select. If you’re paranoid about forward compatibility, I’d apply the same restriction to your own System Configuration fields, as it’s hard to tell where the core Magento team may take this feature in the future.

The  tag specifies a Model class (in URI/Grouped Class Name format) to populate a field’s default options. As of Magento Community Edition 1.4x, it works with selects and multi-selects. In addition to the standard Magento Grouped Class Name, an extended syntax of

module/modelname::methodName

is supported. The system will instantiate a Model with getModel('module/modelname') and call its methodNamemethod to retrieve an array of value/label paris to use for the source. If the method name is left off, thetoOptionArray method will be called by default.

By default, Magento Form Elements are rendered with the Block class

Mage_Adminhtml_Block_System_Config_Form_Field

However, if you want to use a custom renderer for your System Configuration field, you can specify a different block class (in URI/Grouped Class Name form) with the  tag.

For example, the last_update field in the adminnotification group


    
    label
    adminhtml/system_config_form_field_notification
    3
    1
    0
    0
 

specifies that a field renderer of adminhtml/system_config_form_field_notification should be used. This translates into the following class

File: app/code/core/Mage/Adminhtml/Block/System/Config/Form/Field/Notification.php
class Mage_Adminhtml_Block_System_Config_Form_Field_Notification extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        $element->setValue(Mage::app()->loadCache('admin_notifications_lastcheck'));
        $format = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM);
        return Mage::app()->getLocale()->date(intval($element->getValue()))->toString($format);
    }
}

The core team is overriding the _getElementHtml method to ensure that any entered date will be displayed with the same format.

Once a form is submitted to Magento, its values must be saved. For System Configuration fields, this is normally handeled with the Model class

Mage_Core_Model_Config_Data

However, there may be times where you want your System Configuration to use a different backend model. The tag allows you to specify a different Model class (using URI/Grouped Class Name format).

Most often this isn’t because you want to save where the data is stored, but rather because you want to perform some additional action when a field is saved. By extending the Mage_Core_Model_Config_Data class with your own model and defining a _beforeSave and/or _afterSave method on your model, you can take additional action anytime a config value is changed.

For example, consider the import field in the tablerate group


    
    import
    adminhtml/system_config_backend_shipping_tablerate
    6
    0
    1
    0

The Grouped Class Name adminhtml/system_config_backend_shipping_tablerate translates to the following class

class Mage_Adminhtml_Model_System_Config_Backend_Shipping_Tablerate extends Mage_Core_Model_Config_Data
{
    public function _afterSave()
    {
        Mage::getResourceModel('shipping/carrier_tablerate')->uploadAndImport($this);
    }
}

Here the core team is hooking into the _afterSave method (which is called after a model is saved) to update theshipping/carrier_tablerate Model with information from the just uploaded file.

and

Both these tags are used with System Configuration fields that use the imagefield with a adminhtml/system_config_backend_image backend model. These determine both

  1. Where the image file is uploaded
  2. The base URI path used when rendering an  tag

First, let’s cover the  tag

sales/store/logo

There’s three things being set by the above.

  1. The base image upload path
  2. The path, from the base, where this specific image field should be uploaded
  3. Whether or not the current config scope should be appended to the path

The base image upload path is set with the config attribute (system/filesystem/media above). This specifies a System Configuration path. That is, the base image upload path isn’t system/filesystem/media, but it’s the value of the Magento System Configuration at system/filesystem/media (which resolves to {{root_dir}}/mediain a default Community Edition install)

Once the base image upload path is found, we need to append the sub-directory this specific image should be uploaded to. To get this we append the value of the 's text node

sales/store/logo

to the value of the base image upload path, which will give us something like this

/path/to/magento/install/media/sales/store/logo

Finally, if the scope attribute is set to “1”, the current Configuration Scope will be transformed into a path. If you were uploading an image with the scope set to default, you’d get a path like

/path/to/magento/install/media/sales/store/logo/default

However, if you were uploading an image with the scope set to a specific store, you’d end up with a path like

/path/to/magento/install/media/sales/store/logo/stores/5

where “5” is the ID of the store scope you’re currently at.

When we upload an image, only the scope and image name portion of the path get saved to the config. This means we need to tell the System what the base URL should be for our image.

sales/store/logo

The scope_info and text node function the same as ’s. Where  differs is in setting thebase of the image URI (which is going to, naturally, be different than the local base file system path).

As you’ve likely intuited, the base path is set using the type attribute. The configured value will be passed into the getBaseUrl method on the global Mage object to set the base URL for the image. The the above example, that would look something like

Mage::getBaseUrl('media')

You can see the actual code that does this in the Mage_Adminhtml_Block_System_Config_Form_Field_Image class.

class Mage_Adminhtml_Block_System_Config_Form_Field_Image extends Varien_Data_Form_Element_Image
{
    //...

    protected function _getUrl()
    {
        $url = parent::_getUrl();

        $config = $this->getFieldConfig();
        /* @var $config Varien_Simplexml_Element */
        if (!empty($config->base_url)) {
            $el = $config->descend('base_url');
            $urlType = empty($el['type']) ? 'link' : (string)$el['type'];
            $url = Mage::getBaseUrl($urlType) . (string)$config->base_url . '/' . $url;
        }

        return $url;
    }

    //...
}

Finally, it’s important to note that this base URL is not used consistently throughout Magento to create a final URL for a configured image. From what I’ve seen this is only used to create an image preview within the System Configuration admin itself.

Wrapup

As you can see, the Magento System Configuration admin is a powerful system that’s almost an application development environment unto itself. By leveraging the functionality built into the system you can quickly and reliably build out new custom functionality for your, or your client’s stores.

来源:http://alanstorm.com/magento_system_configuration_in_depth_tutorial

你可能感兴趣的:(magento)