Save on-the-fly created form-inputs to custom database


I have a form in which the user can add some input fields by clicking a button. Those fields can be seen as a group, one group looks like this:

[Button: Add Car] > click > those three inputs get added

<input name="car[n][brand]" type="text" value="" >
<input name="car[n][color]" type="text" value="" >
<input name="car[n][price]" type="text" value="" >

[n] gets dynamically set on creation, so each group has its unique ID.

Now I want to store those groups in a custom table via a custom hook, but only the last group gets saved. Why?

And: why does $hook->getValue('car'); return nothing?

custom Hook:

$cars = $modx->newObject('myCars');

foreach($_POST['car'] as $car) {

	$cars->set('car_brand', $car['brand']);
	$cars->set('car_color', $car['color']);
	$cars->set('car_price', $car['price']);

return true;

You have to move the line with newObject inside the loop to create multiple new objects.

foreach($_POST['car'] as $car) {
	$cars = $modx->newObject('myCars'); //new inside the loop
	$cars->set('car_brand', $car['brand']);
	$cars->set('car_color', $car['color']);
	$cars->set('car_price', $car['price']);

thank you @halftrainedharry – works perfectly.

@halftrainedharry you wanna help me get those items, too?

Those cars are separated from extras. So I have two custom tables and I would like to combine the output. Therefore I have stored the car-ID in each extra.

This here works somewhat, but adds up the extras pretty quirky:

minified version of my snippet:

$cars = $modx->getCollection('myCars');

foreach($cars as $car) {

	$q = $modx->newQuery('carExtras');
		'car_id' => $car->get('id')
	$carExtras = $modx->getCollection('carExtras', $q);

	foreach ($carExtras as $carExtra) {
		$extraItem .= $carExtra->get('extra_something');

	$output .= other stuff;
	$output .= $doc->get('category').$extraItem;

return $output;

If you have a relationship defined in your schema between “myCars” and “carExtras”, then you should be able to use getMany instead of the second getCollection call (and maybe use getCollectionGraph to reduce the number of database queries).

Yes, I have defined a relationship, @halftrainedharry. Will look into getMany, thanks for the hint.

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.