Magento creating custom attribute with custom validations - magento

I need to create an attribute. Also i need to validate that attribute value. So i created a new .js file and add some functions. Then in setup file, i call the function name. But after creating the attribute that validation class wont come with the field.
$installer->addAttribute(MageTest_Module_Model_Name::ENTITY, 'test_value', array(
'input' => 'text',
'type' => 'text',
'label' => 'Test Value',
'backend' => '',
'user_defined' => false,
'visible' => 1,
'required' => 0,
'position' => 60,
'class' => 'validate-testValue',
'note' => 'This should contains 2 digits. Example 00',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));
'validate-testValue' is my js function name. Can anyone help me to solve this please.
Thank You.

to use Magento form validator you have to register your method with the Validator object.
Try something like that in your custom js file
Validation.add('validate-testValue','HERE your error message if the field is not valid',function(fieldValue) {
return Validation.get('IsEmpty').test(fieldValue) || fieldValue == "testValue";
});
Ok, this example will only validate if your field value is "testValue", not very usefull.
But you can adapt it I guess :)

Related

Unable to understand Install script (sql script) in Magento

I am adding attribute by updating sql script, like this,
$installer = $this;
$installer->startSetup();
$installer->addAttribute('customer_address', 'group_id', array(
'label' => 'Address group',
'visible' => true,
'required' => false,
'type' => 'int',
'input' => 'select',
'source' => 'address_group/address_attribute_source_group',
'user_defined' => 1,
'position' => 100
));
.
.
.
$installer->endSetup();
I am unable to understand what is meant by following line, I am unable to find any explanation about it
'source' => 'address_group/address_attribute_source_group',
I am unable to comment on your post. Trying to understand if you have copied this code from somewhere. From your code I understand that you want to add a "Customer Address Attribute" named as "customer_address"
'source' => 'address_group/address_attribute_source_group'
The implication of the above is the path. You should have a folder/file path as below:
/app/code/local/Address/Group/Model/Address/Attribute/Source/Group.php
Group.php:
class Address_Group_Model_Address_Attribute_Source_Group ...
Since, this attribute is of TYPE => "SELECT", you should be having the options array in this file "Group.php"
Options Array should be something very similar to:
public function toOptionsArray() {
return array(
array(
'label' => '',
'value' => ''
),
array(
'label' => Yes,
'value' => 1
),
array(
'label' => No,
'value' => 0
)
);
}
Let me know if you got it!
Happy to Help!
Happy Coding...
It points to the class that provides options for the attribute. As attribute uses select input it requires options to be provided. This class is created by calling Mage::getModel() and passing the value of source to it. To find the class you need to find node models/address_group in config.xml files of the available modules. This will provide class prefix. Next what comes after slash is added to that prefix in order to create class name. So in this case it will resolve to something like Company_AddressGroupModule_Model_Address_Attribute_Source_Group. This class need to implement toOptionsArray method that returns an array in the following format:
array(
array('value' => 'option_value', 'label' => 'option_label'),
...
);

How do I limit number of characters in the admin form in magento

I have following code in my Form.php
$fieldset->addField('desc', 'textarea', array(
'label' => Mage::helper('module')->__('Description'),
'required' => true,
'name' => 'desc',
));
How to restrict the number of characters in this text area?
In theory you should be able to do that by adding to the textarea a maxlength attribute.
So you should end up with something like this:
<textarea maxlength="50"></textarea>
But Magento does not allow the maxlength attribute.
If you take a look at the Varien_Data_Form_Element_Textarea class (the one responsable for rendering textareas) you will see this method.
public function getHtmlAttributes()
{
return array('title', 'class', 'style', 'onclick', 'onchange', 'rows', 'cols', 'readonly', 'disabled', 'onkeyup', 'tabindex');
}
Those are the only ones that you can specify when you create the element.
First option would be to extend this class and add the maxlength among the allowed attributes, then your column could look like this:
$fieldset->addField('desc', 'textarea', array(
'label' => Mage::helper('module')->__('Description'),
'required' => true,
'name' => 'desc',
'maxlength' => 50
));
The second option is to add it via some javascript.
$fieldset->addField('desc', 'textarea', array(
'label' => Mage::helper('module')->__('Description'),
'required' => true,
'name' => 'desc',
'after_element_html' => '<script type="text/javascript">Event.observe(window, "load", function() {$("id_of_textarea_here").setAttribute("maxlength", 50)})</script>'
));
A third option would be to insert instead of the javascript above some code that limits the length of the text.
You can find an example here.
Final Note:
the content from after_element_html will be displayed in the form right after the element. So you can basically put anything there.

Change category attribute within installation script

I have my module. This module has installation script where should be add custom image field to categories.
$setup->addAttribute('catalog_category', 'additional_image', array(
'type' => 'varchar',
'backend' => 'catalog/category_attribute_backend_image',
'label' => 'Additional Image',
'input' => 'image',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'visible' => 1,
'required' => 0,
'user_defined' => 0,
'default' => '',
'position' => 6,
));
After that it must change captions other image fields (Image, Thumbnail). How I can get this system's fields and change their?
You can do this using Mage_Eav_Model_Entity_Setup::updateAttribute() method.
This is a long way off but someone else may need the information.
Mage_Eav_Model_Entity_Setup::updateAttribute()
has 5 arguments, 3 of which are necessary.
I am going to use the example of a custom customer attribute:
$entityTypeId = 'customer'
$id = 'my_custom_attribute_code'
$field = 'is_used_for_customer_segment'
$value = '1'
$sortOrder = Not Needed
So as you can see I am using the customer entity to update the attribute. I am updating my custom attribute with attribute id (code) my_custom_attribute_code. The field in this attribute that I am udpating is the is_used_for_customer_segment and setting the value to yes(1).
Here is an example of how to do this as an update.
$installer->startSetup();
$installer->updateAttribute('customer', 'my_custom_attribute_code', 'is_used_for_customer_segment', '1');
$installer->endSetup();

Magento admin grid sending data from Action to Controller

I'm trying to write a custom action to run off of an admin grid that I have built. Is it possible to send a value from a column in the grid to the controller via either get or post?
I've tried googling, but I cannot find a proper explanation for this anywhere. A link to an explanation of the column settings ('getter', 'type' etc.) would also be useful if this is available.
Add this code to your Grid.php:
$this->addColumn('action',
array(
'header' => Mage::helper('yourmodulename')->__('Action'),
'width' => '100',
'type' => 'action',
'getter' => 'getId',
'actions' => array(
array(
'caption' => Mage::helper('yourmodulename')->__('Edit'),
'url' => array('base'=> '*/*/edit'),
'field' => 'id'
)
),
'filter' => false,
'sortable' => false,
'index' => 'stores',
'is_system' => true,
));
That will build an "Edit" URL with the Id of the selected row as part of the URL. It will look something like <frontname>/<controllername>/edit/id/<value> where value is returned by the getter getId().
The getter field will execute any of the standard Magento magic getters, ie any attribute is gettable. So you could have getName or getProductUrl or getIsLeftHanded if you wanted and your controller can parse the attribute.
The controller can then retrieve that passed value using Mage::app()->getRequest()->getParam('attributename');
In terms of documentation/tutorials, have a read of this article on the website of #AlanStorm as it might help.
HTH,
JD

cakePHP optional validation for file upload

How to make file uploading as optional with validation?
The code below validates even if i didn't selected any file.
I want to check the extension only if i selected the the file.
If i am not selecting any file it should not return any validation error.
class Catalog extends AppModel{
var $name = 'Catalog';
var $validate = array(
'name' => array(
'rule' => '/^[a-z0-9 ]{0,}$/i',
'allowEmpty' => false,
'message' => 'Invalid Catalog name'
),
'imageupload' => array(
'rule' => array('extension',array('jpeg','jpg','png','gif')),
'required' => false,
'allowEmpty' => true,
'message' => 'Invalid file'
),
);
}
thanks in advance
"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"
So by the time you save your data array, it looks something like this I assume:
array(
'image' => 'foobar',
'imageupload' => array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
)
Which means, the imageupload validation rule is trying to work on this data:
array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".
Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it.
Concept:
In Controller, before validating, or saving (which does validation automatically by default) check if any file is uploaded. If not uploaded, then unset validator for the file field.
Sample code:
Controller
// is any image uploaded?
$isNoFileUploaded = ($this->request->data['Model']['field_name']['error'] == UPLOAD_ERR_NO_FILE) ? true : false ;
if ($isNoFileUploaded) {
$this->Model->validator()->remove('field_name');
}
Notes:
This solution comes under preprocessing as one of the two alternative approaches (preprocessing in controller, custom validation in model) suggested by #deceze's answer

Resources