Leverage the filter system, convert plain text URLs into links in drupal.

Posted by: 
Dominique De Cooman

This small post will explain how you can leverage the filter system to apply it to external data:

  • Convert plain text URLs into links in drupal.
  • Limit allowed HTML tags
  • Convert line breaks into HTML
  • Correct faulty and chopped off HTML

You can call every filter from code if you want to. Let us say that you have a custom ds field that is pulling data (html) from somewhere.

<?php
    
// Use the database we set up earlier
    
db_set_active('db_integration');

    
// Get your data
    //OutputWordScanner by cid, tid and source to get the test name and words. Display like "test: words"    
    
$field 'field_' $node->type '_tid';
    
$results db_query("SELECT * FROM {CustomOutputSuggestor} WHERE cid  = :cid AND source = :source AND tid = :tid", array(
      
':cid' => $account->field_cid['und'][0]['value'],
      
':source' => str_replace('tender_'''$node->type),
      
':tid' => $node->{$field}['und'][0]['value'],
        )
        )->
fetchAll();

    
// Go back to the default database,
    
db_set_active();

    
//Process the results from the query
    
module_load_include('module''filter''filter');
    
$filter = new stdClass();
    
$filter->settings = array(
      
'filter_url_length' => 80,
    );
    foreach (
$results as $result) {      
      
$data .= '<div class="suggestion-test-suggestion">' _filter_url($result->suggestions$filter) . '</div>';
    }
    
// Save result of the data to the cache
    
$expire time() + variable_get('db_expire_time'3600);
    
cache_set($user->uid '-' $node->nid '-' 'suggestion'$data'cache_tests'$expire);
?>

The data that we are pulling contains links so we want those links to be formatted correctly. This you can do by using the snippet:

<?php
      module_load_include
('module''filter''filter');
      
$filter = new stdClass();
      
$filter->settings = array(
        
'filter_url_length' => 80,
      );
     
_filter_url($result->suggestions$filter)
?>

The snippet creates a class with settings and then executes the filter_url filter to filter the results for urls to convert.

You can do this for every filter. For example you want to:

  • limit allowed HTML tags? You can create a setting with the allowed tags and have it filter.
  • You want to chop of faulty html? A common problem when importing html from other sources.

Add new comment