Search code examples
craftcms

Unable to save an Entry because matrix field is invalid - Craft CMS 2


I'm trying to save an Entry but Craft errors because of an invalid matrix field. The Entry includes a matrix field but I haven't changed it. I'm trying to edit another field. When I save the entry manually from the admin panel, it saves fine without any errors.

I have researched this problem online and a lot of people were recommending that I provide the matrix's ids when saving the entry. However, even then, I still get an error.

In the code below you'll see that I'm trying to save 3 fields:

  • Cover Image
  • Language
  • Tracks

Each of these fields required me to manually save them because they are relations. That's OK, however, as mentioned earlier, the matrix field (named tracks) errors.

Here's my code below

    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = "programmes";
    $entry = $criteria->first([
        "slug" => $programme["slug"]
    ]);

    if ($entry) {
        // Update Entry attributes
        $entry->getContent()->coverImage = $entry->coverImage->ids();
        $entry->getContent()->tracks = $entry->tracks->ids();
        $entry->getContent()->language = $entry->language->ids();

        // Save Entry
        if (!craft()->entries->saveEntry($entry)) {
            return $entry->getErrors();
        }
    }

The error that comes back is the following

Argument 1 passed to Craft\MatrixService::validateBlock() must be an instance of Craft\MatrixBlockModel, string given, called in craft/app/fieldtypes/MatrixFieldType.php on line 451

Solution

  • Including the matrices themselves and not their ids has worked.

    $entry->getContent()->tracks = $entry->tracks->all();