Skip to content

Commit

Permalink
Add decimal field support to field factory service.
Browse files Browse the repository at this point in the history
  • Loading branch information
mstenta committed Mar 30, 2023
1 parent 2c0aef3 commit 5f9b32b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
5 changes: 5 additions & 0 deletions docs/development/module/services.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ Both methods expect an array of field definition options. These include:
- `type` (required) - The field data type. Each type may require additional
options. Supported types include:
- `boolean` - True/false checkbox.
- `decimal` - Decimal number with fixed precision. Additional options:
- `precision` (optional) - Total number of digits (including after the
decimal point). Defaults to 10.
- `scale` (optional) - Number digits to the right of the decimal point.
Defaults to 2.
- `entity_reference` - Reference other entities. Additional options:
- `target_type` (required) - The entity type to reference (eg: `asset`,
`log`, `plan`)
Expand Down
38 changes: 38 additions & 0 deletions modules/core/field/src/FarmFieldFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ protected function buildFieldDefinition(BaseFieldDefinition &$field, array $opti
$this->modifyBooleanField($field, $options);
break;

case 'decimal':
$this->modifyDecimalField($field, $options);
break;

case 'entity_reference':
$this->modifyEntityReferenceField($field, $options);
break;
Expand Down Expand Up @@ -234,6 +238,40 @@ protected function modifyBooleanField(BaseFieldDefinition &$field, array $option
]);
}

/**
* Decimal field modifier.
*
* @param \Drupal\Core\Field\BaseFieldDefinition &$field
* A base field definition object.
* @param array $options
* An array of options.
*/
protected function modifyDecimalField(BaseFieldDefinition &$field, array $options = []) {

// Set the precision and scale, if specified.
if (!empty($options['precision'])) {
$field->setSetting('precision', $options['precision']);
}
if (!empty($options['scale'])) {
$field->setSetting('scale', $options['scale']);
}

// Build form and view display settings.
$field->setDisplayOptions('form', [
'type' => 'number',
'weight' => $options['weight']['form'] ?? 0,
]);
$view_display_options = [
'label' => 'inline',
'type' => 'number_decimal',
'weight' => $options['weight']['view'] ?? 0,
];
if (!empty($options['scale'])) {
$view_display_options['settings']['scale'] = $options['scale'];
}
$field->setDisplayOptions('view', $view_display_options);
}

/**
* Entity reference field modifier.
*
Expand Down

0 comments on commit 5f9b32b

Please sign in to comment.