BLOG

Einen Node mit Bild, Text, Terms, Menüeintrag, Pfad-Alias, Kommentar und einen Block in Drupal 7 programmatisch erstellen

Diesen Quelltext habe ich für das Design Starter Kit geschrieben und wollte das einfach mal zeigen. Ich denke die Kommentare sprechen für sich.

<?php
/**
   * Create a dsk custom node.
   * @see http://drupal.org/node/889058
   */

  // This is a node object. It's very easy to create an array and cast it to
  // an object. See futher below for a print_r() of the full node types.
 
$node = (object) array(
   
// Plain string.
   
'title' => 'Title',
   
// Body text field. Fields are multilingual and for multiple values. So the
    // array is a bit more complictad than in D6.
   
'body' => array(
     
// "und" stands for "undefined" language. No german "und" :) But we
      // use the core constant here anyway.
     
LANGUAGE_NONE => array(
       
// First element.
       
0 => array(
         
// Value is the main text.
         
'value' => 'Body Text',
         
// The Summary if we split it up.
         
'summary' => 'Summary',
         
// Filtered HTML by default.
         
'format' => 'filtered_html',
        )
      ),
    ),
   
// Default types are "page" and "article".
   
'type' => 'article',
   
'language' => LANGUAGE_NONE,
   
// User that creates the node.
   
'uid' => 1,
  );

 
// Prepare the node object to be saved. This sets some defaults and calls
  // hook_node_prepare.
  //  This also sets the nodes uid to the current user. If this is not what
  //  you want remove this function call.
  // @see http://api.drupal.org/api/drupal/modules--node--node.module/function/node_object_prepare/7
 
node_object_prepare($node);


 
/**
   * Add a file.
   */
  // Some filepath on our system. It's the Druplicon! :D
 
$filepath = drupal_realpath('misc/druplicon.png');
 
// Create managed File object and associate with Image field.
 
$file = (object) array(
   
'uid' => 1,
   
'uri' => $filepath,
   
'filemime' => file_get_mimetype($filepath),
   
'status' => 1,
  );

 
// We save the file to the root of the files directory.
 
$file = file_copy($file, 'public://');

 
$node->field_image[LANGUAGE_NONE][0] = (array)$file;

 
/**
   * Add a some terms.
   */
 
$node->field_tags[LANGUAGE_NONE][] = array (
   
'vid' => 1,
   
'tid' => 'autocreate',
   
'name' => 'dsk 1',
   
'vocabulary_machine_name' => 'tags'
 
);

 
$node->field_tags[LANGUAGE_NONE][] = array (
   
'vid' => 1,
   
'tid' => 'autocreate',
   
'name' => 'dsk 2',
   
'vocabulary_machine_name' => 'tags'
 
);

 
// Finally save the node object. The function uses the node object by
  // reference. So we have a nid set after this call and still can work
  // with the node.
 
node_save((object) $node);

 
// Create a menu entry for our new node.
 
$link = array();
 
$link['menu_name'] = 'main-menu';
 
$link['link_title'] = 'Link Title';
 
$link['link_path'] = "node/$node->nid";
 
$link['options']['attributes']['title'] = 'Link description';
 
menu_link_save($link);

 
// Create a path alias for the node.
 
$path['alias'] = 'our-great-dsk-node';
 
$path['source'] = 'node/' . $node->nid;
 
$path['language'] = LANGUAGE_NONE;
 
path_save($path);

 
// Add a comment.
 
$comment = (object) array(
   
'nid' => 1,
   
'cid' => 0,
   
'pid' => 0,
   
'uid' => 1,
   
'mail' => '',
   
'is_anonymous' => 0,
   
'homepage' => '',
   
'status' => COMMENT_PUBLISHED,
   
'subject' => 'dsk subject',
   
'language' => LANGUAGE_NONE,
   
'comment_body' => array(
     
LANGUAGE_NONE => array(
       
0 => array (
         
'value' => 'aaa',
         
'format' => 'filtered_html'
       
)
      )
    ),
  );
 
comment_submit($comment);
 
comment_save($comment);

 
/**
   * Create a custom block.
   * @see http://api.drupal.org/api/drupal/modules--block--block.admin.inc/function/block_add_block_form_submit
   */
  // Base block data for the custom block table. We need the delta.
 
$delta = db_insert('block_custom')
    ->
fields(array(
     
'body' => 'dsk Block',
     
'info' => 'dsk Block info',
     
// Input format.
     
'format' => 'filtered_html',
    ))
    ->
execute();

 
// Insert main data to the block table.
 
$query = db_insert('block')->fields(array('visibility', 'pages', 'custom', 'title', 'module', 'theme', 'status', 'weight', 'delta', 'cache', 'region'));
 
$query->values(array(
   
'visibility' => BLOCK_VISIBILITY_NOTLISTED,
   
'pages' => '',
   
'custom' => BLOCK_CUSTOM_FIXED,
   
'title' => 'dsk Block Title',
   
'module' => 'block',
   
// We only set the block for the bartik theme.
   
'theme' => 'bartik',
   
'status' => 1,
   
'weight' => 0,
   
// Delta value from above.
   
'delta' => $delta,
   
'cache' => DRUPAL_NO_CACHE,
   
'region' => 'sidebar_first',
  ));
 
$query->execute();

 
// Finally clear all caches that our content can shine!
 
cache_clear_all();
?>

Kommentare

Entity-Methoden, 'direkt'

[ http://drupal.org/project... ] Ja, das Entity-Modul kenne ich und habs mal provisorisch aktiviert, setze es aber noch nicht ein. Was die CRUD-Operationen anbelangt: entity_access(), entity_create(), entity_delete(), entity_save(), entity_view() klingen natürlich vielversprechend.

Ich hätte mich in meinem ersten Kommentar etwas deutlicher ausdrücken sollen. Ich meinte eigentlich: Wann setze ich sowas wie bspw. DrupalDefaultEntityController::Foo ein, und wann eine der von Dir oben beschriebenen "gewrappten Verfahren"? Oder habe ich beim DrupalDefaultEntityController auf api.drupal.org etwas falsch verstanden?

Gut, da mit dem Entity-Modul ja ein umfangreiches Werkzeug zur Verfügung steht, erübrigt sich diese Frage auch etwas. Obwohl nicht alle auf Contrib-Modulen aufsetzen wollen (bspw. bei eigenen Modulen und dergleichen).

Entities

Hi,

ganz klar sind das oben Core Geschichten rund um Core Entities und von daher mit Wrappern versorgt. Diese sind wie oben zu sehen erstmal nicht intuitiv, aber dann relativ einfach.

Ich denke für alle anderen Entities muss man den Source des Moduls anschauen, das die Entity mitbringt bzw. das die entity API benutzt wurde.

http://drupal.org/project/entity

Mit dem Modul haben wir dann ein CRUD Interface das uns das Leben einfacher macht.

Super! Nur: Drupal7-Entitäten (Entities)

Super! Danke für diesen immens klaren Beitrag.
Auf ergänzende Weise erhellend oder erhellende Weise ergänzend wäre zudem eine konzise Erklärung gewesen, wie die [neuen] Drupal7-Entitäten (Entities) mit der Erschaffung/Erzeugung solcher Drupal-System-Elemente zusammenhängen. Im Wesentlichen beziehe ich mich auf 'DrupalDefaultEntityController': Wann kann ich wie oben beschrieben verfahren (also relativ praktisch-angewandt-intuitiv), wann stütze ich meinen Code eher direkt auf Entitäten (eher abstrakt-umständlicher)? Existiert hier eine praxiserprobte Anwendungskonvention?