Eno\Section » field

field($name) → value or null
field($name, $options) → array/value or null
field($name, $loader) → value or null
field($name, $loader, $options) → array/value or null

Retrieve a field's value from the section, optionally supplying a loader to validate and/or transform the value, and/or an options array.

enocolor: blue
sound:
php$section->field('color');   // returns 'blue'
$section->field('sound');   // returns null

$section->field('sound', [ 'required' => true ]);   // throws a ValidationError
$section->field('sound', [ 'enforce_element' => true ]);   // returns null
$section->field('texture', [ 'enforce_element' => true ]);   // throws a ValidationError

$section->field('color', function($value) { return strtoupper($value); });   // returns 'BLUE'

$section->field('color', function($value) {   // throws a ValidationError: Only green is allowed!
  if($value != 'green') {
    throw new Exception('Only green is allowed!');
  }
  return $value;
});

$section->field('color', [ 'with_element' => true ]);
  // returns [ 'element' => [Field name="blue" value="blue"], 'value' => 'blue' ]

Parameters

$name

A string representing the name of the field to return.

$loader

A function returning the transformed/validated value or throwing an error. (The function is applied to each list item on its own and its argument signature is dynamic, you can either use ($value) or ($name, $value))

$options

enforce_element

Whether the field must be present in the document (true or false, defaults to false)

enforce_value

Whether there must be a value or the field is allowed to be empty (defaults to false)

required

Alias for enforce_value (this exists on many methods and depending on context refers to either element or value)

with_element

Whether to return an array of the form [ 'element' => ..., 'value' => ... ] instead of just the value (default false)

Return value

The value of the field, or null if empty, or an array of the form [ 'element' => ..., 'value' => ... ] when the option with_element is specified.