1

In my component, I have 3 tables, 2 object tables (Course and Module), and 1 linking table (Course_Modules).

In my edit form for courses I have a multi-select allowing users to pick 1 or more modules that are part of a course.

When this is saved, I need to add linking records with the courseId and moduleId to Course_modules.

However, I don't want to do this if the save fails - only if the course record saved correctly.

There seems to be innumerable places to make this happen (JTable save(), JControllerForm save(), JTable bind(), JTable store(), in the model), but I'd like it only to happen if the main save succeeded. Does anyone have guidance on how best to do this?

1 Answer 1

2

I would put it in the model:

public function save($data)
{
    $return = parent::save($data);

    if ($return)
    {
        $dispatcher = JDispatcher::getInstance();
        $table = $this->getTable();
        $key = $table->getKeyName();
        // $pk is the new id of the saved record
        $pk = (!empty($data[$key])) ? $data[$key] : (int) $this->getState($this->getName() . '.id');

        // here your save Course_Modules method
        return true;
    } else {
        return false;   
    }
}

Btw. I used to use this method of a third (linking) table too. Until I found the mysql function FIND_IN_SET. https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

You can store multiple module_id's in one field called module_ids.
For example '1,3,4,8'
With FIND_IN_SET you'll get your (frontend) queries without the need of a third table.

2
  • 1
    Not sure about FIND_IN_SET (normalisation!), but I like the <code>save</code> method. Thank you! Apr 10, 2015 at 10:42
  • I agree with @codinghands. When you think you need to use FIND_IN_SET(), you should actually normalize your data storage design. dba.stackexchange.com/a/174204/157408 Feb 2, 2019 at 0:30

Your Answer

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

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