How to validate a new custom category attribute in Magento, so that no more than 300 words can be written in that new field?
Is that possible? How could I achieve this? Thanks for your contributions.
When creating you category attribute like ...
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$attribute = array(
'group' => 'General Information',
'label' => 'Some Description',
'type' => 'text',
'input' => 'textarea',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible' => true,
'user_defined' => true,
'required' => false,
'default' => ''
);
$installer->addAttribute('catalog_category', 'your_attribute_code', $attribute);
$installer->endSetup();
add this two lines to your attribute data:
'frontend_class' => 'validate-length maximum-length-300',
'note' => 'Maximum length 300 characters',
This will enables Magentos form validation and disallow saving more then 300 characters from backend.
Update:
To have a visual feedback how many characters are left, you can add a JS file to your admin pages. It will display a character counter for every input field that has CSS classes validate-length
and maximum-length-XXX
:
<layout version="0.1.0">
<adminhtml_charactercounter>
<reference name="head">
<action method="addJs">
<script>admin-charactercounter.js</script>
</action>
</reference>
</adminhtml_charactercounter>
<adminhtml_catalog_product_edit>
<update handle="adminhtml_charactercounter"/>
</adminhtml_catalog_product_edit>
<adminhtml_system_config_edit>
<update handle="adminhtml_charactercounter"/>
</adminhtml_system_config_edit>
<!--
add other handles
...
-->
</layout>
Just add the layout handles for other pages where you need it ...
document.observe('dom:loaded', function() {
Element.addMethods({
prepare_for_countdown: function(element) {
var elm = $(element);
if(!elm.retrieve('counter')) {
var counter = new Element('span');
elm.next('.note').insert(counter);
elm.store('counter', counter);
var maxLen = elm.className.match(/maximum-length-(\d+)/)[1];
elm.store('maxLen', maxLen);
}
return elm;
},
countdown: function(element) {
var elm = $(element);
var curLen = elm.getValue().length;
var maxLen = elm.retrieve('maxLen');
var count = maxLen - curLen;
var counter = elm.retrieve('counter');
if (curLen >= maxLen) {
counter.update(' (' + count + ')').setStyle({'color': 'red'});
} else {
counter.update(' (+' + count + ')').setStyle({'color': 'green'});
}
return elm;
}
});
$$('.validate-length').invoke('prepare_for_countdown').invoke('countdown');
document.on('keyup', '.validate-length', function(evt, elm) {
elm.countdown();
});
});
config.xml
to 1.0
too, to trigger your update script? To check if its working you can also add frontend_class
in eav_attribute
table manually.