Friday, October 19, 2018

A Custom SugarLogic Expression

I made my first custom SugarLogic expression tonight. It turned out to be fairly easy but the Manual has small error in it and it fails to explain one thing.

 So here is the complete story.  First, this is the Developer Guide Manual page for this. Its fairly complete but it tells you to run the SugarLogic repair from the 'Schedulers' menu instead of the 'Repair' menu, small detail. It also does not really go over where the little 'how to' popup text is created. I will go over that here.

 For this demo I made a simple SugarLogic expression that returns the number of years from a date until now. It was to show the age of a person based on a birthday field. Here is the code that I placed in this file 'custom/include/Expressions/Expression/Date/NumberOfYearsExpression.php'

<?php
/**
* <b>NumberOfYears(Date d)</b><br>
* Returns number of years since the specified date.
*/
class NumberOfYearsExpression extends NumericExpression
{
/**
* Returns the entire enumeration bare.
*/
function evaluate() {
$params = DateExpression::parse($this->getParameters()->evaluate());
if(!$params) {
return false;
}
$now = TimeDate::getInstance()->getNow(true);
//set the time to 0, as we are returning an integer based on the date.
$params->setTime(0, 0, 0); // this will be the timestamp delimiter of the day.
$tsdiff = $params->ts - $now->ts;
$diff = (int)ceil($tsdiff/31536000);
return $diff;
}
/**
* Returns the JS Equivalent of the evaluate function.
*/
static function getJSEvaluate() {
return <<<EOQ
var then = SUGAR.util.DateUtils.parse(this.getParameters().evaluate(), 'user');
var now = new Date();
then.setHours(0);
then.setMinutes(0);
then.setSeconds(0);
var diff = then - now;
var years = Math.ceil(diff / 31536000000);
return years;
EOQ;
}
/**
* Returns the operation name that this Expression should be
* called by.
*/
static function getOperationName() {
return "NumberOfYears";
}
/**
* All parameters have to be a date.
*/
static function getParameterTypes() {
return array(AbstractExpression::$DATE_TYPE);
}
/**
* Returns the maximum number of parameters needed.
*/
static function getParamCount() {
return 1;
}
/**
* Returns the String representation of this Expression.
*/
function toString() {
}
}

Once you have the file in place you run the Admin > Repair > Rebuild Sugar Logic Functions repair and then clear your local browser cache. That last step is crucial.

There is a popup on the Expression Editor that explains hwo to use a function, in this case it looks like this


The text for this popup comes from that comment at the top of the file there, I dont know how or where they do that and it seems rather silly to do it that way but there you go.  The comment in question is above the CLASS in the code

/**
 * <b>NumberOfYears(Date d)</b><br>
* Returns number of years since the specified date.
*/


No comments:

Post a Comment