1

I have a custom component where the user can add some data. Here are the two relevant fields:

<field 
    name="title" 
    type="text" 
    label="Title" 
    description="Please enter a title" 
    required="true" 
/>
<field 
    name="alias" 
    type="text" 
    label="Alias" 
    description="Please enter an unique alias" 
    required="true" 
/>

I am currently using the standard 'save' method to save the form data. But the problem obvious is that it is saving duplicate alias items. Where and how will I add a check to ensure that the alias is not in use (just like with Menu Item or Article).

3

The best place is your table class before storing data. For example below code in store function of table class.

public function store ($updateNulls = false)
{
    if ($table->load(array('alias' => $this->alias, 'catid' => $this->catid)) && ($table->id != $this->id || $this->id == 0))
    {
        $this->setError(JText::_('COM_MYCOMPONENT_DATABASE_ERROR_UNIQUE_ALIAS').'| Alias: '.$this->alias);
        return false;
    }

    return parent::store($updateNulls);
}
  • Wouldn't the best place be during form validation ? – Max Apr 12 '18 at 8:59
1

I followed the answer and came up with the following:

  public function save($data){
        $table = $this->getTable();
        $table->load(array('alias' => $data['alias']));

        if (($table->alias == $data['alias']) && $table->id != $data['id'])
        {
            $this->setError(JText::_('COM_MYCOMPONENT_ALIAS_ALREADY_EXISTS').'| Alias: ' . $data['alias']);
            return false;
        }
        $save = parent::save($data);
    }

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

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