The question is pretty straightforward. How can I add a class on field A, if field B is empty? I can not find any module does this feature. The Conditional Fields does not have the class feature too. Can this done by programmatically? If so, how?
3 Answers
One solution here is is to use template_preprocess_field
function. In your template.php add a MYTHEME_preprocess_field
function and perform a check on the node's field value to determine a class that you set in the classes_array
variable.
function MYTHEME_preprocess_field(&$variables) {
$node = menu_get_object();
//Add a new CSS class to field_MYHIDDEN_FIELD
if($variables['element']['#field_name'] == 'field_MYHIDDEN_FIELD') {
//Check field_MYCHECKED_FIELD for an empty value
$new_class = (!isset($node->field_MYCHECKED_FIELD[LANGUAGE_NONE][0]['value'])) ? 'mytheme-field-novalue' : 'mytheme-field-value';
$variables['classes_array'][] = $new_class;
}
}
-
Nope, it should stay
[0]
if your field only accepts one value. The example code sets the classmytheme-field-novalue
when there's no value set in thefield_MYFIELD
field. For title field, you can check the$node->title
property. Commented Sep 22, 2015 at 20:40 -
Sorry I accidentally deleted my questions. Here are my questions: 1. If I want to make the statement for “if not empty”, where should I change? change the “[0]” to “[1]”? 2. If I want to make the statement for title field, what do I need to replace with “field_MYFIELD[LANGUAGE_NONE]?– CocoSkinCommented Sep 22, 2015 at 20:56
-
If you want to reverse the logic, just drop the
!
operator in front of theisset
function call. Commented Sep 22, 2015 at 21:02 -
sorry Shawn, i still not clear where to put the 2nd field and new class. Please see my updated question above.– CocoSkinCommented Sep 23, 2015 at 13:47
-
I updated the answer to elaborate on what I think you're asking. Commented Sep 24, 2015 at 1:32
I would use states for something like this:
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states
Another more pure UI route is to use Views, Views "No Results" and View "Rewriting" and either the EVA or ctools Content Panels to construct the node view.
I haven't tested this, but it will look something like this:
- Create a content view filtering by node and published value
- Add fields B and A (in that order)
- Set Field A to "Exclude from Display"
- Configure field B's "No results behavior" to render something like
<span class="b_empty">[field_a]</span>
but set the "Rewrite Results" to<span class="b_has_data">[field_a]</span><span>[field_b]</span>
Here, field B is doing all the heavy lifting, empty or not. - Using EVA, you can then attach that result to your node's field display as you need.