Validation

Validation

menashemenashe Posts: 196Questions: 43Answers: 2

Time to get crazy!

Can I have a Validator which checks whether a related table (FKs) has a latest value (think MAX function in SQL) which is within X days of today?

I have a PURCHASES table, which has one record per line on a store receipt. If an item is on sale for a period of a week, I don't want to enter a new (the SAME) price in the PRICES table every time that I might purchase it that week.

I'd like to check if I already have an entry in the PRICES table within that timeframe; OTHERWISE, I will require a new price (via the Validator).

Alternately, what are my options vis-a-vis SQL or Editor PHP to return the price information. (I know how to write that SQL; can it be called from Datatables?)

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin

    Sure you can! You can provide custom field validators and custom form level validation. Since they are custom functions, you can do what ever you want, including calling the database. You just need return a string on error or true if valid.

    Allan

  • menashemenashe Posts: 196Questions: 43Answers: 2

    Allan,

    Thank you! I don't see any examples of accessing the database in a custom field validator.

    Can you give me an example or pointer?

    Thanks!

  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin
    Answer ✓
    Editor::inst( $db, 'table' )
        ->fields( ... )
        ->validator( function ( $editor, $action, $data ) use ($db) {
          $pdoResource = $db->resource();
    
          // .. normal PDO query / binding / etc
        })
    

    You could use our abstraction layer if you prefer, but a PDO object means you can just do all the normal database stuff as you would with any other PHP script.

    One thing to consider is that your validator might need to be different between an edit and an insert. For example, if you are checking for duplicates, on edit you need to discount the existing row. The predefined db validators in the libraries might be of some interest to see how they work.

    Allan

  • menashemenashe Posts: 196Questions: 43Answers: 2

    Thank you!

    Where have you been hiding this stuff??! :D

Sign In or Register to comment.