Skip to content

Instantly share code, notes, and snippets.

@opi
Last active December 20, 2015 12:29
Show Gist options
  • Select an option

  • Save opi/6131176 to your computer and use it in GitHub Desktop.

Select an option

Save opi/6131176 to your computer and use it in GitHub Desktop.
Drupal : text => link formatter
<?php
/**
* Implements hook_field_formatter_info().
*/
function mymodule_field_formatter_info() {
return array(
'mymodule_link' => array(
'label' => 'Link for ingenie site/email',
'field types' => array('text'),
'settings' => array(
'link_type' => 'http'
),
),
);
}
/**
* Implements hook_field_formatter_settings_form().
* @return array
*/
function mymodule_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
$display = $instance['display'][$view_mode];
$settings = $display['settings'];
$element = array();
if ($display['type'] == 'mymodule_link') {
$element['link_type'] = array(
'#title' => t("Type of link"),
'#type' => 'radios',
'#options' => array(
'http' => "http://",
'mailto' => "mailto:",
),
'#default_value' => ($settings['link_type']) ? $settings['link_type'] : 'http',
);
}
return $element;
}
/**
* Implements hook_field_formatter_settings_summary().
*/
function mymodule_field_formatter_settings_summary($field, $instance, $view_mode) {
$display = $instance['display'][$view_mode];
$settings = $display['settings'];
$summary = array();
if ($display['type'] == 'mymodule_link') {
$summary[] = ($settings['link_type'] == 'http') ? "http://" : "mailto:";
}
return implode('<br />', $summary);
}
/**
* Implements hook_field_formatter_view().
*/
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
$settings = $display['settings'];
switch ($display['type']) {
case 'mymodule_link':
foreach ($items as $delta => $item) {
$url = $item['value'];
if(!empty($url)) {
switch($settings['link_type']) {
case 'http':
// Force url to begin with http
if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
$url = 'http://' . $url;
}
break;
case 'mailto':
$url = 'mailto:'.$url;
break;
}
// Return link
$element[$delta] = array(
'#theme' => 'link',
'#text' => check_plain($item['value']),
'#path' => $url,
'#options' => array(
'html' => FALSE,
'absolute' => TRUE,
'external' => TRUE,
'attributes' => array(
'target' => '_blank',
'title' => entity_label($entity_type, $entity)
)
)
);
} // if(!empty($url)) {
}
break;
}
return $element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment