Search code examples
crudatk4

ATK4: Handling many to many relationships in CRUD - Adding subCRUD without breaking Add New


I'm trying to gracefully handle extra many to many relationship data in an ATK4 CRUD object. I can manually add the current entry's linked tables as sub CRUD objects while isEditing(), but in doing so i break the 'Add New' button. Code as follows:

    function page_projects($p) {
            $crud = $this->add('CRUD');
            $crud->setModel('Project', null, array('Title', 'School'));
            if($crud->grid){
                    $crud->grid->addPaginator(10);
                    $crud->grid->addQuicksearch(array('Title','School'));
            }

            if($crud->isEditing()){

                    $vForm = $crud->form;

                    $keywords = $vForm->add('CRUD');
                    $keywords->entity_name = 'Keyword';
                    $keywords->setModel(                            
                            $crud->model->load($crud->id)->
                                ref("mProjectKeywords"));
                    //Other snipped m:m rels            
            }

    }

The issue is simply that $crud->id is not populated (and shouldn't be) when generating a new entry, which means i can't spawn new sub cruds. A workaround is to use:

    if($crud->isEditing() && !is_null($crud->id)) {

when checking isEditing(), but this simply stops the sub CRUDS from being instantiated to avoid having load() throw an exception. I've tried looking at loadAny() and tryLoad() and neither do what i want in a many to many context: load a record if one exists, generate a new one otherwise.

Does anyone know a better way of handling this, and if there's not already one in the framework then what's the best angle for attacking this problem?


Solution

  • In this case that's normal behavior because you simply can't create mProjectKeywords record in database table before you INSERT referenced records in parent tables (Project and Keywords).

    I do something like if($crud->isEditing() && !is_null($crud->id)) in my projects too. That means you first have to save (insert) new record in Project and only then sub-CRUD shows up and you can add referenced records in Project edit form (which reloads automatically after you save new project).