Problem/Motivation
As reported in farmOS chat: https://irc.farmos.org/bot/log/farmOS/2021-05-31#T64064
Attempting to save a WKT value of GEOMETRYCOLLECTION EMPTY results in:
The website encountered an unexpected error. Please try again later.
Error: Call to a member function getX() on null in Drupal\geofield\Plugin\Field\FieldType\GeofieldItem->populateComputedValues() (line 241 of modules/geofield/src/Plugin/Field/FieldType/GeofieldItem.php).
The GEOMETRYCOLLECTION EMPTY WKT is a common occurrence when pulling geometry from an OpenLayers map feature, like we do in farmOS-map: https://github.com/farmOS/farmOS-map#exporting-wkt--geojson
Steps to reproduce
- Create a new Geofield with a standard WKT widget on a node type.
- Create a new node and set the WKT to
GEOMETRYCOLLECTION EMPTY.
- Save the node, and you will see the error.
Proposed resolution
Check $geom->isEmpty() before attempting to populate computed values when saving a Geofield.
Remaining tasks
Provide a patch for the Geofield module.
User interface changes
None.
API changes
None.
Data model changes
None.
Comments
Comment #2
m.stentaFound this old issue: #2672108: Don't save empty geometry WKT
Comment #3
m.stentaI ran into this issue again during farmOS alpha migration testing - where there are some instances of
GEOMETRYCOLLECTION EMPTYsaved in old farmOS databases (most likely a result of #2672108: Don't save empty geometry WKT before I patched it). This causes the migration to fail when it tries to save this in the new D9 Geofield.I then tested replicating this outside of a migration, and it's very easy to. I'm updating the issue description's "Steps to reproduce".
I traced this to the
setValue()method ofDrupal\geofield\Plugin\Field\FieldType\GeofieldItem, where it calls thepopulateComputedValues()method after values are set.The problem is that the
populateComputedValues()method checks to see ifis_empty($geom), but it does NOT check$geom->isEmpty(). This check is used in theGeofieldItem::isEmpty()method itself to avoid saving empty geometries (which coincidentally is what the patch in #2672108: Don't save empty geometry WKT added to the 7.x branch).However, Geofield 8.x-1.x also runs
populateComputedValues(), which executes beforeGeofieldItem::isEmpty(), so we need to have a similar check in that method to prevent populating all the computed values (like centroid lat/lon, bounding box coords, geohash, etc), which can't be populated with an empty geometry.See: https://git.drupalcode.org/project/geofield/-/blob/84373f3aadb58ea36cc28...
The solution is very simple! Just change:
if (!empty($geom)) {to:
if (!empty($geom) && !$geom->isEmpty()) {I am moving this issue to the upstream Geofield issue queue. Stay tuned for a patch...
Comment #4
m.stentaPatch attached.
Comment #6
itamair commentedThanks. Committed into dev and deploying a new 8.x-1.32 release with this.
Comment #7
m.stentaThank you @itamair!