Help with isset($_POST['action']) && $_POST['action'] === 'edit'

Help with isset($_POST['action']) && $_POST['action'] === 'edit'

crush123crush123 Posts: 417Questions: 126Answers: 18
edited May 2015 in Editor

I have an editor instance where I want to update another table on edit.

All was working ok, until I added validation to some of my editor fields.

If everything validates ok, no problem, but the $_POST['action'] === 'edit' block of code will run regardless of whether my editor validates, throwing an error

How can I check to see if the editor input validates before running the edit block ?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,771Questions: 1Answers: 10,112 Site admin

    Use the Editor->validate() method - which is just what the Editor class calls internally to perform the validation. Obviously you need to set up the list of fields etc first.

    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited May 2015

    Sorry, I very well may be missing the point here.

    The validation bit works, so for example

     if (Editor::action( $_POST ) === Editor::ACTION_EDIT) {
            $contacttypeidvalue = $_POST['data']['contacts']['ContactTypeID'];
            $companyidvalue = $_POST['data']['contacts']['CompanyID'];
            $membershipexpiresvalue = $_POST['data']['members']['MembershipExpiresEnd'];
    
            //If contacttype has been selected, update the companyidField   
            if ($contacttypeidvalue == '1') {
            //set companyidField to the new value if company contact
            $companyidField
                ->set( Field::SET_EDIT )
                ->validator( 'Validate::notEmpty' );
            } else {
            //set companyidField to null if not a company contact
            $companyidField
                ->set( Field::SET_EDIT )
                ->setValue( function() {return null;});
            }
            //If membershipyear has been selected, update the membershipexpiresField    
            if ($membershipexpiresvalue != '') {
            $membershipexpiresField
                ->set( Field::SET_EDIT );
                //->validator( 'Validate::required' );
            }
        }
    

    an invalid entry will prevent the editor form from posting

    but if i add the following code after ->process

    if ( isset($_POST['action']) && $_POST['action'] === 'edit' ) {
    ////check the contact type of the contact being edited, and remove from the members table if their contacttypeid iS not 2 (individual member)
    $contacttype = $_POST['data']['contacts']['ContactTypeID'];
     if ($contacttype != 2) {//if NOT an individual member, remove row from the members table
     $editedcontact =  ltrim($data['row']['DT_RowId'],'row_');
    //remove rows from the members table if they exist
      $sql = $db->sql( "DELETE FROM members WHERE ContactID IN (".$editedcontact.")");
     }
    

    }

    this block runs regardless of the form data being valid.

    if it IS valid, all is well, but if it isn't, it throws an error.

    I would like the second block to run only if the entry is valid

  • allanallan Posts: 61,771Questions: 1Answers: 10,112 Site admin

    but if i add the following code after ->process

    Add it before the data is processed :-). You want to ensure that it is valid before the data is acted upon presumably.

    You want to set the Editor class up fully, and then execute the validation. If it passes go on to do whatever is needed in your custom actions and call the process() method.

    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited May 2015

    In my own mind, i thought that running the second block after the process method would mean that if the editor class had invalid data, then it wouldn't process, hence the second block wouldn't execute.

    I tried moving the code before the data is processed, but that throws an error every time

    If it helps clarify, here is the full editor class

    <?php
    
    
    // DataTables PHP library
    include( "../DataTables-1.10.5/extensions/Editor-PHP-1.4.2/php/DataTables.php" );
    
    // Alias Editor classes so they are easy to use
    use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Join,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate;
    
    // Build our Editor instance and process the data coming from _POST
      $editor = Editor::inst( $db, 'contacts', 'ContactID' );//table name and PKey(defaults to ID)
    
            $companyidField = Field::inst( 'contacts.CompanyID' );
            //->set( Field::SET_NONE );
    
            $membershipexpiresField = Field::inst( 'members.MembershipExpiresEnd' );//individual members (editable)
            //->set( Field::SET_NONE );
    
            $membershipexpiresField_1 = Field::inst( 'members_1.MembershipExpiresEnd' );//company members (non editable)
            //->set( Field::SET_NONE );
    
        if (Editor::action( $_POST ) === Editor::ACTION_CREATE) {
            $companyidvalue = $_POST['data']['contacts']['CompanyID'];
            $membershipexpiresvalue = $_POST['data']['members']['MembershipExpiresEnd'];
    
            //If corporate contact has been selected, update the companyidField 
            if ($companyidvalue != '') {
            $companyidFieldthe 
                ->set( Field::SET_CREATE );
                //->validator( 'Validate::required' );
            }
            //If membershipyear has been selected, update the membershipexpiresField    
            if ($membershipexpiresvalue != '') {
            $membershipexpiresField
                ->set( Field::SET_CREATE );
                //->validator( 'Validate::required' );
            }
        }
    
        if (Editor::action( $_POST ) === Editor::ACTION_EDIT) {
            $contacttypeidvalue = $_POST['data']['contacts']['ContactTypeID'];
            $companyidvalue = $_POST['data']['contacts']['CompanyID'];
            $membershipexpiresvalue = $_POST['data']['members']['MembershipExpiresEnd'];
    
            //If contacttype has been selected, update the companyidField   
            if ($contacttypeidvalue == '1') {
            //set companyidField to the new value if company contact
            $companyidField
                ->set( Field::SET_EDIT )
                ->validator( 'Validate::notEmpty' );
            } else {
            //set companyidField to null if not a company contact
            $companyidField
                ->set( Field::SET_EDIT )
                ->setValue( function() {return null;});
            }
            //If membershipyear has been selected, update the membershipexpiresField    
            if ($membershipexpiresvalue != '') {
            $membershipexpiresField
                ->set( Field::SET_EDIT );
                //->validator( 'Validate::required' );
            }
        }
    
      $editor->field(
        Field::inst( 'contacts.ContactID' ),
        Field::inst( 'contacts.ContactTypeID' ),
        $companyidField,
        Field::inst( 'contacts.FirstName' ),
        Field::inst( 'contacts.LastName' ),
        Field::inst( 'contacts.EmailAddress1' )
            ->validator( 'Validate::email' ),
        Field::inst( 'contacts.EmailAddress2' )
            ->validator( 'Validate::email' ),
        Field::inst( 'contacts.CompanyName' ),
        Field::inst( 'contacts.JoinedFromSite' )
                ->setFormatter( function ( $val, $data, $opts ) {
                    return ! $val ? 0 : 1;
                } ),
        Field::inst( 'contacts.RequestedMembershipForm' )
                ->setFormatter( function ( $val, $data, $opts ) {
                    return ! $val ? 0 : 1;
                } ),
        Field::inst( 'contacts.Display' )
                ->setFormatter( function ( $val, $data, $opts ) {
                    return ! $val ? 0 : 1;
                } ),
        Field::inst( 'contacts.Active' )
                ->setFormatter( function ( $val, $data, $opts ) {
                    return ! $val ? 0 : 1;
                } ),
        Field::inst( 'companies.CompanyDescription' )
            ->set( Field::SET_NONE ),
        $membershipexpiresField,
        $membershipexpiresField_1
    )
    ->leftJoin('companies','companies.CompanyID', '=','contacts.CompanyID')
    ->leftJoin('members','members.ContactID', '=','contacts.ContactID')
    ->leftJoin('members AS members_1','members_1.CompanyID', '=','companies.CompanyID');
    
    $data = $editor
    ->process( $_POST )
    ->data();
    
    if ( ! isset($_POST['action']) ) {
        // Get a list of corporate members for the `select` list
    $data['corpmembers'] = $db
        ->sql( 'SELECT companies.CompanyID as value, companies.CompanyDescription as label FROM companies INNER JOIN members ON members.CompanyID = companies.CompanyID ORDER BY CompanyDescription ASC')
        ->fetchAll();
    }
    
    if ( isset($_POST['action']) && $_POST['action'] === 'edit' ) {
    ////check the contact type of the contact being edited, and remove from the members table if their contacttypeid iS not 2 (individual member)
    $contacttype = $_POST['data']['contacts']['ContactTypeID'];
     if ($contacttype != 2) {//if NOT an individual member, remove row from the members table
     $editedcontact =  ltrim($data['row']['DT_RowId'],'row_');
    //remove rows from the members table if they exist
      $sql = $db->sql( "DELETE FROM members WHERE ContactID IN (".$editedcontact.")");
     }
     }
    
    
    echo json_encode( $data );
    ?>
    
  • allanallan Posts: 61,771Questions: 1Answers: 10,112 Site admin

    The process() method will call validate() itself, and if validation fails it will not continue to process the data - but it does not stop the rest of the script executing.

    I don't see a call to $editor->validate() above. If you wanted to validate the data before doing something, I would expect it to be placed around like 106.

    However, if you are happy to have the additional actions after the process() call, then you could just check what $data contains and see if there are any field errors. If so, then validation failed.

    Allan

  • allanallan Posts: 61,771Questions: 1Answers: 10,112 Site admin

    Thanks for your PM - I hope you don't mind continuing the discussion here (just as this is where the code is, so I can easily refer to it!).

    Does your additional logic need to run before or after the ->process() method is called? The solution will depend directly on that.

    Regards,
    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited May 2015

    I dont think it matters where it runs, but here is my scenario

    Basically all I want to do is validate my editor fields, and at the point the table is updated, I (may) need to update another table, dependent upon the values returned.
    If any of the editor fields do not validate, i want to see a validation error, so the form is not submitted.

    eg if I am changing the contacttypeid ($_POST['data']['contacts']['ContactTypeID']).

    If the value returned is '2', do nothing, otherwise delete a row in the other table
    At the moment, if i try and run the delete, i get an error, but if I remove the validation, it processes ok, (but obviously the data entered into the main table is not what i want)

    Hope this makes sense

  • allanallan Posts: 61,771Questions: 1Answers: 10,112 Site admin
    Answer ✓

    Got it! Thanks for the clarification.

    Try this:

    $data = $editor
        ->process( $_POST )
        ->data();
    
    if ( ! isset($_POST['action']) ) {
        // Get a list of corporate members for the <code>select</code> list
        ...
    }
    
    if ( ! isset( $data['fieldErrors'] ) && isset($_POST['action']) && $_POST['action'] === 'edit' ) {
        ////check the contact type of the contact being edited, and remove from the members table if their contacttypeid iS not 2 (individual member)
        ...
    }
    

    I've cut down the blocks of code as I've not made any changes there and so that the change is clearer.

    The only thing I've done is to add ! isset( $data['fieldErrors'] ) into your condition for doing the additional work. I think this is the easiest and most straight forward option.

    So basically all it does is to check and see if Editor found any validation errors (we know that if fieldErrors is set, then there were errors - if it is not, then there were no errors).

    Does that make sense? And more importantly, when you update your code, does that work for you?

    Regards,
    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18

    Looking good

    $data['fieldErrors'] is the check I needed.

    My scenario is currently simpler than it will be, I need to make checks at create too, but now this logic is in place, I can get on with it.

    Thanks again

This discussion has been closed.