Update fields by PHP

Events happening in the community are now at Drupal community events on www.drupal.org.
dennys's picture

My requirement is to use Rules to modify a field value before save. The rule is field_final (changed) = field_final (unchanged) + field A (changed) - field A (unchanged)

I can use several actions (calculate a value, set a data value) to do above job and it works. But I want to use a custom PHP to do it, is there a sample code to do it?

I need to know how to get unchanged/changed value and how to set changed value, thanks.

Btw, I try use to the follow commands to test but they don't work (I use a hard-code value '123' to test only)
$node->field-final['und'][0]['value'] = 123;
$node->field-final[LANGUAGE_NONE][0]['value'] = 123;

Comments

Write an action!

itangalo's picture

I suggest that you write an custom action for this, instead of executing PHP stored in your database. Executing PHP from the database is slow, risky and difficult to version control – while writing a Rules action is easy and fun. :-)

I sugegst something like this:

<?php
/<strong>
* Implements
hook_rules_action_info().
*/
mymodule_rules_action_info() {
 
$actions = array(
   
'mymodule_action_add_numbers' => array(
     
'parameter' => array(
       
'term1' => array(
         
'type' => 'integer',
         
'label' => t('First integer to add'),
        ),
       
'term2' => array(
         
'type' => 'integer',
         
'label' => t('Second integer to add'),
        ),
      ),
     
'provides' => array(
       
'sum' => array(
         
'type' => 'integer',
         
'label' => t('Sum'),
        ),
      ),
    ),
  );

  return
$actions;
}

/</
strong>
*
Callback for the mymodule_action_add_numbers action.
*/
function
mymodule_action_add_numbers($term1, $term2) {
 
$sum = $term1 + $term2;
  return array(
   
'sum' => $sum,
  );
}
?>

Some more introduction about writing Rules actions can be found here: http://nodeone.se/node/895

Good luck!
//Johan Falk
**
Check out NodeOne's Drupal Learning Library! 200+ screencasts and exercises, for Drupal introduction, advanced configuration, and coding. Creative Commons license!

The video is great, but I

dennys's picture

The video is great, but I download the example from http://drupal.org/project/rules_example, it seems not the same as the video?

Probably more

itangalo's picture

I think the example code contains more than is covered in the videos. I hope it can be useful anyway. (Or are you missing some code, and that is problematic?)

Thanks, I'll try to read the

dennys's picture

Thanks, I'll try to read the code. The video is good, the only problem is the character is not very clear and cannot use copy/paste to test.

Rules

Group organizers

Group categories

Categories

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds: