1

I am using magento 1.9.2.4

I need to one unique and require field in my custom module form

I am using below code for form field

class Test_Brand_Block_Adminhtml_Brand_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
 {
            protected function _prepareForm()
            {   
                $model = Mage::registry('test_brand');
                $fieldset->addField('option_identifier', 'text', array(
                'name'      => 'option_identifier',
                'label'     => Mage::helper('checkout')->__('Option Identifier'),
                'title'     => Mage::helper('checkout')->__('Option Identifier'),
                'required'  => true,
                ));
             }


}
3
  • What do you mean by unique field in form? Dec 15, 2016 at 7:24
  • i need to set option_identifier require and unique Dec 15, 2016 at 7:27
  • option_identifier is dynamic generate or manually created
    – Amit Bera
    Dec 15, 2016 at 7:34

2 Answers 2

1

Using 'required' => true, in form field you can make field is required. But you can not make field value unique without custom code.

You have to create database field unique and also check in your post action first if that field is unique or not if it is not unique then throw exceptation

public function postAction()
    {
        $post = $this->getRequest()->getPost();
        if ( $post ) {
            if($this->getRequest()->getPost('your-field')){
                $collection = Mage::getModel('yourmodel/yourmodel')->getCollection();
                $collection->addFieldToFilter('your-field',$this->getRequest()->getPost('your-field'));
                if(count($collection)){
                    Mage::getSingleton('customer/session')->addError(Mage::helper('yourhelper')->__('your-field name is not unique'));
                    $this->_redirect('*/*/');
                    return;
                }
            }
        }
    }

Above is example use it as reference make it as per your need

1
1

The best way is:

1) Add to source model this.

protected function _construct()
{
    $this->_init("your_module/your_model", "super_id");

    $this->addUniqueField(array(
        'field' => 'name',
        'title' => Mage::helper('loyalty')->__('This name has already been taken.')
    ));
}

2: Try catch exceptions of Mage_Core_Exception

try {
    $model = Mage::getModel("your_module/your_model")->load('some_id');
    $model->setName('I am bad man!');
    $model->save();

} catch (Mage_Core_Exception $e) {
    Mage::getSingleton("adminhtml/session")->addError(
    $e->getMessage()
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.