Mit første brugbare modul, som indeholder en rules action, som indsætter data fra en fil i to CCK-felter i en Node.
De store Drupal-nørder straffer mig sikkert max, men glæder mig til at høre om det. Hvis jeg får mega lyst, så forsøger jeg at lægge det op på Drupal.org.
<?php
/**
* @file
* Module for fetching data from a file in the module folder "hardcoded to words.txt".
* TOOD: make this dynamic. This module saves information from a file to a specific
* field or fields in the Drupal data-base.
*/
/**
* Implements rules_action_info.
*
*/
function get_data_rules_action_info() {
return array(
'node_add_data_action' => array(
'type' => 'node',
'label' => t('GN node add data'),
'configurable' => TRUE,
'behavior' => array('changes_property'),
'triggers' => array('node_presave', 'node_insert', 'node_update'),
),
);
}
/**
* Adds data to CCK fields in a node.
*
*/
function node_add_data_action($node, $context = array()) {
//Get word 1 and word 2 from a big file
$filename = 'words.txt';
$filename = drupal_get_path('module', 'get_data').'/'.$filename;
//Read the first two lines
$file = file($filename);
$word1 = $file[0];
$word2 = $file[1];
//Delete the first two lines in the file
$line_count = 2; // Number of lines to remove
$file = array_slice($file, $line_count);
// Write the file
$handle = fopen($filename, 'w');
fwrite($handle, implode('', $file));
fclose($handle);
//Load the latest node ID (nid).
//Source: http://drupal.stackexchange.com/questions/3502/how-do-you-build-a-query-to-get-a-series-of-nodes-and-their-field-values-filtere
$query = db_select('node', 'n')
->fields('n', array('nid'))
->orderBy('created', 'DESC'); //Most recent first. Query paused here.
$query->range(0, 1);
foreach ($query->execute() as $entity_type => $entities) {
foreach ($entities as $entity_id => $entity) {
$nid = $entity;
watchdog('node_add_data_action', "Node ".$nid.' fired from database.');
}
}
$node = node_load($nid); //Load the node
//Set the field values and node title.
$node->field_word_1[$node->language][0]['value'] = $word1;
$node->field_word_2[$node->language][0]['value'] = $word2;
$node->title = $word1." ".$word2;
node_save($node); //Save the node
}
« Last Edit: June 07. 2013, 20:20:43 by admin »
Comments