what is the best way for calculate diferent values from fields in a collection and punt into result field.
For example for multiply quantity and price in a collection row.
It's posible to make a new Fieldtype called calculate and define som rules in options, to choose diferent fields and apply aritmethic rules.
I think this doesn't exist yet, but could be implemented.
Maybe specifying a function name in a Calculate field, that works by calling a specific php function that takes the form data in a file in the config directory. Something like functions.php.
you can achieve that by listening to the collections.save.before event.
so, create config/bootstrap.php and add the following snippet:
<?php
$app->on('collections.save.before.{$collectionName}', function($name, &$entry, $isUpdate) {
if (isset($entry['a'], $entry['b'])) {
$entry['calculatedField'] = $entry['a'] * $entry['b'];
}
});
Does this require that the target field of the calculation exists in the collection for this to work?
@mpartipilo no. in that case it won't be available in the admin backend ui, but you get it in your api query result-set. you can also use the field to query, sort etc via the api.
@aheinze i try your code but nothing happens.
I create a collection named calculation
and create 3 fields
price
quantity
calculated
this is my config/bootstrap.php
```
$collectionName = "calculation";
$app->on('collections.save.before.{$collectionName}', function($name, $entry, $isUpdate) {
if (isset($entry['price'], $entry['quantity'])) {
$entry['calculated'] = $entry['price'] * $entry['quantity'];
}
});
I make a simple debug to capture values and all is ok i read entries price and quantity, and the multiplications is stored in txt file. But not stored in database.
$collectionName = "calculation";
$app->on('collections.save.before.calculation', function($name, $entry, $isUpdate) {
if (isset($entry['price'], $entry['quantity'])) {
$fichero = __DIR__ . '/debugcalculator.txt';
$entry['calculated'] = $entry['price'] * $entry['quantity'];
file_put_contents($fichero, $entry['calculated']);
}
});
````
$app->on('collections.save.before.calculation', function($name, &$entry, $isUpdate) {
if (isset($entry['price'], $entry['quantity'])) {
$entry['calculated'] = $entry['price'] * $entry['quantity'];
}
});
&$entry does the trick
Thanks a lot!!