Skip to content

Instantly share code, notes, and snippets.

@carwin
Created September 21, 2012 03:02
Show Gist options
  • Save carwin/3759515 to your computer and use it in GitHub Desktop.
Save carwin/3759515 to your computer and use it in GitHub Desktop.
Drupal 7: Conditionally change templates based on fields filled out on node creation.
function themefoo_preprocess_node(&$variables, $hook) {
$node = $variables['node'];
$type = $variables['type'];
$columns = 1; // Default to 1 column layout.
/*
* Programmatically figure out how many columns we have
* based on which fields the user has filled out in
* the node form.
*
* I'll update this gist later to explain
*/
if(isset($variables['field_side_block_ref'])){
if(!empty($variables['field_side_block_ref'][0])){
$side_blocks = $variables['field_side_block_ref'];
$columns++;
}else{
$side_blocks = false;
}
}
if(isset($variables['field_content_image'])){
if(!empty($variables['field_content_image'][0])){
$content_image = $variables['field_content_image'];
$columns++;
}else{
$content_image = false;
}
}
/*
* Check for File Attachments too, but don't add a column
*/
if(isset($variables['field_file_attachments'])){
if(!empty($variables['field_file_attachments'][0])){
$has_attach = $variables['field_file_attachments'];
}else{
$has_attach = false;
}
}
/*
* Check for Gallery content, don't add a column.
*/
if(isset($variables['field_gallery_images'])){
if(!empty($variables['field_gallery_images'][0])){
$gallery_images = $variables['field_gallery_images'];
}else{
$gallery_images = false;
}
}
/*
* Assign theme_hook_suggestions based on the number of
* columns in the $columns variable.
*/
switch ($columns) {
case 1:
// Nothing special to do here, just use node.tpl.php
array_push($variables['theme_hook_suggestions'], 'node__1col');
break;
case 2:
//$variables['theme_hook_suggestions'][] = 'node__2col';
array_push($variables['theme_hook_suggestions'], 'node__2col');
break;
case 3:
//$variables['theme_hook_suggestions'][] = 'node__3col';
array_push($variables['theme_hook_suggestions'], 'node__3col');
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment