I'm writing a custom field using the Drupal 8 API. Now I need to have a radio button group with some custom classes to each of the different options label. I have already the render array for rendering the radio buttons but can't add some class to the options label.

How can I do this?

In the code block below, you can find a html example on how to draw the field:

<fieldset id='demo2' class='rating'>
    <input class='stars' type='radio' id='s5' name='rating' value='10' />
    <label class='full' for='s5'></label> <input class='stars' type='radio' id='s4h' name='rating' value='9' />
    <label class='half' for='s4h'></label> <input class='stars' type='radio' id='s4' name='rating' value='8' />
    <label class='full' for='s4'></label> <input class='stars' type='radio' id='s3h' name='rating' value='7' />
    <label class='half' for='s3h'></label> <input class='stars' type='radio' id='s3' name='rating' value='6' />
    <label class='full' for='s3'></label> <input class='stars' type='radio' id='s2h' name='rating' value='5' />
    <label class='half' for='s2h'></label> <input class='stars' type='radio' id='s2' name='rating' value='4' />
    <label class='full' for='s2'></label> <input class='stars' type='radio' id='s1h' name='rating' value='3' />
    <label class='half' for='s1h'></label> <input class='stars' type='radio' id='s1' name='rating' value='2' />
    <label class='full' for='s1'></label> <input class='stars' type='radio' id='sh' name='rating' value='1' />
    <label class='half' for='sh'></label></fieldset>";

My render array looks like:

$element['fieldset'] = array(
      '#type' => 'fieldset',
      '#attributes' => array(
        'class' => array(
          'rating',
        ),
      ),
    );

    $element['fieldset']['star'] = array(
      '#type' => 'radios',
      '#options' => array(1 => "", 2 => "", 3 => "", 4 => "", 5 => "", 6 => ""
      , 7 => "", 8 => "", 9 => "", 10 => ""),
      '#attached' => array(
        'library' => array(
          'core/jquery',
          'rate_field/admin-star-field',
        ),
      ),
      '#attributes' => array(
        'class' => array(
          'stars',
        ),
      ),
    );

Comments

dotmundo’s picture

Either create a custom template for this, use one of the preprocessing/alter hooks or use JQuery. I am not clear what the logic should be for distinctive classes. Can you elaborate?