Setting location data programmatically

2.3k Views Asked by At

I'm stuck on a problem that I've researched for several days with no luck and the answers here are usually spot on.

I have custom module code that adds a node from form supplied data:

$edit = array();
$edit['uid'] = $user->id;
$edit['name'] = $user->name;
$edit['status'] = 1;
$edit['taxonomy'] = array($term_id);
$edit['title'] = $Title;
$edit['body'] = $body;

etc...

and then saved with:

node_invoke_nodeapi($edit, $nType);
node_validate($edit);
if ($errors = form_get_errors()) {
      print_r($errors);
}

$node = node_submit($edit);
node_save($node);

This all works perfectly. But I'm trying to add location data to each node based on a supplied (sanitized) zip field.

I have gmap and location modules installed and working. When I add the zip directly using the drupal content editor it all works. Even the views gmap. So i know versions and mods are all correct.

I've used this:

$location = array(
'country' => 'US',
'postal_code' => $zip,
);
$locationID = location_save($location);

and this:

$location['country'] = "US";
$location['postal_code'] = $zip;
$locationID = location_save($location);

with and without the country element. And then in the node data init section (above) this:

$edit->locations[0]['lid'] = $locationID;

or

if($locationID) $edit['field_location'][0]['lid'] = $locationID;

or

if($locationID) $edit['location'][0]['lid'] = $locationID;

But none of this works. The submit will go through ok actually but no location data is saved. And no errors thrown.

Any help with this would be greatly appreciated.

2

There are 2 best solutions below

0
jeff On

I did get this to work, (in case anyone is having the same issue and stumbles upon this), by creating the node first and then adding the location data to the node with:

$locations = array();
$locations[0]['postal_code'] = $zip;

$criteria = array();
$criteria['nid'] = $node->nid;
$criteria['vid'] = $node->vid;
$criteria['genid'] = 'NAME OF NODE TYPE HERE';

location_save_locations( $locations, $criteria );

I guess location_save_locations is the correct way of doing it, not location_save.

0
Augusto On

Following your approach, as exposed by the wider location_save_locations() at line 4, you can update a location with location_save($locations[$key], TRUE, $criteria).

A few notes:

  • location_save return the lid of the saved location, or FALSE if the location is considered "empty."
  • Clean your cache or query the database ( mysql> SELECT * FROM location ORDER BY lid DESC limit 6 ) for a fresh view of the new entity location (ie: node_load data may be cached).

Alternatively, if you are handling an entity with a location field, you may try something cleaner like:

  // Updated the location.
  $node->field_location['und'][0] = $location; 
  // Save the node.
  node_save ($node);