Drupal 8.5.2编程保存地理字段报错:geofield_compute_values()未定义
geofield_compute_values() Undefined Error in Drupal 8.5.2 Hey there! Let's break down why you're hitting that "undefined function" error and how to fix it when working with Geofield programmatically in Drupal 8.5.2.
Why the error happens
The geofield_compute_values() function you're referencing likely doesn't exist in the version of the Geofield module compatible with Drupal 8.5.2. Drupal 8.5.x is an older release, and the Geofield module's API evolved over time—this function was probably added in a later version that doesn't support your Drupal core version. The good news is the module works fine in the backend because it uses internal methods that are available in your installed version.
Solutions to try
1. Manually construct Geofield values (no function needed)
Instead of relying on that missing function, you can directly format the coordinates into the structure Geofield expects. Here's a practical example for saving a point to a Geofield field on a node:
// Assume you have a node object $node and your Geofield field is named 'field_location' $latitude = 40.7128; $longitude = -74.0060; // Option 1: Use GeoJSON format (recommended) $node->field_location->value = json_encode([ 'type' => 'Point', 'coordinates' => [$longitude, $latitude], // Note: GeoJSON uses [lon, lat] order ]); // Option 2: Use WKT (Well-Known Text) format // $node->field_location->value = "POINT($longitude $latitude)"; // Save the node $node->save();
2. Use Geofield's internal methods
If you prefer using module-provided logic, check the GeofieldItem class (part of the Geofield module) for helper methods. For example, you can use its static methods to generate valid values:
use Drupal\geofield\Plugin\Field\FieldType\GeofieldItem; $latitude = 40.7128; $longitude = -74.0060; // Generate a GeoJSON string using the module's helper $geojson = GeofieldItem::generateGeoJson('Point', [$longitude, $latitude]); $node->field_location->value = $geojson; $node->save();
3. Verify your Geofield module version
Double-check the Geofield version you installed via Composer. Ensure it's compatible with Drupal 8.5.2—older versions of Geofield (like 1.x releases) support Drupal 8.5.x, and they don't include geofield_compute_values(). If you want to use that specific function, you'd need to upgrade your Drupal core to a newer version (like 8.9.x) that supports a Geofield version where this function was added. Just make sure to test upgrades thoroughly to avoid breaking existing functionality.
内容的提问来源于stack exchange,提问作者Jimmie Johansson

