Newly Created Realtionship Modal Id

Hello,

I am having a Relation manager in a controller. I am wondering how to get the newly created id in

onRelationManageCreate

Scenario:
After creating a model record i want to display that record in a popup immediatly after it is created.
But i am struggling to get the id of the newly created relation model.

thank you.

you can listen to the event attached to the relation in the model. Example:

YourModel::extend(function ($model) {

   $model->bindEvent('model.relation.attach', function (string $relationName, array $ids, array $attributes) {
   // check here the value of  $relationName and grab the ids
  }
})

@chris thank you. Please excuse my ignorance i am very new to Octobercms.

Can you explain this snippet?

OC triggers this vent when a new relationship is added. So you can listen to the event in your boot plugin method.

https://octobercms.com/docs/api/model/relation/attach

1 Like

@chris thanks alot

i did it like this

public function boot()
{
    CmsBlock::extend(function ($model) {
        $model->bindEvent('model.relation.attach', function (string $relationName, array $ids, array $attributes) {
            // check here the value of  $relationName and grab the ids
            trace_log("New relation {$relationName} was created", $ids);
        });
    });
}

The parent model Model is belongsToMany to CmsBlock
However still not listeneing to the event. is there anythign i am doing wrong?

I guess it should be the other way around then:

public function boot()
{
    ParentModel::extend(function ($model) {
        $model->bindEvent('model.relation.attach', function (string $relationName, array $ids, array $attributes) {
            // check here the value of  $relationName and grab the ids
            trace_log("New relation {$relationName} was created", $ids);
            if ($relationName == 'nameOfYourRelationship' // for example, blocks) { 
              // grab the new id here
            }
        });
    });
}
2 Likes

@chris thanks alot. it works. Can i ask how you sent it to javascript responce. e.g: when the relation is created the ajax sent some details of the newly created realtion without the id. this way we get the id but my question is that how can i get this id in the javascript responce?

at the moment i am getting only a flash message.

I overwrite the _form_manage.htm to

        <?= Form::ajax('onRelationManageCreate', [
            'sessionKey' => $newSessionKey,
            'data-popup-load-indicator' => true,
            'data-request-success' => "$.popup({ handler: 'onShowBlockList', extraData: { block_id: some_id  } });",
        ]) ?>

i want to pass the newly created id to a custom handler onShowBlockList.
thanks alot for helping :slight_smile:

1 Like