4

I was hoping someone could shed some light on this issue I'm having. I'm trying to update a relationship field through a plugin, without much success, the entry looks like this:

Entry page

I saw a post on here regarding something similar here: Relation row insertion in DB (plugin) so going from that my code at the moment looks like this:

// The id of the entry i want to attach to the relation
$storeId = $formData['storeId'];

// The entry as shown above
$source = craft()->elements->getElementById($entryId);

foreach($blocks as $blockId => $value)
{
 // The matrix block with the relation
 $matrixBlock = craft()->matrix->getBlockById($blockId);

 // Get the 'stores' field
 $fieldId = $matrixBlock->stores->relatedTo['field'];
 $field = craft()->fields->getFieldById($fieldId);

 // Save the relationship
 craft()->relations->saveRelations($field , $source, array($storeId));

}

$blocks is just an array like: array('1092' => 0) and $value will just be determining whether to set or unset the relation.

When I run the above through a controller, no errors appear but no relation actually takes place on the stores field. Are there any glaring mistakes i'm making? any help would be much appreciated!

Thank you.

7

Figured it out, trying to use the Entry as the source was wrong as the 'stores' relationship field actually belongs to the matrix field.

So by setting the matrix field as the source this is now working just fine!

craft()->relations->saveRelations($field , $matrixBlock, $relations);
3

You can also do it like this. This way is especially useful when creating a new entry with a required relationship field:

    public function createWorldConfig(UserModel $user, EntryModel $world)
    {
        $section    = craft()->sections->getSectionByHandle('yourSectionName');
        $entryTypes = craft()->sections->getEntryTypesByHandle('yourEntryTypeName');
        $entryType  = reset($entryTypes);

        $entry            = new EntryModel();
        $entry->sectionId = $section->id;
        $entry->typeId    = $entryType->id;
        $entry->authorId  = $user->id;
        $entry->postDate  = date('Y-m-d');

        // Build the relationship using and ID array.
        $entry->content->relatedEntryField = array($anotherEntry->id);

        $wasSaved = craft()->entries->saveEntry($entry);

        if (!$wasSaved) {
            return null;
        }

        return $entry;
    }

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.