setValue with calculated value from other fields in row

setValue with calculated value from other fields in row

aragusaragus Posts: 5Questions: 3Answers: 1

Hi, I am having trouble with setValue in a row create where it won't allow a function within it. I have been trying:

Field::inst( 'tool_meals.map_iid' )
            ->setValue( function ($val, $data) {
                $mapiid = getMapIid($data['tool_meals']['meal'], $data['tool_meals']['meal_type']);
                return $mapiid;
            }),

However this returns the error: Fatal error: Uncaught ArgumentCountError: Too few arguments to function {closure}(), 0 passed

Which leads me to believe setValue doesn't have the ability to actually set a value based on other values within the row (?).
I tried setFormatter, but that's incorrect as it's a formatter (I am needing to pass a value to the dtb).
Then I tried the below:

$editor->on('preCreate', function ($editor, $values) {
    $mapiid = getMapIid($values['tool_meals']['meal'], $values['tool_meals']['meal_type']);
    echo $values['tool_meals']['meal'].":".$values['tool_meals']['meal_type'].":".$mapiid." || "; //this is for debugging, see below
    $editor->field('tool_meals.map_iid' )->setValue($mapiid);
});

this worked... sort of. It assigned the last value calculated for $mapiid to every row, however the echo reveals that the calculation is occurring. Which leads me to believe there might be some async php going on (?) or a strange reason why the above doesn't apply the correctly calculated $mapiid to the corresponding row.

Any help much appreciated.

Craig

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin
    Answer ✓

    Which leads me to believe setValue doesn't have the ability to actually set a value based on other values within the row (?).

    Correct. setValue does not get any parameters passed to it.

    It assigned the last value calculated for $mapiid to every row, however the echo reveals that the calculation is occurring

    Yup - correct again. The event is the right way to go about this, but preCreate is triggered for all rows, before any of them are written to the database. This allows the code to bail (if needed) before interacting with the db.

    The event you want is validatedCreate (sorry about the naming - preCreate was already used when I added this one - it is relatively new).

    This is where it gets called. Note that you can't use setValue here to set the value to write in the db - you need to write it to the $values array - e.g.:

    $editor->on('validateCreate', function ($e, &$values) {
      // ...
      $values['tool_meals']['map_iid'] = $mapiid;
    });
    

    It isn't idea for such a case I know - It is on my mind to come up with better naming.

    Allan

  • aragusaragus Posts: 5Questions: 3Answers: 1

    Wonderful! Worked thank you.

Sign In or Register to comment.