2

I found this previous question, but I'm struggling to adapt it to what I want to accomplish.

How can you take a file/image that is attached to one node, and move it to another or create a new node and attach it there?

1

I can't recommend this as finished code, and I certainly can't vouch for it's safety/usability, but I was able to accomplish this with:

<?php
function testymod_node_presave($node){

    if($node->type == 'image_gallery'){
        $nl = $node->language;//to shorten lines

        if(isset($node->field_image,$node->field_image[$nl],$node->field_image[$nl][1])){
            //Leave the first file, but move all the rest to indidivual nodes of their own
            for($i=1;$i<count($node->field_image[$nl]);$i++){
                $tmpNode = new stdClass();//Create a node object

                $tmpNode->uid = $node->uid;    

                //Use the current node data                    
                $tmpNode->type = $node->type;
                $tmpNode->title = $node->title;
                $tmpNode->language = $nl;

                //Set some defaults
                node_object_prepare($tmpNode);

                //Add the file
                $tmpNode->field_image[$nl][0] = (array) unserialize(serialize($node->field_image[$nl][$i]));//Only way I know to do a deep clone

                $tmpNode = node_submit($tmpNode); // prep for saving

                node_save($tmpNode); // Should have an nid now
            }
            //Remove attachments from the original
            $node->field_image[$nl] = array_slice($node->field_image[$nl], 0,1);
        }

    }
}
?>

I may try to develop this into a usable module with a switch in the content type to enable it for a given content type, but I'd need to figure out how to automatically copy any relevant fields over as well.

| 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.