f3-cortex icon indicating copy to clipboard operation
f3-cortex copied to clipboard

Fluid Mode With Arrays

Open marcus-at-localhost opened this issue 7 months ago • 0 comments

Hi, I'm building a DB in fluid mode from a JSON object. In my model, the only $fieldConf entry is the ID field, any other column is added at runtime. But not the field that is an array. It crashes here: https://github.com/ikkez/f3-cortex/blob/6c735c713e0eb0d562614e7dc1be72de097c71b1/lib/db/cortex.php#L1658

Unfortunately, I can't use a custom setter/getter onset('unknown_fieldname', ...) in the model, since I don't know the name of the field.

Is there an elegant way to set this up to save and retrieve objects in fluid mode?

Edit:

For now I solved it with a custom cortex method that takes in the dataset and creates onset and onget hooks on the fly.

CSV Model

namespace Model;

class Csv extends Base
{
	protected
		$db = 'TemplateDB', // F3 hive key of a valid DB object
		$table = 'csv',     // the DB table to work on
		$fluid = true,
		$fieldConf = [
			'checklistID' => [
				'type' => 'VARCHAR128',
				'index' => true,
				'unique' => true,
				'belongs-to-one' => ['\Model\Checklists', 'checklistID']
			],
		];

	public function setupFluidHooks($fields)
	{
		foreach ((array)$fields as $key => $field) {
			if (is_array($field)) {
				$this->onset($key, function ($self, $val) {
					return json_encode($val);
				});
				$this->onget($key, function ($self, $val) {
					return json_decode($val, true);
				});
			}
		}
	}
}


public function checklistsToDatabase(array $csv, string $checklistID, string $templateID): \Model\Csv
{
	\Model\Csv::setup();

	$csvModel = new \Model\Csv();
	$csvModel->load(['checklistID = ?', $checklistID]);
	$csvModel->setupFluidHooks($csv);
	$csvModel->copyFrom($csv);
	$csvModel->save();
	return $csvModel;
}

This was the least intrusive, but maybe there is a better way?

marcus-at-localhost avatar Jul 02 '24 10:07 marcus-at-localhost