How to calculate a field with the API?

How to calculate a field with the API?

paintitblackpaintitblack Posts: 60Questions: 20Answers: 0

Hello everyone,

how is it possible to calculate a non-existing field with the API. E.g. I try to calculate the profit (sellPrice minus purchasePrice).

I tried different ways, but nothing really works.

My current try is this:

Editor::inst( $db, '_stocks' )
->fields(
Field::inst( 'status' ),
Field::inst( 'name' ),
Field::inst( 'profit' ) ->setValue( $row['sellPrice']*$row['purchasePrice'] )
)
->process( $_POST )
->json();

Does anybody has an idea how to solve that issue?

Kind Regards

Answers

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    This is when updating a row? Yes, you'd use a server-side event for this as it provides access to the data submitted for the row being added / edited.

    Allan

  • paintitblackpaintitblack Posts: 60Questions: 20Answers: 0

    This is when I get the Information from the Database and while updating. I tried now this solution:

    Editor::inst( $db, '_stocks' )
    ->fields(
    Field::inst( 'status' ),
    Field::inst( 'name' ),
    Field::inst( 'purchasePrice' ),
    Field::inst( 'quantity' ),
    Field::inst( 'profit' ) ->set( Field::SET_EDIT )
    )
    ->on( 'preEdit', function ( $editor, $values ) {
    $editor
    ->field( 'profit' )
    ->setValue( $_SESSION['purchasePrice']*$_SESSION['quantity'] );
    } )
    ->process( $_POST )
    ->json();

    But I got:
    <b>Notice</b>: Undefined variable: _SESSION in <b>C:...\api.php</b> on line <b>68</b><br />

    How is it possible to the purchasePrice and the quantity for the calculation?

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    That suggests that you haven't started a session I think. Or possibly that there is no purchasePrice or quantity parameter in the session.

    I'm to clear on why you want to use _SESSION parameters given that this data is submitted by the user is it not?

    ->on( 'preEdit', function ( $editor, $values ) {
    $editor
      ->field( 'profit' )
      ->setValue( $values['purchasePrice']*$values['quantity'] );
    } )
    

    Allan

This discussion has been closed.