PHP Field validation example

From DreamFactory
Jump to: navigation, search
DreamFactoryTutorialsPHP Field validation example
 
(4 intermediate revisions by 2 users not shown)
Line 1: Line 1:
This script validates that certain fields are in the POST request when creating records. If not, an exception is thrown  
+
This script validates that certain fields are in the POST request when creating records. If not, an exception is thrown and 500 error returned to the client. If the script exits normally with no exception being thrown, then the records will be written to the database and the post-process script, if any, will be run.  
and 500 error returned to the client. If the script exists normally with no exception being thrown then the records will  
+
be written to the database and the post-process script, if any, will be run.  
+
  
 
<pre>
 
<pre>
Line 7: Line 5:
 
// This script runs BEFORE records are written to the db.
 
// This script runs BEFORE records are written to the db.
  
$payload = \Request::json()->all();
+
$payload = $event['request']['payload'];
  
if(!array_key_exists('annual_revenue', $payload)){
+
if(!empty($payload['resource'])){
    throw new \Exception('Missing field annual revenue.');
+
    foreach($payload['resource'] as $record){
}
+
        if(!array_key_exists('annual_revenue', $record)){
 
+
            throw new \Exception('Missing field annual revenue.');
if($payload['annual_revenue'] <= 0){
+
        }
    throw new \Exception('Annual revenue must be > 0');
+
       
 +
        if($record['annual_revenue'] <= 0){
 +
            throw new \Exception('Annual revenue must be > 0');
 +
        }
 +
    }
 
}
 
}
 
</pre>
 
</pre>

Latest revision as of 22:14, 15 July 2016

This script validates that certain fields are in the POST request when creating records. If not, an exception is thrown and 500 error returned to the client. If the script exits normally with no exception being thrown, then the records will be written to the database and the post-process script, if any, will be run.

// POST /api/v2/db/_table/account triggers script db._table.account.post.pre_process
// This script runs BEFORE records are written to the db.

$payload = $event['request']['payload'];

if(!empty($payload['resource'])){
    foreach($payload['resource'] as $record){
        if(!array_key_exists('annual_revenue', $record)){
            throw new \Exception('Missing field annual revenue.');
        }
        
        if($record['annual_revenue'] <= 0){
            throw new \Exception('Annual revenue must be > 0');
        }
    }
}