라벨에 클래스를 추가하려면 어떻게해야합니까?


8

Drupal의 폼 API로 생성 된 특정 레이블에 클래스 이름을 다음과 같이 추가해야합니다.

$form['name'] => array(
  '#type' => 'textfield',
  '#title' => 'Prénom'
);

다음을 사용 <textarea>하면 레이블이 아닌 클래스를 가져옵니다.

$form['name']['#attributes']['class'] = array('myClass');

에 클래스를 추가 할 비슷한 것을 찾고 있습니다 <label>.


필드 이름에 대한 상위 컨테이너 클래스를 사용하여 CSS를 사용하여 해당 필드 레이블을 아직 대상으로 지정할 수없는 경우도 고려해야합니다..field-name-field-myfield label{ color:red; }
David Thomas

답변:


6

Form API의 속성을 사용하여 클래스를 양식 요소의 레이블 태그로 설정할 수 없습니다. 그러나 접두사와 접미사를 설정하여 요소 (라벨 + 텍스트 영역)를 래핑하고 중첩 된 CSS 선택기를 사용하여 수행하려는 작업을 수행 할 수 있습니다.

$form['name'] => array(
  '#type' => 'textfield',
  '#title' => 'Prénom'
  '#prefix' => '<div class="myClass">',
  '#suffix' => '</div>'
);

CSS에서 다음과 같이 레이블 태그를 선택할 수 있습니다.

.myClass label {
  text-transform: uppercase; /* just for example */
}

괜찮은 해결책은 아니지만 이것이 내가 보통하는 방법이며 다른 사람들이하는 것을 보았습니다. #attributes입력 요소 자체이므로 코드가 myClass클래스를 추가하는 것이 맞습니다 textarea.


7

StackOverflow 의이 게시물에 따르면 Drupal Form API는 레이블에 클래스 추가를 지원하지 않지만 적절한 해결 방법이 포함되어 있습니다.

대신 필드 및 레이블에 랩퍼 클래스를 사용하여 대상을 지정할 수 있습니다.

.form-item-field-foo label {
  /* CSS here */
}

theme_form_element_label ()에 대한 API 문서는 레이블을 사용할 수없는 이유를 보여줍니다 (적어도 즉시 사용 가능한 것은 아님). 속성 배열이 테마 함수에서 초기화되고 두 개의 선택적 클래스 ( 'option'및 'element)로 채워집니다. -보이지 않음 ').

완전히 불가능합니까? 사실, 나는 그것이 가능하다고 생각하지만, 나는 이것을 직접 시도하지 않았다는 것을 덧붙여 야합니다. 당신은 시도 할 수 있습니다 :

  • 사용자 정의 모듈에서 hook_element_info_alter ()#label_attributes사용하여 일부 (또는 모든) 양식 요소에 새 특성을 추가하십시오 .
  • theme_form_element_label ()을 재정의하고 $attributes배열을 값과 병합합니다 $element['#label_attributes'].

시도해 보시면 작동하는지 알려주십시오.


시간 제약으로 인해 Ayesh K가 제안한 더 쉬운 해결책을 찾아 볼 것입니다. 이것은 좋은 해결책처럼 보이지만 다른 누군가를 도울 수 있습니다. +1
Shawn

플러스 1 theme_form_element_label () 테마 기능을 언급위한
표의 문자

해결 방법 : 사이트에 JS가 필요한 경우 DOM을 조정하는 것이 가장 쉽습니다. 그렇지 않은 경우 다른 (평균) 방법은 제거 '#title'하거나 설정 '#title_display' => 'invisible'한 다음 수행하는 것 '#suffix' => '<label for="TheElementId" class="option">Display This Text</label>'입니다. 이로 인해 <div>Drupal이 양식 입력 요소에 사용 하는 랩퍼 외부에 표시 되지만 CSS 규칙은 다르게 보일 수 있습니다.
SeldomNeedy 2016 년

2

Ayesh의 답변을 확장하여 그러한 코드의 사용 사례를 포함 시켰습니다. marvangend의 답변은 Drupalesk에 비해 훨씬 간단하지만 매우 간단한 결과를 얻을 수 있습니다. 양식 특정 요소 및 CSS를 상기 양식과 함께 번들로 유지하는 것이 일반적인 사용 사례이므로 내부 요소를 대상으로하고 작업 할 수있는 것이 좀 더 구체적입니다.

http://legomenon.io/article/drupal-7-adding-form-placeholder-attributes

function mymodule_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    // Waterfall.
    case 'webform_client_form_16':
    case 'webform_client_form_51':
    case 'webform_client_form_64':
    case 'webform_client_form_78':
      $exclude = array('select', 'radios', 'checkboxes', 'managed_file');
      foreach ($form['submitted'] as $name => $component) {
        if (!in_array($component['#type'], $exclude) && $name != '#tree') {
          $form['submitted'][$name]['#prefix'] = '<span class= "label-invisible">';
          $form['submitted'][$name]['#suffix'] = '</span>';
          $form['submitted'][$name]['#attributes']['placeholder'] = $component['#title'];
        }
      }
      $form['#attached']['css'] = array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.form.css',
      );
    break;
  }
}

2

Drupal 8에서 간단히 your_module.module 파일에 추가하면됩니다

function your_module_preprocess_form_element(&$variables) {

  $element = $variables['element'];
  if (isset($element['#label_attributes'])) {
    $variables['label']['#attributes'] = array_merge(
      $variables['attributes'],
      $element['#label_attributes']
    );
  }
}

양식 작성시 #label_attributes를 추가하십시오.

$form['some_field'] = [
  [...]
  '#label_attributes' => [
    'some_attr' => 'some_value',
  ]
]

0

Fences D7 모듈을 사용하여 이것을 달성하는 비교적 쉬운 방법을 찾았습니다. 이 모듈에는 필드를 사용자 정의하기위한 많은 템플릿 파일이 제공됩니다. 고유 한 클래스를 제공 할 필드를 편집하고 랩퍼 마크 업을 관련있는 것으로 변경하십시오. 그런 다음 모듈 내에서 해당 템플릿 파일을 찾아 사이트 / all / themes / THEME_NAME에 복사하십시오.

전에

<span class="field-label"<?php print $title_attributes; ?>>
  <?php print $label; ?>:
</span>

<span class="<?php print $label; ?> field-label"<?php print $title_attributes; ?>>
  <?php print $label; ?>:
</span>

를 추가 <?php print $label; ?>하면 필드 이름을 클래스로 인쇄하여 모든 필드 레이블을 개별적으로 타겟팅 할 수 있습니다. 나는 이것이 다른 누군가를 돕기를 바랍니다!


0

더럽지 만 '#title'속성에 HTML을 추가 할 수 있습니다.

$form['some_element'] = array(
  '#type'          => 'textfield',
  '#title'         => '<span title="HELP!">'.t($subchildlabel).'</span>',
  '#default_value' => 
) 
 
);

나는 그것이 작동한다는 사실에 놀랐다. Drupal이 이것을 걸러 낼 것이라고 생각하지만, 아닙니다. 따라서 다른 클래스로 레이블을 감쌀 수 있습니다.

<label for="edit-m-vernacularname" class="inline"><span title="HELP!">Common name
</span> </label>
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.