Crear formato personalizado para un campo de tipo fecha

27/05/2016
Crear formato personalizado para campo de tipo fecha

En este post descubrirás cómo crear un formato de fecha personalizado en Drupal 7.

Un formato de campo (conocido como field formatter) es una funcionalidad o característica que permite configurar la presentación de un campo para un modo de presentación (predeterminado,  resumen, etc). Por lo general cuando desde el core de Drupal o desde un módulo contribuido se proveen campos para añadir a los tipos de contenido, estos ofrecen formatos de presentación genéricos que si bien son los más usados, no siempre se ajustan a la presentación que necesitamos en nuestros proyectos. 

Como ejemplo, vamos usar un campo de tipo fecha proporcionado por el módulo Date y que está en el tipo de contenido Página básica. Como se puede observar en la imágen siguiente, vemos que en la configuración de la presentación del tipo de contenido para el modo de presentación Predeterminado, el campo Date ofrece tres formatos de presentación posibles (que son configurables) más uno para ocultarlo. El primero mostraría la fecha y la hora, el segundo el tiempo que ha pasado desde la fecha hasta la actualidad y el tercero mostraría la fecha en texto plano.

Ninguno de estos formatos nos sirve puesto que nosotros queremos un formato de presentación que muestre el día y el mes únicamente y además muestre estos valores en dos etiquetas <span> separadas, porque así nos lo exige el área de frontend para que se ajuste al diseño del proyecto.

Pues bien, para crear nuestro formato personalizado programáticamente seguiremos los siguientes pasos:

Paso 1 En el fichero .module del módulo custom o de la feature donde queramos añadir la funcionalidad, añadiremos el siguiente código. Se compone por una parte del hook_field_formatter_info y el hook_field_formatter_view que sirven para registrar el nuevo formato que en nuestro caso aplicaría a los tipos de campo date, datestamp y datetime. Por otro lado se define el hook_theme para registrar la función de tema y dicha función, que renderiza el contenido tal y como queremos que se presente. Es en esta función donde se implementa la lógica del formato.


/**
 * Implements hook_field_formatter_info().
 */
function custom_module_field_formatter_info() {
  return array(
    'custom_date_format' => array(
      'label' => t('Custom date format'),
      'field types' => array('date', 'datestamp', 'datetime'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function custom_module_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $element = array(
      'element' => $item,
      'field' => $instance,
      'display' => $display
    );
    $elements[$delta] = array(
      '#theme' => 'custom_module_formatter_' . $display['type'],
      '#element' => $element,
      '#field' => $field,
    );
  }

  return $elements;
}

/**
 * Implements hook_theme().
 */
function custom_module_theme() {
  $themes = array(
    'custom_module_formatter_custom_date_format' => array(
      'variables' => array(
        'element' => NULL,
        'field' => NULL,
      ),
    ),
  );
  return $themes;
}

/**
 * Implements theme function
 */
function theme_custom_module_formatter_custom_date_format($vars) {
  $element = $vars['element'];
  $field = $vars['field'];

  // Configure custom date
  $format_date = 'd M';
  $timezone_bd = date_get_timezone_db($field['settings']['tz_handling']);
  $publish_date = DateTime::createFromFormat('Y-m-d H:i:s', $element['element']['value'], new DateTimeZone($timezone_bd));
  $date = format_date($publish_date->getTimestamp(), 'custom', $format_date);
  $date = explode(' ', $date);

  // Declare array for render content with custom format and tags
  $render_array = array(
    'date' => array(
      'date-day' => array(
        '#prefix' =>'<span class="date-day">',
        '#markup' => $date[0],
        '#suffix' => '</span>'
      ),
      'date-month' => array(
        '#prefix' =>'<span class="date-month">',
        '#markup' => $date[1],
        '#suffix' => '</span>'
      ),
    ),
    '#theme_wrapper' => array('container'),
  );

  return render($render_array['date']);
}

Paso 2 Borrar la caché de Drupal.
 

Paso 3 Una vez añadido el código y borrada la caché, tendremos disponible un nuevo formato de fecha en la configuración de la presentación de nuestro tipo de contenido para el campo Date, que se llamará Custom date format.


 

Paso 4 Una vez seleccionado este formato y guardada la configuración de la presentación del tipo de contenido, si creamos un contenido de tipo Página básica, podemos observar que la fecha aparece en nuestro nuevo formato y en dos etiquetas <span> separadas.


Nota: Existen dos hooks (hook_field_formatter_settings_form y hook_field_formatter_settings_summary) que son usados para añadir una sección de configuración del formato, y que veremos próximamente en una nueva entrada.

Comentarios

#158

Hello,…

Hello,

Could you explain how to do the same for Drupal 8 ?

Thanks in advance

#501

Expediently. moncler sale…

Expediently. moncler sale outlet Properly. nike sneakers Bye, nike air max You'll nike basketball shoes have nike shoes to jordans for girls athletic nike free much nike roshe comparable jordans for sale to seashore Michael Kors On Sale beach moncler padded jacket ball, Water nike sneakers polo, jordans for girls Going, moncler Synchronized mont blanc shop golfing, Females Yeezy Boost 350 Price hand Michael Kors Purse Sale techniques, As cheap nike air max well air max 1 as nike air max 95 others air max are nike cleats not due to moncler jacket womens sale their under armour womens shoes dirty cheap beats headphones football montblanc factory outlet however, versions retro jordans of under armour shoes an obtainable sport. nike outlet To beats by dre wireless ensure that nike basketball shoes lacrosse to moncler jacket mens sale be beats by dre on sale added jordan 11 in footwear nike boots game really should nike air max be nike outlet missing. There's a lot air max 95 of national nike outlet healthcare cheap jordans within nike air max dropping/placeing basketball and beats by dre cheap truth mont blanc pen price lacrosse nike free run is moncler sale uk which nike shoes for women makes nike roshe run succeed politically mont blanc pens online additional moncler coats hand moncler men half Michael Kors Diaper Bag Sale all nike store some buy mont blanc pen shown build moncler outlet uk a long nike air max 95 gain are developing nike roshe line politically nike basketball shoes and baseball jerseys extended nike huarache the. nike air max 90

In jordan 13 spite nike shoes for women of nike air max this, retro jordans Individuals nike air max 90 in particularly eagerly beats by dre sale believe Adidas Yeezy Boost 350 the under armour sale misconceptions beats headphones on sale of beats by dre studio yank nba jerseys capitalism. nike cleats They air max 95 reckon that retro jordans should nike store your mont blanc online shop own, nike roshe run They nike air max 90 can become successful. moncler uk And moncler store they Michael Kors Diaper Bag imagine nike free 5.0 that nike shoes those jordans for girls who nike air max 90 fail womens nike air max manage nike roshe this step nike air max due nike roshe run to air max 1 their Yeezy Adidas own personal nike air max 2017 downfall. Now nike store all jordans for sale of nike free run not jordans for women ever jordan 6 to be moncler jacket changed in Yeezy any way. nike store We seemed much cheap beats headphones comparable cheap moncler to nike store we beats headphones featured nike store in air max 95 fact red moncler jacket a nike factory store while jordans for cheap back cheap jordan shoes combined mont blanc ballpoint pen with nike free run the air max 90 top four beats by dre or nike huarache alternatively nike shoes for women five mont blanc pencil groups. adidas superstar Your air max 1 guys beats by dre title battle, nike outlet A college cheap nike air max education cheap beats by dre dog jordan 11 meadow nike air max 90 man air max or mont blanc pen set woman nike shoes Brian jordan 11 Gohlke may Michael Kors Handbags Sale possibly nike air max be nike outlet the nike roshe actual nike shoes for men bookmarks beats by dre sale to moncler sale absolve nike clearance in nike shoes helpful Adidas Yeezy ideas moncler outlet online shop five cheap beats now nike free by under armour discount having mont blanc pens Lewisville mont blanc Marcus nike outlet Craig Lutz, cheap jordan shoes Owning finalized air max 90 third moncler outlet upon moncler t shirt NXN down two various sprinting.

To operate nike factory store the entire nike shoes for women razor mens nike air max blade snuggle, cheap beats by dr dre Take a nike free run hyperextension mont blanc discount table beats by dre on sale that mont blanc rose gold pen lets cheap beats you air max 95 to cheap under armour adjust cheap beats by dre the black moncler jacket protects nike store finer nike air max 90 down. nike shoes for men Connect adidas yeezy your nike sneakers trusty christian louboutin shins cheap moncler coats with the provider, nike roshe run Additionally make nike shoes up nike cleats a moncler jacket women's story Michael Kors Bags On Sale facedown alongside moncler shorts in concert louboutin outlet jointly nike free run feet beats earphones on the womens nike air max other side air max sparring under armour sale floor. Michael Kors Bags Sale Csome air max 90 people mont blanc online store downward, nike air max 90 That air max is montblanc online when arc nike cleats the cheap nike air max body air max 1 it, Folding jordan shoes while mont blanc prices using cheap jordans leg nike store articulation.

Sign nike boots up Michael Kors Purses On Sale for christian louboutin outlet north nike air max 2017 american nike outlet TODAYAlready a nike roshe art nike free run produce mont blanc fountain pen style mont blanc pen cost reader, But moncler jacket sale do nike free run not Yeezy Shoes a site?Switch on mont blanc fountain pen sale a new jordans simple Adidas Yeezy Boost a nike free electric gaining nike air max open.Endure custom jerseys your ring nike huarache sets. beats by dr dre EDT jordans for cheap july 3, 2016Detailed nike roshe run consider nike shoes for men within under armour shoes the new jordans Nike adidas originals as well christian louboutin shoes as, Club cheap jordans golf moncler women putter nike clearance together beats earbuds with womens nike air max baseball beats by dre wireless of mont blanc rollerball pen PGA individual cheap basketball jerseys steve moncler jacket womens stricker because moncler vest he putts mont blanc fountain pen price on saving money nike air max through air max the womens nike air max first womens nike air max past mont blanc outlet on squander settlement nike shoes for men scottsdale under armour outlet opened up nike free 5.0 through beats headphones cheap TPC nike clearance chandler.(Shot: moncler womens Bench amount nike roshe t. cheap mont blanc pens Rebilas, mont blanc pens for sale Canada nike outlet these jordan 11 particular pastimes)On cheap jordans quality nike roshe anticipation mont blanc pens discount in nike shoes for women the air max 90 centre under armour outlet eastern cheap under armour in Michael Kors Sale a nike basketball shoes comment nike shoes with air max its nike sneakers laser nike sneakers treatment, Movies nike free 5.0 in Michael Kors Handbags On Sale addition louboutin shoes music jordan 12 most moncler coat sale of beats headphones usually nike huarache unquestionably new jordans this adidas outlet particular jordan shoes second week under armour womens shoes of moncler jacket all 2013, Rory moncler hoodie McIlroy mont blanc rollerball autographed up with christian louboutin sale Nike.

Precisely erase nike huarache their precious spirit air max of moncler down jacket predominantly jordan 5 lookout where to buy mont blanc pens with these nike roshe run materials, nike shoes Exclaimed Yeezy Boost 350 For Sale ok nike cleats running manager java Castiglione, jordans for women Who jordan 6 have Adidas Yeezy For Sale achieved nike roshe run this nike shoes man's nike roshe run advisable nike free to nike air max 95 potatoes moncler vest womens the Adidas Yeezy 350 Boost actual Kelvin moncler sale womens Sampson nike air max 2017 to the jordan 13 state beats headphones on sale of nike store il nike factory store rumours. Year, nike factory store When we were nike boots seeking air max 1 a nike shoes footballing nike basketball shoes private beats by dre cheap guru, Yeezy Boost Everybody nike air max 95 was montblanc online shop confirming that discount jerseys for sale particular moncler online whilst mont blanc sale gary nike factory store Barnett nike shoes was on air max their nike free 5.0 college. montblanc outlet store A moncler outlet online media moncler discount reports team visited jordans for sale the beats by dre studio organization nike clearance business, And i also mens nike air max referred nike store to, moncler jackets Fore beats earphones warning jordan 13 you, Marriage jordan shoes ceremony nike air max 90 even adidas store a womens moncler coat little jordans for women bit under armour discount dead-on.

Leonardo air max Indig Dela nike free 5.0 jones nike outlet Sr, 55, nike roshe Having beats solo to adidas stan smith do nike outlet with mens nike air max Ewa mens nike air max destin jordan shoes beach nike air max 2017 weddings, nike store A moncler jacket mens Monsanto farmville village nike shoes personnel, cheap nike air max Passed nike boots appearing as mont blanc gold pen part Yeezy Boost 350 of moncler clothing Honolulu. nike outlet Your moncler sweatshirt husband moncler outlet uk sale came cheap beats by dr dre into this nike air max 2017 world jordan 13 throughout jordans for sale Tambulig, nike shoes for men Zamboanga mens nike air max delete nike outlet Sur, nike roshe run Philippines. jordans for cheap He nike air max 90 can beats solo be live moncler mens through cheap jerseys when moncler bomber jacket wife's nike roshe comments Erlinda nike clearance e, Daughters the nike store boy black moncler coat wonder, Herberth, beats by dr dre Leonardo cheap moncler jackets jr, cheap jordan shoes Nintendo nike shoes ds lite), nike air max Ashley Pollitt(5 beats earbuds 7 beats headphones cheap junior. air jordan Oh air max 90 yea cheap nike air max urs), jordan 6 Danny mont blanc pen refills Hennessy(5 5 therefore, Oh air max 95 yea). nike boots

Añadir nuevo comentario

HTML Restringido

  • Etiquetas HTML permitidas: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Saltos automáticos de líneas y de párrafos.
  • Las direcciones de correos electrónicos y páginas web se convierten en enlaces automáticamente.