I have a model X that has a many-to-many relationship with the Word model. In the controller of the X model, I have a custom form widget which submits a wordId via ajax, and save that relationship:
public function onAddWord()
{
$wordId = post($this->getFieldName());
if (is_numeric($wordId)) {
$this->model->words()->syncWithoutDetaching([$wordId]);
} else {
// if the word that user selected, was not in the list, wordId does not contain any ID,
// but it's the actual new word the needs to be added to the words table
$newWord = WordModel::create(
[
'word' => $wordId,
'lang_id' => 2,
]
);
$this->model->words()->attach($newWord->id);
}
// refresh the relation manager list
return $this->controller->relationRefresh('related_words');
}
This works perfectly when I am updating model X. But when I am in the create
page of model X, saving the above relations fails, because model X does not exist yet. I tried to use differed binding, but it didn't work:
public function onAddWord()
{
$sessionKey = $this->controller->formGetSessionKey();
$wordId = post($this->getFieldName());
if (is_numeric($wordId)) {
$this->model->words()->syncWithoutDetaching([$wordId]);
} else {
// if the word that user selected, was not in the list, wordId does not contain any ID,
// but it's the actual new word the needs to be added to the words table
$newWord = WordModel::create(
[
'word' => $wordId,
'lang_id' => 2,
], $sessionKey
);
$this->model->words()->attach($newWord->id, $sessionKey);
}
// refresh the relation manager list
return $this->controller->relationRefresh('related_words');
}
How can I make this work?