1. "Fabrik 4" helpers needed!

    You are invited to join other community members active in coding, maintaining and improving Fabrik. Please visit https://fabrik.help for more information!
    Dismiss Notice

Calculate a default value

Sep 27, 2013
Calculate a default value
  • Most (but not all) element types have a default field (to set the default value for a new record). These elements typically also provide an Eval Default checkbox by which the default can become a calculated field.

    Here are some common examples of how you might use this capability to do some interesting things:

    Basic example of return (top)

    You should always return a string or numeric value you want to use as the default. In this example we are returning the string 'default'.
    return 'default';

    Set to todays date but at 8pm / 20hrs (top)

    $d = JFactory::getDate();
    $d->setTime(20, 0, 0);
    return $d->toSql();

    Get the element's filter value (top)

    Say you filtered a list on an element, then went to add in a new record. Wouldn't it be great if the filtered element's value matched the selected filter? To achieve this enter the following in the element's default field:
    return FabrikHelperElement::filterValue(8);
    Replace the 8 in the above example with your element's id.

    Set to a query string value(top)

    Element values can be set on the query string, without using the Default mechanism, by simply appending &table___element=value on the query string on a form's normal URL. However, sometimes you may need to pass a query string value to a read only element (one which has "Form Access" set to prevent the currently logged on user from editing it).

    If an element is read only, you won't be able to set the value via the query string. But because default values are still applied when creating a new form, even for 'read only' elements, you can use this trick with an eval'ed default:

    $app = JFactory::getApplication();
    return $app->input->getString('query_string_key');
    This would set the element's default value to whatever &query_string_key=value is set to on the URL. Obviously modify this to use getInt() if you specifically want an integer.

    One example way of using this trick is if you are using the Relate Data feature on a List to "Add" a form to a related list, but you wanted to keep the foreign key (FK) on the related list as read only. As the related data Add feature uses the simple query string method to set the FK on your new related form's value to that of the PK (rowid) on the 'parent' list, you would ...

    return $app->input->getInt('relatedtable___fk_element');
    on your related table's FK element on the related form.