1

Users in my project have a Favourite Entries field. In my plugin I want to check whether a specific Entry is present in that field for that user. I'm passing the Entry ID to look for. I am not interested in getting the Entry itself - I just want to check to see if it's already in the Favourite Entries field or not.

I'd hoped that this would work:

if( $user->favouriteEntriesField->id($searchingForThisEntryId)->total() === 0 ) {
    ... doesn't contain the Entry yet ...
}

But it doesn't work ( Object of class Craft\ElementCriteriaModel could not be converted to string )

[edit]

A working solution is to loop through everything:

foreach ($user->favouriteEntriesField as $favouriteEntry) {
    MyPlugin::log("ID of loop iterations Favourite Entry: $favouriteEntry->id", LogLevel::Info);

    if($favouriteEntry->id === $searchingForThisEntryId) {
        craft()->userSession->setError(Craft::t('This document is already favourited.'));

        $this->documentFavourited = "yes";
    }
}
1

You can also use find() method or better first() method.

first() returns EntryModel or null.

if( $user->favouriteEntriesField->first(['id' => $searchingForThisEntryId]) ) {
    craft()->userSession->setError(Craft::t('This document is already favourited.'));
}

Here we take advantage of baseModel's setAttributes() method that is being used by first() method.

/**
 *   @var searchingForThisEntry EntryModel
 */

if( $user->favouriteEntriesField->first($searchingForThisEntry) ) {
    craft()->userSession->setError(Craft::t('This document is already favourited.'));
}
| improve this answer | |
3

You can avoid looping by getting an array of the IDs of the favourite entries, then check to see if the specific Entry ID is in the array.

$favouriteEntryIds = $user->favouriteEntriesField->ids();
if( in_array($searchingForThisEntryId, $favouriteEntryIds) ) {
    ... the Entry has already been favourited ...
}
| 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.