phpoctobercms

How to target a specific relation in onRelationManageCreate method in OctoberCMS?


OCMS CURRENT BUILD 476

PHP v7.4.21

I'm working on an OctoberCMS plugin and I'm facing an issue with the onRelationManageCreate method in my Controller. I have multiple relations defined in my model, but I want to apply some logic specifically to one of the hasMany relations called backuptasks. However, the code I've tried so far seems to impact all relations to the model instead of just the backuptasks relation.

Here's a simplified version of my code:

Controller/ControllerName.php

   public function onRelationManageCreate($relationName, $recordId = null)
   {
       // Check if the relation name is 'backuptasks'
       if ($relationName === 'backuptasks') {
           $maxAllowed = '1';
           $relationCount = BackupTask::where('machines_id', $recordId)->count();
   
           if ($relationCount >= $maxAllowed) {
               \Flash::error('Maximum limit of related records has been reached');
               return;
           }
       }
   
       // Continue with the regular onRelationManageCreate logic
       return $this->asExtension('RelationController')->onRelationManageCreate($relationName, $recordId);
   }

I've tried using conditionals like if ($relationName === 'backuptasks') to target the specific relation, but it doesn't seem to work as expected. The code within the conditional block still affects all relations instead of just backuptasks.

I've also tried using other approaches mentioned in the OctoberCMS documentation, such as extending the model and binding events, but I couldn't find a solution that specifically targets one relation only.

Is there a way to effectively target a specific relation in the onRelationManageCreate method without affecting other relations? Any insights or alternative approaches would be greatly appreciated.


Solution

  • Solved the issue with the below:

    public function onRelationManageCreate($id = [])
        {
            $recordId = $id;
    
            $parentModel = ParentModel::find($recordId);
    
            if ($parentModel) {
                $relationCount = $parentModel->relationNameHere()->count();
                $maxAllowed = 1;
    
                if ($relationCount >= $maxAllowed) {
                    \Flash::error('Max Allowed error here');
                    return;
                }
            } else {
                \Flash::error('ID not found');
                return;
            }
    
            return $this->asExtension('RelationController')->onRelationManageCreate();
        }