How can I alter the data editor sends to the server prior to the edits being saved to the database?

How can I alter the data editor sends to the server prior to the edits being saved to the database?

JenskhJenskh Posts: 2Questions: 1Answers: 0
edited January 2020 in Editor

My table contains basic user names and addresses. I want to capture the submitted "edits" from the client and validate the addresses on the server side using a service from the USPS. The data returned from that service is often different than what was submitted (zip codes are provided in 9-digit format, words like "street" and "lane" are abbreviated, etc.). Within the global validator I can ensure certain rules were followed and, while I can edit the $data array passed to the validate routine, it appears the validator's $data is a copy, so my editing it doesn't affect what is saved to the database (the edit is succesful, but it saved what the user entered, not what I changed in the validator).
Is a global validator the place to do this or is there a better option? I didn't find any examples where the to-be-edited data is altered prior to the actual database update. I am coding in PHP.
Lastly, I'm a hobbyist developer, so I would appreciate your patience if I'm missing something basic.

Here is my validator:

...

->validator( function ( $editor, $action, $data ) {
    if ( $action === Editor::ACTION_EDIT ) {
        $key=array_keys($data['data'])[0];
        $mydata=&$data['data'][$key]['tblcontacts'];
        $first_name=$mydata['first_name'];
        $last_name=$mydata['last_name'];
        $business_name=$mydata['business'];
        $add1=&$mydata['address1'];
        $add2=&$mydata['address2'];
        $city=&$mydata['city'];
        $state=&$mydata['state'];
        $zip=&$mydata['zip'];
        $email=$mydata['email'];
        $phone=&$mydata['phone'];

        $error_message='';
        // address validation routines take arguments by reference and update 
        // those arguments based on USPS response
        $valid=IsValidContactInfo($first_name, $last_name, $business_name, $email, $phone, $error_message);
        $valid = $valid && IsValidAddressInfo($add1, $add2, $city, $state, $zip, $error_message);

        if(! $valid) {
            return $error_message;
        }
    }
} )

...

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Hi,

    You need to tell PHP to pass $data by reference, you do that by adding & - e.g. &$data. See the PHP documentation here.

    Allan

  • JenskhJenskh Posts: 2Questions: 1Answers: 0

    Thanks Allan; I'm glad it was so simple. Ironically, I pass by reference in my "IsValidAddressInfo()" function but neded a second set of eyes to point out my error here.

This discussion has been closed.