Adjust values on PHP events

Adjust values on PHP events

Loren MaxwellLoren Maxwell Posts: 387Questions: 94Answers: 10
edited May 2017 in Free community support

I'm trying to write a function that swaps two values to ensure the higher one is always in a specific field (i.e., scores in a game), but while the submission goes through, the values are never actually swapped.

I believe I'm doing it correctly by here: https://editor.datatables.net/manual/php/events
and I've even used $editor->field()->set method as explained here: https://datatables.net/blog/2015-10-02
but nothing works.

Method 1:

    ->on( 'preEdit', function ( $editor, $id, $values ) {
        if ( $values['scored'] < $values['allowed'] ) {
        
            // Swap scores
            $editor->field( 'scored' )->set( $values['allowed'] );
            $editor->field( 'allowed' )->set( $values['scored'] );
        }
    } )

Method 2:

    ->on( 'preEdit', function ( $editor, $id, $values ) {
        if ( $values['scored'] < $values['allowed'] ) {
        
            // Swap scores
            $temp = $values['scored'];
            $values['scored'] = $values['allowed'];
            $values['allowed'] = $temp;
        }
    } )

Method 3:

    ->on( 'preEdit', function ( $editor, $id, $values ) {
        if ( $values['scored'] < $values['allowed'] ) {
        
            // Swap scores
            $temp = $values['scored'];
            $values['scored'] = $values['allowed'];
            $values['allowed'] = $temp;
            $editor->field( 'scored' )->set( $values['scored'] );
            $editor->field( 'allowed' )->set( $values['allowed'] );
        }
    } )

Any thoughts would be appreciated.

This question has an accepted answers - jump to answer

Answers

  • Loren MaxwellLoren Maxwell Posts: 387Questions: 94Answers: 10
    edited May 2017

    Ok, I got it.

    I should have been using setValue instead of set!

    Final code ended up being:

        ->on( 'preEdit', function ( $editor, $id, $values ) {
            if ( $values['scored'] < $values['allowed'] ) {
            
                // Swap scores
                $editor->field( 'scored' )->setValue( $values['allowed'] );
                $editor->field( 'allowed' )->setValue( $values['scored'] );
            }
        } )
    

    Not sure if there's any reason to swap the $values, but it seems to work without it unless there's something else I'm not aware of.

  • allanallan Posts: 61,743Questions: 1Answers: 10,111 Site admin
    Answer ✓

    I think method 2 would also work if you used function ( $editor, $id, &$values ) for the function header. Note the & which means that it is passed by reference. Otherwise PHP creates a new array when you write to it.

    The setValue() method is the correct one to use if you want to use the API to do this. set() is used to mark if the field can be written to the database.

    Allan

This discussion has been closed.