Saturday, May 25, 2019

Create node programatically with translation content in Drupal 8

            $node = Node::create(array(
                'type' => 'news',
                'langcode' => 'en',
                'uid' => '1',
                'status' => 1,
                'title' => $node['Title'],
                'field_description' =>array(0=>array('value'=>$node['PublishingPageContent'],'summary'=>$node['Comments'],'format'=>'full_html')),
                'field_news_type' =>121
         ));

             $node->save();
             $node_fr = $node->addTranslation('fr');
             $node_fr->title = 'frenchtitle';
             $node_fr->body->summary = 'summary';
             $node_fr->body->value = 'frenchcontent';
             $node_fr->body->format = 'full_html';

            //Saving the node
             $node_fr->save();   

Create node programtically with image content in Drupal 8

              $file_image = '/apps/sites/test.jpg';
                $file_content = file_get_contents($file_image);
                $directory = 'public://Migimage/';
                file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
           
                $file_image = file_save_data($file_content, $directory.basename($src),  FILE_EXISTS_REPLACE);
                $fid = $file_image->id();


    $node = Node::create(array(
                'type' => 'news',
                'langcode' => 'en',
                'uid' => '1',
                'status' => 1,
                'title' => $node['Title'],
                'body' =>array(0=>array('value'=>$node['valuecontent'],'summary'=>$node['summary'],'format'=>'full_html')),
                'field_test_type' => '233',
                'field_image' => array(
                                  'target_id' => $fid,
                                  'alt' => 'Sample',
                                  'title' => 'Sample File'
                                  )
             ));