I have a json file with a bunch of id's & associated images.

The id's relate to existing entries in my Craft installation.

I have a Matrix field called Content with a block type called allImages - the allImages block type has a single field called images defined as an Asset field type.

What I would like to do is import the json file & update the existing entries with the images as defined in the json.

I cannot for the life of me figure out how to add images to the Matrix field in code. There are plenty of samples around submitting post variables from a custom form to the saveEntry action.

Any tips would be greatly appreciated

1 Answer 1


This is totally untested but something like this could work (or at least give you some hints)

edit: since I was bored I tested the code.. it works

public function actionImport(){
    $jsonData = // getYouJsonDatasomehow here
    foreach($jsonData as $json){
        $entry = craft()->elements->getElementById($json['id']);
        /** @var \Craft\MatrixBlockModel[] $matrix */
        $matrix = $entry->Content->find();
        /** @var \Craft\MatrixBlockModel $block */
        foreach ($matrix as $block){
            // I pretend there is already the required block for the entry otherwise you have to create it

            if($block->getType()->handle === 'allImages'){
                // long version...
                $attributes = $block->getContent()->getAttributes();
                $attributes['images'] = $json['imageIds'];
                // some other changes if you want... title or whatever

                // short version would be
                $block->getContent()->setAttribute('images', $json['imageIds']);


Since you did not say if the blocks/entries already exist or if the images even exist or if they have to be imported as well I decided to pretend everything is ready to use and your json images contain just an array of ids. If your images contains only local paths you would have to import them first with something like

$arrImages = [];
foreach($json['images'] as $image){
    $path = $image['path'];
    $name = $image['name'];

    $response = craft()->assets->insertFileByLocalPath(

    if($newFildeId = $response->getResponseData()['fileId']){
        $arrImages[] = $newFildeId;

$block->getContent()->setAttribute('images', $arrImages);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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