Set column default values inner DataTables PHP API

Set column default values inner DataTables PHP API

matschematsche Posts: 14Questions: 6Answers: 0

Hi,
is it possible to set default values (for several columns) in the DataTables PHP API instead of setting this information in the Javascript part?
The PHP API should send this default values to the client which pre-fills the relevant text input fields.

This procedure is already used for dropdown menues.

Cheers,
Matthias

Answers

  • rf1234rf1234 Posts: 2,943Questions: 87Answers: 416

    With get formatters you can return anything to the client:
    https://editor.datatables.net/manual/php/formatters

    Here is an example that uses get and set formatters and validation. You don't want to return passwords to the client. Hence you use a get formatter that returns nothing for example. But you can also put complex conditions within the get formatter and make the conditions dependent on the content of other fields that you retrieve at the same time.

    Field::inst( 'user.password' )
        ->validator( function ( $val, $data, $opts ) {
            return validatorPassword($val);
        } )
        ->getFormatter( function ( $val, $data, $opts ) {
            return '';                   
        } )
        ->setFormatter( function($val, $data, $opts) {
            return password_hash($val, PASSWORD_DEFAULT, ['cost' => 14]);
        }),
    Field::inst( 'user.password AS repeatPassword' )->set( false )
        ->validator( function ( $val, $data, $opts ) {
            return validatorPassword($val, $data['user']);
        } )
        ->getFormatter( function ( $val, $data, $opts ) {
            return '';                   
        } ),
    
    Field::inst( 'cashflow.id AS cashFlowElement' )->set( false )
            ->getFormatter( function($val, $data, $opts) {
                if ( $data['cashflow.id'] > 0 ) {
                    if ($data['variable.currency'] <= '') {
                        return "F" . $data["cashflow.element"] .
                        "/" . $data["cashflow.element_id"] . "/fixed";
                    } else {
                        return "V" . $data["cashflow.element"] .
                        "/" . $data["cashflow.element_id"] . "/variable";
                    }
                }
                return '';
            }),
    
  • matschematsche Posts: 14Questions: 6Answers: 0

    Thanks for your reply. You are right: With the formatters it is possible to return anything to the client. But it is not possible to pre-fill some text input fields in the users DataTables-Editor-Modal. I added a screenshot to avoid comprehension problems.

  • rf1234rf1234 Posts: 2,943Questions: 87Answers: 416

    It is still unclear what you mean: If you are talking about action === 'create' the getFormatters are irrelevant of course. Are you talking about creating a new record?

  • matschematsche Posts: 14Questions: 6Answers: 0

    Sorry, yes. I am talking about creating a new record.

    In class DatatTables\Editor\Field there is the function "options". With this function it is possible to fill radio, select and checkbox input fields. But unfortunately no normal text input fields.

  • rf1234rf1234 Posts: 2,943Questions: 87Answers: 416
    edited December 2019

    Let's assume you are really talking about creating a record and not editing it. In this case Editor will not return anything from the server. But it would be easy for your to prefill the modal fields with default values you are retrieving from the server yourself. This is an example where I retrieve an IBAN from the server and preset the editor form field with it.

    editor
    .on('initCreate', function () {    
        var selected = contractGovDeptTable.row( {selected: true} ); 
        if (selected.any()) {
            var govdeptId = selected.data().govdept_has_user.govdept_id;
            $.ajax({
                type: "POST",
                url: 'actions.php?action=getIban',
                async: true,
                data: { govdeptId: govdeptId },
                dataType: "json",
                success: function (data) {
                    return editor.
                            set( { 'contract.iban': data.iban } );
                }
            });
        }
    })
    

    And a simple query does the job on the server side:

    $dbh->query('SELECT iban FROM govdept WHERE id = :govdeptId');
    $dbh->bind(':govdeptId', filter_input(INPUT_POST,'govdeptId'));
    $row = $dbh->singleAssoc(); // a one-dimensional array is returned SINGLE
    echo json_encode( [ "iban" => getFormatterIban( $row["iban"] ) ] );
    
  • rf1234rf1234 Posts: 2,943Questions: 87Answers: 416

    Now I get it: Yes the Editor options instance which I use very frequently does not help here because you don't have anything like a select list and you don't want any either. Using your own ajax call to preset the form field gives you full flexibility and is not much more coding work than using the Editor options instance I would say. For sure it is the more flexible solution.

  • matschematsche Posts: 14Questions: 6Answers: 0

    Another option is to expand the outgoing JSON object (from api to the customers browser). Example: Adding the json array "custom_default_values".

    {
        "data" : [{
                "DT_RowId" : "row_2",
                "id" : "2",
                "hostgroup_name" : "blub",
                "service_description" : "blub",
                "check_command" : "blub",
                "max_check_attempts" : "2",
                "check_interval" : "15",
                "retry_interval" : "5",
            }, {
                "DT_RowId" : "row_3",
                "id" : "3",
                "hostgroup_name" : "blab",
                "service_description" : "blab",
                "check_command" : "blab",
                "max_check_attempts" : "3",
                "check_interval" : "5",
                "retry_interval" : "5",
            }
        ],
        "files" : [],
        "draw" : 1,
        "recordsTotal" : "2",
        "recordsFiltered" : "2",
        "custom_default_values" : [{
                "max_check_attempts" : "3",
                "check_interval" : "5",
                "retry_interval" : "5"
        }]
    }
    

    A custom javascript function is looking for the "custom_default_values" array and pre-fills the relevant text boxes in the "create new entry" modal.
    With this solution the browser have not to request the api twice.
    But I do not like this solution... I think this should be the task of DataTables themselves.

  • rf1234rf1234 Posts: 2,943Questions: 87Answers: 416
    edited December 2019

    I am not sure whether this should be in the scope of data tables. Also the options instance doesn't preset your fields. It only provides a list of options.
    If you really want to preset your fields with defaults on create I think doing your own ajax call to retrieve the data and then using the api to set the fields in Javascript is the best solution.
    Ja, matsche: Man kann nicht alles haben ... Frohes Fest wünsche ich Dir.
    Roland

This discussion has been closed.