1

I'm using the saveRelations method in the RelationsService to save entry relationships in a plugin I'm working on. Everything is working as expected, however, saveRelations is returning null on success, which seems odd.

Here is a portion of the code I'm working with:

public function addCategoryRelation(CategoryModel $category, EntryModel $entry)
{
    $field        = $craft()->fields->getFieldByHandle('handle');
    $handle       = $field->handle;
    $relations    = $category->$handle;
    $relationsIds = [];

    /**
     * Get the ids for the relations.
     */
    foreach ($relations as $entry) {
        $relationsIds[] = $entry->id;
    }

    if (!in_array($entry->id, array_values($relationsIds))) {
        $relationsIds[] = $entry->id;
        return craft()->relations->saveRelations($field, $category, $relationsIds);
    } else {
        return [
            'error' => 'Entry already saved.',
        ];
    }
}
1

You're getting null back simply because the saveRelations() method doesn't actually return anything.

If you need to return true from addCategoryRelation if the relations are successfully saved, or possibly an error message (or false) if they aren't, you can consider wrapping the call to saveRelations() in a try/catch block – something like this should work:

public function addCategoryRelation(CategoryModel $category, EntryModel $entry)
{
    ...
    if (in_array($entry->id, array_values($relationsIds))) {
        return [
            'error' => 'Entry already saved.',
        ];
    }
    try {
        $relationsIds[] = $entry->id;
        return craft()->relations->saveRelations($field, $category, $relationsIds);
    } catch (\Exception $e) {
        // Something went wrong – return `false` or an error message, log the exception?
        return false;
    }
    return true;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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