Skip to content

Instantly share code, notes, and snippets.

@evagoras
Last active December 9, 2015 18:28
Show Gist options
  • Save evagoras/95038d5f68060a859b7d to your computer and use it in GitHub Desktop.
Save evagoras/95038d5f68060a859b7d to your computer and use it in GitHub Desktop.
Problem and possible solution for ColdBox ORM handling of NULLs
component singleton {
// ORM Entities
property name="entityService" inject="entityService:address";
public any function patch( event, rc, prc ) {
var bean = entityService.get( rc.id );
if( isNull(bean) ) {
// 404 Not Found
}
else {
// prc.nullProperties is populated from an onRequestCapture() Interceptor
// It includes all the passed in fields that are NULL
var bo = populateModel( model=bean, excludeFields=prc.nullProperties );
for ( property in prc.nullProperties ) {
bean.setAsNull( property );
}
var vResults = validateModel( bo );
if ( vResults.hasErrors() ) {
for ( error in vResults.getAllErrors() ) {
prc.response.addMessage( error );
}
// 400 Validation Errors
}
// no validation errors
else {
entityService.save( bo );
// 201 Resource Edited
}
}
}
}
component {
public any function init() {
return this;
}
public void function setAsNull( required string property ) {
variables[ arguments.property ] = javaCast( "null", 0 );
}
}
component {
void function onRequestCapture( any event, struct interceptData, any buffer ) {
if( listFindNoCase( "PUT,PATCH,DELETE", event.getHTTPMethod() ) ) {
// Content sent in from the client
var requestContent = toString( getHTTPRequestData().content );
// If the package is JSON, then deserialize and add to the RC collection
if ( isJson(requestContent) ) {
var jsonRequestContent = deserializeJson( requestContent );
var nullProperties = "";
for ( var key in jsonRequestContent ) {
// If value is not NULL then add it to the RC collection
if ( structKeyExists(jsonRequestContent, key) ) {
event.setValue( key, jsonRequestContent[key] );
}
// If the value is NULL then add it to a list of NULL properties
else {
nullProperties = listAppend(nullProperties,key);
}
}
// Add the list of NULL properties to the PRC collection
event.setPrivateValue( "nullProperties", nullProperties );
}
}
}
}
@evagoras
Copy link
Author

evagoras commented Dec 9, 2015

The most important lines here are https://gist.github.com/evagoras/95038d5f68060a859b7d#file-addressescontroller-cfc-L15-L17
Without those, the Bean never saves a NULL value to the database.
So if someone posts a JSON package with this:
{"someINTfieldInTheDatabase":null}
The only way I can get it to save as a NULL is by doing the above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment