Skip to main content

Decimal Numeric field type in Drupal 8 Form API

If you are looking for a nice presetantion table for the drupal 8 API form like this one (in drupal 7) https://api.drupal.org/api/drupal/developer!topics!forms_api_reference… you will be dissappointed because there is nothing like this for drupal 8. Do not worry because the drupal 8 form API evolved and got better :)

Trying to find how do i declare a decimal - float with a precision of to 2 decimal places was kind of hard as there was no example. What i found was the number type field with the step option in it. The examples were only with steps of integer numbers e.g step => 2 , step => 10 etc and it was then that i had my AHA! moment. Why not only integers and not decimals too! So here it is.

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $config = $this->config(static::SETTINGS);

    //Precision of 2 decimals like 23,23 or 56,76 etc
    $form['cost_per_hour'] = [
      '#type' => 'number',
      '#step' => '.01',
      '#title' => $this->t('Monday - Saturday (1 hour)'),
      '#description' => $this->t('Total cost (vat 24% included) for 1 hour from Monday to Saturday'),
      '#default_value' =>  $config->get('meeting_room.daily_1_hour'),
      '#required' => TRUE,
      '#weight' => '0',
    ];

    //Precision of 1 decimals like 23,2 or 56,7 etc
    $form['cost_per_hour'] = [
      '#type' => 'number',
      '#step' => '.1',
      '#title' => $this->t('Monday - Saturday (1 hour)'),
      '#description' => $this->t('Total cost (vat 24% included) for 1 hour from Monday to Saturday'),
      '#default_value' =>  $config->get('meeting_room.daily_1_hour'),
      '#required' => TRUE,
      '#weight' => '0',
    ];

 

form api