December 2014

Drupal 7 Bootstrap image field upload widget

When using the Bootstrap theme in Drupal 7, the image upload widget leaves a lot to be desired. I looks pretty crappy
Below is how I overcame this.
It should probably work with file fields too but instead of overriding THEME_image_widget, you would override THEME_file_widget, though I haven't tried it yet.

First, add this to your css

 .btn-file { 
position: relative;
overflow: hidden;
}

.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity = 0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}

Then override the theme_image_widget in your template.php
A note on admin theme
If your upload widget is on a node edit page (or any admin page) the active theme will be your admin theme. This means the code will need to go into your admin themes template.php and the css in your admin themes css.

 function MYTHEME_image_widget($variables) { 
$element = $variables['element'];
$output = '';
$output .= '<div class="image-widget form-managed-file clearfix">';

if (isset($element['preview'])) {
$output .= '<div class="image-preview">';
$output .= drupal_render($element['preview']);
$output .= '</div>';
}

$output .= '<div class="image-widget-data">';
if ($element['fid']['#value'] != 0) {
$element['filename']['#markup'] = '<div class="form-group">' . $element['filename']['#markup'] . ' <span class="file-size badge">' . format_size($element['#file']->filesize) . '</span></div>';
}
else {
$element['upload']['#prefix'] = '<div class="input-group"><span class="input-group-btn"><span class="btn
...

Disable taxonomy term delete button if term has nodes.

The below snippet will disable the delete button on the taxonomy term edit page if the term has any nodes assigned to it.
It implements hook_form_FORM_ID_alter()

 function hook_form_taxonomy_form_term_alter(&$form, &$form_state) { 
$query = db_select('taxonomy_index', 't');
$query->condition('tid', $form_state['term']->tid, '=');
$query->join('node', 'n', 't.nid = n.nid');

$count = $query->countQuery()->execute()->fetchField();
if ($count) {
$form['actions']['delete']['#disabled'] = TRUE;
$form['actions']['delete']['#suffix'] = "<span>$count nodes, cant delete</span>";
}
}