I have a Category element, locations
, which I am trying to update programatically through a Craft 3 plugin that reads data from a CSV.
The locations
category has a Field Layout: latitude
(Number), longitude
(Number), nearbyLocations
(Categories).
I am having trouble updating a locations' nearbyLocations
field. I am inserting an array of Categories into the nearbyLocations
field on the setFieldValues()
call.
A TypeError gets thrown deep in the bowels of Craft:
craft\helpers\StringHelper::toLowerCase() must be of the type string, array given, called in /home/vagrant/code/vendor/craftcms/cms/src/helpers/Db.php on line 448
Below is my code:
$new_nearby_locations is an array of Category elements.
$new_nearby_locations = [];
foreach ($nearby_locations_slugs_from_csv as $nearby_location_slug) {
$nearby_location = Category::find()
->slug($nearby_location_slug)
->one();
if (!is_null($nearby_location)) {
array_push($new_$nearby_locations, $nearby_location);
}
}
Update $category's field values.
$category = Category::find()->slug($slug)->one();
$category->setFieldValues([
'latitude' => $new_latitude, // previously defined
'longitude' => $new_longitude, // previously defined
'nearbyLocations' => $new_nearby_locations
]);
Save the changes
Craft::$app->elements->saveElement($category);
I am suspicious that updating nearbyLocations
by inserting an array of Category elements is wrong. If so, what is the right format?
Or am I doing something else wrong.
Thanks in advance!