3

I'm following the Element Actions example from the official Craft docs.

I've defined an Artist entry type, and have defined an entries field on my Assets to relate an Artist to each Asset. To avoid assigning Artists one-by-one, I'm attempting to create a Element Action so that I can select multiple Assets in the Asset Index and relate them to an Artist entry in bulk.

I'm almost there. I can select an Artist (entry) from a dropdown I've created on the Asset Index page in the CP, but I'm struggling to save the relationship in the performAction function within my plugin. I assume I should be using the relations service saveRelations() method to accomplish this?

I'm new to Craft and not sure where I'm going wrong. I'm sure the fact that I'm doing this within an ElementAction is irrelevant, it's just that I'm doing something wrong while trying to save the relation. Here's the relevant part of the code as it currently stands:

public function performAction(ElementCriteriaModel $criteria)
{
    // Get the selected artist
    $artistId = $this->getParams()->artist;
    $artist = craft()->entries->getEntryById($artistId);

    // Make sure it's a valid one
    if (!$artist)
    {
        $this->setMessage(Craft::t('The selected artist could not be found.'));
        return false;
    }

    // Assign the artist to the selected elements
    $assets = $criteria->find();

    foreach ($assets as $asset)
    {
        $artistFieldModel = craft()->fields->getFieldByHandle('artist');
        craft()->relations->saveRelations($artistFieldModel, $asset, $artistId);
    }

    // Success!
    $this->setMessage(Craft::t('Artist successfully assigned.'));
    return true;
}

Any pointers gratefully appreciated.

2

So it seems what I was doing wrong was passing in a single $artistId rather than an array. With the change shown below it works as expected:

foreach ($assets as $asset)
{
    $artistFieldModel = craft()->fields->getFieldByHandle('artist');
    craft()->relations->saveRelations($artistFieldModel, $asset, [$artistId]);
}

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.