1

I am trying to create a node programmatically from the data(JSON) sent by my front-end template.

<input id="title" name="title" type="text" >
<input id="body" name="body" type="text">
<input type="file" name="pic" id ="pic1" accept="image/*">

^^ This is my front end html

jQuery(document).ready(function(){
jQuery("#save").click(function(){
    //alert("The paragraph was clicked.");
  var postData =  [{
      "content-type" : "article",
      "title": jQuery("#title").val(),
      "body" : jQuery("#body").val(), 
      "pic1" : jQuery("#pic1").val(),
  }];
        jQuery.ajax({
            type: "POST",
            dataType: "application/json; charset=utf-8",
            url: "my-module/create-artcle/", //This is the menu hook I created
            data: {'article': postData},
            success:function(data){
            //if(data.status === "success"){
              alert(data);
            //  window.location = "/user";
            //}
          }
    });
  });

});

^^^ This is my json.

This data is sent to the hook_menu I created, which triggers a callback function to create the node. here is the code for that.

function create_article(){
  global $user;

  if(isset($_POST['article'])) {
      $json = $_POST['article'];
      $decodedData = json_decode($json, true);

      $contentType = $decodedData[0]["content-type"];
      $title = $decodedData[0]["title"];
      $body= $decodedData[0]["body"];
      $image1 = $decodedData[0]["pic1"]; 

       //Create a article
       $node = new stdClass();

       //Set values to fields
       $node->type = $contentType;
       $node->title = $title;
       $node->body[LANGUAGE_NONE][0]['value'] = $body;

       node_object_prepare($node);
       $node->language = LANGUAGE_NONE; 
       $node->uid = $user->uid;
       $node->status = 1; 

       $node = node_submit($node); 
       node_save($node);
  }
}

So far I am getting my code to work except saving the image, because I'm seriously confused in saving an image to my node. The value that I get from front-end is simply the name of the image. my question is : can I save an image to the node I am creating with what I am getting from front-end ? If so I am confused with this reference https://www.drupal.org/node/201594

could any one guide me to extend this code to save my image.. $image1 this variable contains the image name.

Thank you.

1 Answer 1

0

The best way to achieve that is through Services module

In your case you have to post the image itself and use the file data in node object as a value for the field see that snippet:

  //$file_array is the result from saving the file
  //assuming you have the field name is image
  $file_array = api_save_file($_POST['image'], $title);
  $node->field_image[LANGUAGE_NONE][0]['value'] = $file_array

Note that you have to save the image base64 encoded like

//save base64 images as files 
//@return object file object

 function api_save_file($file, $name, $entity_type = 'node', $entity_id = 0){
$data = base64_decode($file);    

$finfo = finfo_open();
$mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
finfo_close($finfo);
// get file type png. jpg
$ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
$file_name = str_replace(' ', '-', $name);

$file = file_save_data($data, 'public://'.$entity.'/'.$file_name.'.'.$ext, FILE_EXISTS_REPLACE);
file_usage_add($file, 'file', $entity_type, $entity_id);

return array(
    'fid' => $file->fid,
    'width' => 800,
    'height' => 600,
    'display' => 1,
    'alt' => $name,
    'title' => $name
);

}

2
  • Hi! I will try this out and vote your answer. Thank you. Commented Sep 1, 2015 at 3:16
  • Don't forget to remove all file usage records with id = 0 Commented Sep 1, 2015 at 7:32

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.