Jump to content

Recommended Posts

I have a custom module that is displaying events fed by a JSON feed. The problem I am having is when the JSON feed is updated (for example a title name is updated) it creates a new event instead of updating the original event. 

 

I am new to php and what I have tried is not working. Any help would be appreciated.

   
    $category_matches = taxonomy_get_term_by_name('Dicate', 'events');
    $category = array_pop($category_matches);
    if (!$category) {
      watchdog('rad', 'no dicate  found', 'error');
      return;
    }
    $feed_url = 'https://las/rad-forms/api/v1/getfeed';
    $options = array('headers' => array());
    $options['headers']['Authorization'] = 'Basic ' . base64_encode('rad:6WLUMwFgAjdOQPazZ7K0yxBRxklVAEWZaaaAcQuzQh4V7v7ZWP2cHl/BtCdhlj1ngacrhA==');
    $response = drupal_http_request($feed_url, $options);
    $response_data = $response->data;
    $json_data = json_decode($response_data);
	
    $feed_data = $json_data->dicate;
    if (!count($feed_data)) {
      watchdog('rad_feed', 'bad feed request - ' . print_r($response, TRUE));
    }
    foreach ($feed_data as $event) {
      // make sure it doesn't already exist
      $event_nids = FALSE;
      $query = new EntityFieldQuery(); 
      $query->entityCondition('entity_type', 'node') 
        ->entityCondition('bundle', 'event')
        ->propertyCondition('title', $event->{'draftTitle'}, '=')
        ->fieldCondition('field_event_dates', 'value', strtotime($event->startTime) , '=')
        ->range(0, 1) //($start, $length)
        ->addMetaData('account', user_load(1)); // Run the query as user 1.
		
      $result = $query->execute();
      if (isset($result['node'])) { // existing event found, just count it
        $counter_existing++;
	//ADDED TO UPDATE
	$event->{'draftTitle'} = $node->title;
        $node->field_event_category[$node->language][0]['tid'] = $category->tid;
        $node->field_event_dates[$node->language][0]['value'] = strtotime($event->startTime);
        node_save($node);
      }
      else { // event doesn't exist; create new one
        $counter_new++;
        $node = new stdClass();
        $node->type = 'event';
        $node->language = LANGUAGE_NONE;
        node_object_prepare($node);
        $node->status = 1;
        $node->promote = 0;
        $node->sticky = 0;
        $node->comment = 0;
        $node->uid = 1;
        $node->title = $event->{'draftTitle'};
        $node->field_event_category[$node->language][0]['tid'] = $category->tid;
        $node->field_event_dates[$node->language][0]['value'] = strtotime($event->startTime);
        node_save($node);
      }
    }
    variable_set('rad_feed_last_run', $time);
    watchdog('rad_feed', 'ran feed update: ' . $counter_new . ' new events; found ' . $counter_existing . ' existing events');
 
}

JSON Example:

"dictate":[{"form_id" : "1234", "draftTitle" : "Test123", "startTime" : "Wed, Jan 19, 2017"}]
Link to comment
https://forums.phpfreaks.com/topic/302971-update-node-when-data-is-changed/
Share on other sites

The one containing the code that isn't working properly, yes.

 

Thank you for that update. I have added the following lines of code to that if statement. Any advice is appreciated

 

$node = new stdClass();
$node->language = LANGUAGE_NONE;
node_object_prepare($node);
$node->uid = 1;
Edited by Raxter

If you're updating an existing record, wouldn't setting $node to the value of $result['node'] (in order to get the existing event record) make more sense than creating a new standard object - like you do when the event doesn't exist?

Edited by maxxd

If you're updating an existing record, wouldn't setting $node to the value of $result['node'] (in order to get the existing event record) make more sense than creating a new standard object - like you do when the event doesn't exist?

 

Thanks for the input. 

 

Obviously I am new to php and that is why I am here. :)

 

If the event already exists then I am trying to just update it. If it does not exist then I need to create it. The module currently does create a new one. It wont do any updates, I will create a new one with the change.

Everybody here was new to PHP at one point, so that's not a problem!

 

Please post your code as it is now. I think I may be a bit confused - did you add the code from reply #5 to the conditional branch where the event was found, or where it wasn't? The impression that I got before I posted my reply was that you'd added those lines to the 'true' branch of the conditional, and that may not be the case at this point.

 

Basically, I don't see where you're getting the $node variable from if the event is found in the database. It may be Drupal thing (not terribly familiar with Drupal), but it seems to me that the record you want is stored in $result['node'], not in $node.

Everybody here was new to PHP at one point, so that's not a problem!

 

Please post your code as it is now. I think I may be a bit confused - did you add the code from reply #5 to the conditional branch where the event was found, or where it wasn't? The impression that I got before I posted my reply was that you'd added those lines to the 'true' branch of the conditional, and that may not be the case at this point.

 

Basically, I don't see where you're getting the $node variable from if the event is found in the database. It may be Drupal thing (not terribly familiar with Drupal), but it seems to me that the record you want is stored in $result['node'], not in $node.

 

Thanks for the info and the help! I feel like I have been looking at this for weeks! I added the code to initialize the node when it is found (per the reply from another poster). Here is the code I have:

$category_matches = taxonomy_get_term_by_name('Dicate', 'events');
$category = array_pop($category_matches);
if (!$category) {
watchdog('rad', 'no dicate found', 'error');
return;
}
$feed_url = 'https://las/rad-forms/api/v1/getfeed';
$options = array('headers' => array());
$options['headers']['Authorization'] = 'Basic ' . base64_encode('rad:6WLUMwFgAjdOQPazZ7K0yxBRxklVAEWZaaaAcQuzQh4V7v7ZWP2cHl/BtCdhlj1ngacrhA==');
$response = drupal_http_request($feed_url, $options);
$response_data = $response->data;
$json_data = json_decode($response_data);
    
$feed_data = $json_data->dicate;
if (!count($feed_data)) {
watchdog('rad_feed', 'bad feed request - ' . print_r($response, TRUE));
}
foreach ($feed_data as $event) {
// make sure it doesn't already exist
$event_nids = FALSE;
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node') 
->entityCondition('bundle', 'event')
->propertyCondition('title', $event->{'draftTitle'}, '=')
->fieldCondition('field_event_dates', 'value', strtotime($event->startTime) , '=')
->range(0, 1) //($start, $length)
->addMetaData('account', user_load(1)); // Run the query as user 1.
        
$result = $query->execute();

if (isset($result['node'])) { // existing event found, just count it

     $counter_existing++;
    //ADDED TO UPDATE
   $node = new stdClass();
   $node->title = $event->{'draftTitle'};
   $node->field_event_category[$node->language][0]['tid'] = $category->tid;
   $node->field_event_dates[$node->language][0]['value'] = strtotime($event->startTime);
node_save($node);
}
else { // event doesn't exist; create new one
$counter_new++;
$node = new stdClass();
$node->type = 'event';
$node->language = LANGUAGE_NONE;
node_object_prepare($node);
$node->status = 1;
$node->promote = 0;
$node->sticky = 0;
$node->comment = 0;
$node->uid = 1;
$node->title = $event->{'draftTitle'};
$node->field_event_category[$node->language][0]['tid'] = $category->tid;
$node->field_event_dates[$node->language][0]['value'] = strtotime($event->startTime);
node_save($node);
}
}
variable_set('rad_feed_last_run', $time);
watchdog('rad_feed', 'ran feed update: ' . $counter_new . ' new events; found ' . $counter_existing . ' existing events');

}

Right beneath the live that reads

//ADDED TO UPDATE

change

$node = new stdClass();

to

$node = $result['node'];

and see what happens.

 

I'm assuming you know that the code presents a possibility for race condition issues, so you may want to make sure that either save_node() or EntityFieldQuery have some sort of safeguard in place. Again, I know very little about Drupal.

 

Also, I'm not sure if it's just how the code pasted in or not, but formatting your code properly makes it much easier to read - I actually couldn't find where you'd instantiated $event in the foreach() loop until I'd copied the code, pasted it into my IDE, and formatted it. If it is just a by-product of pasting the existing code into the browser, then please disregard all of this last little bit.

Right beneath the live that reads

//ADDED TO UPDATE

change

$node = new stdClass();

to

$node = $result['node'];

and see what happens.

 

I'm assuming you know that the code presents a possibility for race condition issues, so you may want to make sure that either save_node() or EntityFieldQuery have some sort of safeguard in place. Again, I know very little about Drupal.

 

Also, I'm not sure if it's just how the code pasted in or not, but formatting your code properly makes it much easier to read - I actually couldn't find where you'd instantiated $event in the foreach() loop until I'd copied the code, pasted it into my IDE, and formatted it. If it is just a by-product of pasting the existing code into the browser, then please disregard all of this last little bit.

 

I apologize for the code formatting. It is from copying and pasting. It isn't like that in my module. I updated the code per your suggestion. I made a change to the title and startdate value and it did not update values. However, it will create a new event with the new values. 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.