Milk Admin

Expressions in Model (RuleBuilder)

In the Model you can define expressions directly in the rules. These are executed by the backend through ExpressionParser during fill() and validate().

Available Methods

Method Purpose Backend
calcExpr($expression) Calculates a value from other fields Applied in AbstractModel::applyCalculatedFieldsForCurrentRecord()
validateExpr($expression, $message) Custom validation with boolean expression Evaluated by ModelValidator
requireIf($expression) Field required only if condition is true Evaluated by ModelValidator

Complete Example

public function configure($rule)
{
    $rule->int('qty')->required();
    $rule->float('price')->required();

    // Calculated field (backend)
    $rule->float('total')->calcExpr('[qty] * [price]');

    // Custom validation
    $rule->date('end_date')
        ->validateExpr('[start_date] <= [end_date]', 'End date must be later');

    // Conditional required
    $rule->string('notes')
        ->requireIf('[qty] > 10')
        ->error('Notes required for quantity > 10');
}

Backend Behavior

  • calcExpr: is executed on the current record; if the expression fails, the field is not updated.
  • validateExpr: must return true. If it returns a non-empty string, the string is used as an error message.
  • requireIf: if the expression is true, the field is required.
Tip: defining calcExpr, validateExpr and requireIf in the Model allows the FormBuilder to automatically inherit them as data-milk-* on the frontend.
Frontend/Backend difference: on the frontend validateExpr considers only the boolean result true as valid. For custom messages use data-milk-message or the $message parameter in the FormBuilder.
Loading...