0
votes

I am trying to add a function to that strips the html from a field in drupal views. I found a function for sql server called "udf_StripHTML" that does that.

http://blog.sqlauthority.com/2007/06/16/sql-server-udf-user-defined-function-to-strip-html-parse-html-no-regular-expression/

I am using the following code:

/**
 * Implements hook_views_query_alter().
 */
function cviews_views_query_alter(&$view, &$query) {
    // Add a strip html tags from content.
    $fields = array('field_data_body.body_value');

    foreach ($query->where as $key1 => $value) {
        foreach ($value['conditions'] as $key2 => $coditions) {
          if (in_array($coditions['field'], $fields)) {
            $query->where[$key1]['conditions'][$key2]['field'] = 'dbo.udf_StripHTML(' . $coditions['field'] . ')';
      }
    }
  }
}

When views module converts the query object to a string the field become from: 'dbo.udf_StripHTML(field_data_body.body_value)';

to: [dbo].[udf_StripHTMLfield_data_body.body_value]

My question is, how can I add a function there?

Thank you,

2

2 Answers

4
votes

You are going way too deep here friend. I'm going to assume that you're using Drupal 7, but for Drupal 8 this should be similar (since views is in core for both).

A few things about your approach:

  • That function is a user defined function which means that it needs to be defined at a much lower-level (in the SQL database) before you can use it in your query.
  • This is a red-herring approach, however, because you don't need to even touch the SQL to accomplish what you want (you can do this with PHP with strip_tags!)
  • You don't need a query alter hook here (we don't need to go to the database to do this). You could do this with one of the preprocess or field hooks from the field API or the views API using the function linked in my previous point.
  • Even better, you don't even have to touch the code to accomplish this. You can do it right in the Drupal UI.

Under the field settings for the view, select rewrite results and then Strip HTML tags. Presto, no more HTML tags in that field.

Views UI, image source: https://www.drupal.org/node/750172 Image source: https://www.drupal.org/node/750172

0
votes

Here is the solution that worked for me:

// Traverse through the 'where' part of the query.
foreach ($query->where as &$condition_group) {
   foreach ($condition_group['conditions'] as &$condition) {

      if (in_array($condition['field'], $fields)) {
         $value = $condition['value'];
         $field = $condition['field'];

         $condition = array(
           'value' => array(),
           'field' => t('dbo.udf_StripHTML(!field) like \'@value\'', array(
           '!field' => $field,
           '@value' => $value)),
           'operator' => 'formula',);
      }
   }
}