Saturday, January 23, 2016

get a Drupal 8 node programmatically with console in an external script

get a Drupal 8 node programmatically with console in an external script

Install Drush by download the latest stable release using the code below or browse to github.com/drush-ops/drush/releases:

# wget http://files.drush.org/drush.phar

Test your Drush install:

# php drush.phar core-status

Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH:

# chmod +x drush.phar
# mv drush.phar /usr/local/bin/drush

Enrich the bash startup file with completion and aliases:

# drush init

More detail: http://www.drush.org/en/master/install/

Read Drush help:

# drush help

Run your script:

# vim test.php

<?php
use Drupal\node\Entity\Node;

$node = Node::load(6);

echo '<pre>' . print_r($node, TRUE) . '</pre>';
?>

# drush --root=/www/drupal-8.0.1 --uri=drupal8.cent-exp.local php-script test.php

# drush --root=/www/drupal-8.0.1 --uri=drupal8.cent-exp.local --debug php-script test.php

# drush --root=/www/drupal-8.0.1 --uri=drupal8.cent-exp.local --debug --verbose php-script test.php

To create a new node:

<?php
use Drupal\node\Entity\Node;

$node = Node::create(array(
    'type' => 'page',
    'title' => 'your title',
    'langcode' => 'en',
    'uid' => '1',
    'status' => 1,
    'field_firstname' => 'My First Name',
    #'field_fields' => array(),
));

$node->save();

No comments: