Add to structure

I always use the popular addToStructure() function from Sonja and it’s working great. However, I have seen that there are a lot of other structure methods. Can I also work with them instead of the custom function? Has anybody a simple example how to add a entry to a structure in PHP with this methods?

I always use:

function addToStructure($page, $field, $data = array()){
		$fieldData = page($page)->$field()->yaml();
		$fieldData[] = $data;
		$fieldData = yaml::encode($fieldData);
		try {
			page($page)->update(array($field => $fieldData));
		} catch(Exception $e) {
			return $e->getMessage();

Can this replaced with: $structure->add() | Kirby and maybe how?

You could, but you would have to create a new StructureObject, then add that to the structure collection, then use toArray() to convert the collection to an array and Data::encode that-

Ah ok, so I think it’s better to simply use your awesome function! BTW: maybe a cookbook article for future how to deal with structure fields data (add, remove, append, prepend, findBy, etc.) :wink:

1 Like