0

In Views and several field formatting modules you are given the ability to trim the end of text fields to show for example only the first 100 characters. However what if I want to do the reverse. What if I want to trim a field to not show the first 100 characters but to show everything else, how could I do this?

1

The right way would be to write your own view field plugin.

The quick way is as follows: I assume your text field is the main body field. Install views_php. In your view hide the text field. Add a Global PHP field. Make sure it is after the text field. In its output code put the following:

<?php print substr($data->field_body[0]['rendered']['#markup'], 100);?>

In Rewrite Results strip out HTML tags. As you are truncating text you will run into problems with unmatched tags, so you have to do this. Also, this sanitises the text. If you do not do this you have to run check_markup in the php.

Also, this is not the preferred way to output a field. The correct way is to use field_view_field.

And if your field is anything other than the body, then install devel module, and include this PHP snippet in the output code of the PHP field.

<?php print dsm($data);?>

This will help with getting the right field.

| improve this answer | |
  • Ok I tried the above code, the field I am trying to use is the default comment body field whose D7 machine name should be "comment_body". So I tried the following: <?php print substr($data->comment_body[0]['rendered']['#markup'], 100);?> But this causes a PHP error: Notice: Undefined property: stdClass::$comment_body in __lambda_func() I am going to try to install the Devel module and see how I go. I have never used it before. – FrontEnd Jul 13 '14 at 6:55
  • 1
    Code for the comment body: <?php print substr($data->field_comment_body[0]['rendered']['#markup'], 100);?> This is just a primer. You still have to deal with issues such as what to do when the comment text is shorter than 100 characters. – J. Reynolds Jul 19 '14 at 6:59
  • 1
  • 1
    <?php $output = strrev($data->field_comment_body[0]['rendered']['#markup']); $max = 100; if(strlen($output)>$max) { $output = substr($output ,0,$max); $i = strrpos($output ," "); $output = substr($output ,0,$i); $output = $output ." ..... "; } print strrev($output); ?> – J. Reynolds Jul 23 '14 at 5:29
  • 1
    <?php $output = strrev($data->field_comment_body[0]['rendered']['#markup']); $len = strlen($output); $max = 100; if($len-$max>=0) { $output = substr($output ,0,$len-$max); $i = strrpos($output ," "); $output = substr($output ,0,$i); $output = $output ." ..... "; } print strrev($output); ?> – J. Reynolds Jul 24 '14 at 16:35

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.