I want to change the views field label name programtically? I have written a views-view-field.tpl.php. but dont know to change the $output variable.
2 Answers
You can use hook_views_pre_render() for that.
Add this function to your template.php
file:
function YOURTHEME_views_pre_render(&$view) {
switch ($view->name) {
case 'name_of_your_view':
// do some logic for your label
$label = 'My dynamic label';
// define the label value
$view->field['fieldname']->options['label'] = $label;
break;
}
}
Now, the label value will be always as the logic result. No matter whether the label is defined via Views Ui or not, it will be altered by your logic anyway.
-
Are you sure it works on theme level? I always thought it is a module hook only...– CodiumAug 3, 2013 at 21:02
-
Yes, I'm sure it works. Just paste it into your
template.php
file and test it. You can use this hook either by module or theme.– Jack-PLAug 3, 2013 at 21:13 -
@Jack-PL: Thanks i implemented it sucessfully. Actually i want to get label from the view only(dynamic label). So got the label value like this $view->result[0]->_field_data['nid']['entity']->field_aux1_title; Thanks a lot :)– RamAug 5, 2013 at 5:36
When you want to have control over any output at the theme layer, you will have to understand the flow which generate the output.
At first lets see how the output for a field get structured at theme.inc inside view/theme folder. You can have a look at it here. Where you will see $label
& $label_html
getting prepared for tpl files.
So you a option to do your work with help of this preprocess function also, which you will have to implement in your template.php
. You will prepare label name before it goes to tpl file to be printed.
Other way is, when you visit your views-view-fields.tpl.php inside same folder of views/theme, you will see $label_html
to be printed in there. You will have to work on it to achieve what you want as this contains full HTML structure of label of the field.
I believe there are way to do this by help of field--FIELDNAME.tpl.php
also if you are looking to change the label for being displayed the same at every place..
Note - This is not the exact solution but guideline to follow & get your own solution. I have never done this exactly for view but for field label where ever it appears, so if you need, I can post exact solution for that.