12

I would like to add a style attribute to each title fields in my view. I have created one field for a color. I tried to rewrite the result like this:

<h2 style="color: [field_color];">[title_1]</h2>

But the style attribute will be removed. I'm using Drupal 7.

Any help appreciated.

  • Why is it removed? Have you tried using a global text field instead? – Alex Gill Oct 9 '12 at 8:31
  • Thank you for your answer! What do you mean with a global text field? The settings in my view: Format: Unformatted list Show: Fields – Ksn Oct 9 '12 at 8:47
  • You have the option to add a 'global text' field. This field must go after any other fields you have already added. You can then use tokens in this custom field to create similar to what you have done above. You can then hide the fields that are shown in the custom field. – Alex Gill Oct 9 '12 at 8:52
  • 1
    Your best option is to probably create a custom template file for this field or use a class based on the token mentioned below. – Alex Gill Oct 9 '12 at 9:27
  • 1
    If you look under 'Advanced' on the right-hand side theres an option for 'Theme information', here it will give you some suggestions for templates. – Alex Gill Oct 9 '12 at 9:56
4

You can set a class to the title field using Style Settings as shown below screen. You can user token replacements in style settings to set class to the title field.

enter image description here

Using small javascript or jquery read the class of title field and set the color same as class name using CSS property.

  • 2
    Maybe your solution works, but I what to solve this without javascript. Is is possible? – Ksn Oct 9 '12 at 9:36
  • 2
    You cannot directly inject the field value to style property due to security issues.. See the issue here drupal.org/node/853880 – Anil Sagar Oct 9 '12 at 9:45
  • Then you need to write separate css class for each color, however this is worst case, cause you need to write 16 million class :(. Javascript or jquery would be better. – Mathankumar Oct 9 '12 at 10:40
  • 2
    Anil, I tried your solution but Drupal removed # from the color, so I found another solution with jQuery. I added the attribute data to the field: <h2 data-color="[field_color]">[title_1]</h2> I have investigated other solutions with templates, but I couldn't find the right way to solve it. – Ksn Oct 9 '12 at 10:56
1

You can create a tpl for this field (example: views-view-field-MY-VIEW-NAME-page.tpl.php), in this tpl you can add the token writing this:

<h2 style="color: <?php print $field->last_tokens['[field_color]'] ?>;"><?php print $field->last_tokens['[title_1]'] ?></h2>
1

I also had to include the value of a field as an inline color for a particular field. After browsing the web for an easy customizable solution, I ended up doing this:

  1. Add the value of the color as a CSS Class token, just like the image in the previous post.
  2. Rewrite the hook_preprocess_views_view_field() function like this:

     function hook_preprocess_views_view_fields(&$vars) {
      $view = $vars['view'];
    
      // Loop through the fields for this view.
      $previous_inline = FALSE;
      $vars['fields'] = array(); // ensure it's at least an empty array.
      foreach ($view->field as $id => $field) {
    
        // render this even if set to exclude so it can be used elsewhere.
        $field_output = $view->style_plugin->get_field($view->row_index, $id);
        $empty = $field->is_value_empty($field_output, $field->options['empty_zero']);
        if (empty($field->options['exclude']) && (!$empty || (empty($field->options['hide_empty']) && empty($vars['options']['hide_empty'])))) {
          $object = new stdClass();
          $object->handler = & $view->field[$id];
          $object->inline = !empty($vars['options']['inline'][$id]);
    
          $object->element_type = $object->handler->element_type(TRUE, !$vars['options']['default_field_elements'], $object->inline);
          if ($object->element_type) {
            $class = '';
            if ($object->handler->options['element_default_classes']) {
              $class = 'field-content';
            }
    
            if ($classes = $object->handler->element_classes($view->row_index)) {
              if ($class) {
                $class .= ' ';
              }
              $class .= $classes;
            }
    
            $class_array = explode(' ', $class);
            foreach ($class_array as $cid => $candidate) {
              // Find the color hex code.
              if (preg_match('/([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?\b/', $candidate)) {
                $style = 'color:#' . $candidate . ';';
                unset($class_array[$cid]);
              }
            }
    
            $pre = '<' . $object->element_type;
            if ($class) {
              $pre .= ' class="' . implode(' ', $class_array) . '"';
            }
            if ($style) {
              $pre .= ' style="' . $style . '"';
            }
            $field_output = $pre . '>' . $field_output . '</' . $object->element_type . '>';
          }
    
          // Protect ourself somewhat for backward compatibility. This will prevent
          // old templates from producing invalid HTML when no element type is selected.
          if (empty($object->element_type)) {
            $object->element_type = 'span';
          }
    
          $object->content = $field_output;
          if (isset($view->field[$id]->field_alias) && isset($vars['row']->{$view->field[$id]->field_alias})) {
            $object->raw = $vars['row']->{$view->field[$id]->field_alias};
          }
          else {
            $object->raw = NULL; // make sure it exists to reduce NOTICE
          }
    
          if (!empty($vars['options']['separator']) && $previous_inline && $object->inline && $object->content) {
            $object->separator = filter_xss_admin($vars['options']['separator']);
          }
    
          $object->class = drupal_clean_css_identifier($id);
    
          $previous_inline = $object->inline;
          $object->inline_html = $object->handler->element_wrapper_type(TRUE, TRUE);
          if ($object->inline_html === '' && $vars['options']['default_field_elements']) {
            $object->inline_html = $object->inline ? 'span' : 'div';
          }
    
          // Set up the wrapper HTML.
          $object->wrapper_prefix = '';
          $object->wrapper_suffix = '';
    
          if ($object->inline_html) {
            $class = '';
            if ($object->handler->options['element_default_classes']) {
              $class = "views-field views-field-" . $object->class;
            }
    
            if ($classes = $object->handler->element_wrapper_classes($view->row_index)) {
              if ($class) {
                $class .= ' ';
              }
              $class .= $classes;
            }
    
            $object->wrapper_prefix = '<' . $object->inline_html;
            if ($class) {
              $object->wrapper_prefix .= ' class="' . $class . '"';
            }
            $object->wrapper_prefix .= '>';
            $object->wrapper_suffix = '</' . $object->inline_html . '>';
          }
    
          // Set up the label for the value and the HTML to make it easier
          // on the template.
          $object->label = check_plain($view->field[$id]->label());
          $object->label_html = '';
          if ($object->label) {
            $object->label_html .= $object->label;
            if ($object->handler->options['element_label_colon']) {
              $object->label_html .= ': ';
            }
    
            $object->element_label_type = $object->handler->element_label_type(TRUE, !$vars['options']['default_field_elements']);
            if ($object->element_label_type) {
              $class = '';
              if ($object->handler->options['element_default_classes']) {
                $class = 'views-label views-label-' . $object->class;
              }
    
              $element_label_class = $object->handler->element_label_classes($view->row_index);
              if ($element_label_class) {
                if ($class) {
                  $class .= ' ';
                }
    
                $class .= $element_label_class;
              }
    
              $pre = '<' . $object->element_label_type;
              if ($class) {
                $pre .= ' class="' . $class . '"';
              }
              $pre .= '>';
    
              $object->label_html = $pre . $object->label_html . '</' . $object->element_label_type . '>';
            }
          }
    
          $vars['fields'][$id] = $object;
        }
      }
    
    }
    

As you can see, I've added these lines:

$style = '';
$class_array = explode(' ', $class);
foreach ($class_array as $cid => $candidate) {
  // Find the color hex code.
  if (preg_match('/([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?\b/', $candidate)) {
    $style = 'color:#' . $candidate . ';';
    unset($class_array[$cid]);
  }
}

And change the line under:

$pre = '<' . $object->element_type;
if ($class) {
  $pre .= ' class="' . implode(' ', $class_array) . '"';
}
if ($style) {
  $pre .= ' style="' . $style . '"';
}
0

add a name into the field anil suggested then open style.css in your theme folder and type ".my-css-name" followed by desired css results such as:

.my-css-name { color:red; background:green; }

0

I'm just making something similar and here is what i did:

1- Create a view with color and title fields.

2- Create a custom "views-view-fields.tpl" for that view. (A custom template only for the color field, showed me an error)

3- At field->content line add/replace what you need....<h2 style="color: #<?php print $field->content; ?>">

/ / / / From now on, i didn't test it, but it should work fine / / / /

4- Exclude the title field and show it on the header/group

5- Create a custom "views-view-unformatted.tpl" for that view.

6- In this view we add <?php print $title; ?></h2> after <?php print $row; ?>. (we add the title and close the H tag open in the first template)


LAST EDIT:

You can simply use views PHP to print all the thing you need and style won't be filtered.

0

I had this same problem and solved it by creating a template named

views-view-field--field_name_here.tpl.php

In my case, the code I used to create the HTML I needed was:

<?php

$bg_color = $variables["row"]->field_field_button_background_color[0]["raw"]["rgb"];
$link_title = $variables["row"]->field_field_slideshow_item_cta_link[0]["raw"]["title"];
$link_url = $variables["row"]->field_field_slideshow_item_cta_link[0]["raw"]["url"];

echo '<a style="background-color:'.$bg_color.'" href="'.$link_url.'">'.$link_title.'</a>';

Enabling the Devel module and using

dpm($row);

in the template file was VERY helpful. Couldn't have figured this out without it.

0

The easiest solution I could find was to insert the value as a data attribute. Then in my JavaScript I take the value from the data field and update the CSS to reflect the change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.