Showing posts with label Drupal7. Show all posts
Showing posts with label Drupal7. Show all posts

Monday, March 19, 2012

D7 alter login form set default username password



function MYMODULE_form_user_login_block_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'MYMODULE') . '/js/login_form.js',
  );
}



login_form.js
==========
(function ($) {
  $(document).ready(function() {
    var name = document.getElementById("edit-name");
    name.value = "demo";

    var pass = document.getElementById("edit-pass");
    pass.value = "password";
  });
})(jQuery)





Sunday, March 18, 2012

purge drupal taxonomy term data


  // drush php-script purge_taxonomy_term.php

  $vocab_vid = taxonomy_vocabulary_machine_name_load("vocab_name")->vid;

  $terms = taxonomy_get_tree($vocab_vid);
  foreach($terms as $term) {
    //$term = taxonomy_term_load($term->tid);
    taxonomy_term_delete($term->tid);
  }

Monday, February 20, 2012

Upload & Process uploaded file drupal

function test_import($form, &$form_state) {
  $form['csv_file'] = array(
      '#title'          => t('Upload a csv file'),
      '#type'         => 'file',
      '#description'  => t('Must be smaller than 5MB in size.'),
     );
  $form[] = array(
      '#type'  => 'submit',
      '#value'  => 'Process',
    );

  return $form;
}

function test_import_validate($form, &$form_state) {
  $validators = array(
     'file_validate_extensions' => array( 'csv' ),
     'file_validate_size' => array(variable_get('btn_file_size', '5') * 1024),
  );
  // the others validators are http://api.drupal.org/api/drupal/includes!file.inc/group/file/7

  $destination = FALSE;
  // $destination = 'public://testimport/';

  $fileObj = file_save_upload('csv_file', $validators, $destination);
  if (!$fileObj) {
    form_set_error('csv_file', t('Oh Unable to access file or file is missing.'));
  }

}

function test_import_submit($form, &$form_state) {

  $fileObj = file_save_upload( 'csv_file');
  if (!$fileObj) {
    form_set_error('csv_file', t('Unable to access file or file is missing.'));
  }

  ini_set('auto_detect_line_endings', true);
  $file = fopen( drupal_realpath($fileObj->uri), 'r');

  while(!feof($file)) {
    $line = fgets($file);
    $data = explode("\t", $line);
    dpm($data[0]);
  }

  fclose($file);

}


related :
http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#managed_file
http://api.drupal.org/api/examples/image_example%21image_example.pages.inc/7

Friday, February 10, 2012

clickable table row on drupal's tableselect

YOUR.inc
=========
function a_form($form, &$formstate){
  drupal_add_js(drupal_get_path('module', 'YOUR-MODULE-NAME') . '/js/selectable-row.js', 'file');
 
  $header = array
  (
    'name' => 'name',
    'surname' => 'surname',
    'action' => 'action',
  );

  $options['1'] = array(
    'name' => 'name1',
    'surname' => 'surname1',
    'action' => '<a href="http://...">link</a>',
  );

  $options['2'] = array(
    'name' => 'name2',
    'surname' => 'surname2',
    'action' => '<a href="http://...">link</a>',
  );

  $form['tableselect_field'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#multiple' => FALSE,
    '#ajax' => array(
      'callback' => 'an_example_callback',
      'wrapper' => 'a-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
    '#attributes' => array('class' => array('selectable-row')),
  );

  $form['ajax_div'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="a-div">',
    '#markup' => date('y-m-d h:i:s'),
    '#suffix' => '</div>',
  );

  return $form;
}

function an_example_callback($form, $form_state) {
  return $form['ajax_div'];
}


selectable-row.js
===================
(function ($) {

  $(document).ready(function() {

    var selectableRow = $("table.selectable-row tbody").children();

    selectableRow.hover(function () {
      $(this).addClass("highlight");
    }, function () {
      $(this).removeClass("highlight");
    });

    selectableRow.click(function() {
      $(this).siblings().removeClass("selected-row");
      $(this).addClass("selected-row");
      $(this).find(":radio").attr("checked","checked");
      $(this).find(":radio").change();
    });

    // snippet with some modification from
    // http://thephuse.com/design-and-usability/clickable-table-rows-with-jquery/
    selectableRow.find('a').hover( function() {
        $(this).parents('tr').unbind('click');
    }, function() {
        $(this).parents('tr').click( function() {
          $(this).siblings().removeClass("selected-row");
          $(this).addClass("selected-row");
          $(this).find(":radio").attr("checked","checked");
          $(this).find(":radio").change();
        });
    });

  });
})(jQuery)


YOUR.css
=========
tr.highlight {
  background-color: #0000EE;
  color: #FFF;
}

tr.selected-row {
  background-color: #00AAEE;
  color: #FE0;
}

Wednesday, December 14, 2011

Create expand collapse tree drupal 7

mymodule
|- mymodule.info
|- mymodule.module
|- mymodule.js
|- mymodule.css
|- images
 |- file.gif
 |- minus.gif
 |- plus.gif

mymodule.info:
name = My Module
description = My Description
core = 7.x

mymodule.module:
<?php

function mymodule_menu(){
  $items = array();

  $items['mymodule_page'] = array(
    'title' => 'demo',
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_page',
    'access arguments' => array('access content')
  );

  return $items;
}

function mymodule_page() {

  drupal_add_library('system', 'drupal.collapse');
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js', 'file');
  drupal_add_css(drupal_get_path('module', 'mymodule') . '/mymodule.css','file');

  $title = 'My Title';
  $type = 'ul';
  $attributes = array(
    'id' => 'my-custom-listing',
    'class' => 'custom-class another-custom-class', // a string or indexed (string) array with the classes for the list tag
  );

  $items[] = array(
    'data' => '1',
    'class' => array('dummy'=>'category'),
    'children' => array(
         array(
          'data'=> '1.1',
          'class' =>array('dummy'=> 'deepest_item')),
        array(
          'data'=> '1.2',
          'class' =>array('dummy'=> 'deepest_item')),
        array(
          'data'=> '1.3',
          'class' => array('dummy'=> 'category'),
         'children'=> array(
             array('data'=>'1.3.1','class' => array('dummy'=>'deepest_item')),
             array('data'=>'1.3.2','class' => array('dummy'=>'deepest_item'))
          )
        )
    )
  );

  $output =  array(
    'first_para' => array(
      '#type' => 'markup',
      '#markup' => '<p>A paragraph about some stuff...</p>',
    ),
    'second_para' => array(
      '#items' => $items,
      '#title' => $title,
      '#type' => $type,
      '#attributes' => $attributes,
      '#theme' => 'item_list',
    ),
  );
  return $output;

  //return theme_item_list(array('items' => $items, 'title' => $title, 'type' => $type, 'attributes' => $attributes)); }

mymodule.js:
(function ($) {
  $(document).ready(function() {
    $('li.category').addClass('expandable_icon');
    $('li.category').children().addClass('deepest_item');
    $('li.category').children().hide();
    $('li.category').each(
      function(column) {
       $(this).click(function(event){
          if (this == event.target) {
            if($(this).is('.expandable_icon')) {
             $(this).children().show();
             $(this).removeClass('expandable_icon');
             $(this).addClass('collapsible_icon');
            }else{
             $(this).children().hide();
             $(this).removeClass('collapsible_icon');
             $(this).addClass('expandable_icon');
            }
          }
        });
      });
    }
  );
})(jQuery);

mymodule.css:
.expandable_icon{
 list-style-image:url("./images/plus.gif");
 cursor:pointer;
}

.collapsible_icon{
 list-style-image:url("./images/minus.gif");
 cursor:pointer;
}

.deepest_item{
 list-style-image:url("./images/file.gif");
 cursor:pointer;
}

drush en -y mymodule

visit http://YOURSITE/mymodule_page

thanks
http://www.sendesignz.com/index.php/jquery/77-how-to-create-expand-and-collapse-list-item-using-jquery
http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_item_list/7

Thursday, December 8, 2011

show/hide table column in drupal view by jquery

My note on how to toggle show/hide table column in drupal's view.

View 3 on drupal 7 produce html like this

<table class="views-table cols-4">
  <thead> <tr>
    <th class="views-field views-field-title">Example</th>
    <th class="views-field views-field-body">howto</th>
    <th class="views-field views-field-field-1">dynamically</th>
    <th class="views-field views-field-field-2">show/hide</th>
  </tr>
  </thead>
  <tbody>
    <tr class="odd views-row-first views-row-last">
      <td class="views-field views-field-title">table column</td>
      <td class="views-field views-field-body">Drupal</td>
      <td class="views-field views-field-3">Views</td>
      <td class="views-field views-field-4">jquery</td>
    </tr>
  </tbody>
</table>

go to view edit page
Displays -> Page Details -> Page Settings -> Footer
add the following code

Show columns
<form>
<input onclick="toggleVis(this, '.views-field-title')" type="checkbox"> Title
<input onclick="toggleVis(this, '.views-field-body')" type="checkbox"> Body
</form>

<script type="text/javascript">
  function toggleVis(chkbox, col){
    if(chkbox.checked == true) {jQuery(col).show();}
    else {jQuery(col).hide();}
  }
</script>


Some might prefer FAPI like this
function showhide_column_form($form, &$form_state) {

  $form['column_visible'] = array(
    '#type' => 'fieldset',
    '#title' => 'Show/Hide column',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['column_visible']['id'] = array(
    '#type' => 'checkbox',
    '#title' => 'column1',
    '#default_value' => 1,
    '#attributes' => array('onclick' =>"toggleVis(this, '.views-field-title');"),
  );

  return $form;
}
Then replace the previous HTML form by this
<?php
print drupal_render(drupal_get_form('showhide_column_form'));
?>

For me, accessing .module is faster than the view edit page
function my_module_form_views_exposed_form_alter(&$form,&$form_state)
{
  if($form['#id'] == 'views-exposed-form-my-search-page') {

    $inline_script = '
      <style type="text/css">
      .views-field-1 { display: none; }
      .views-field-2 { display: none; }
      </style>

      <script type="text/javascript">
        function toggleVis(chkbox,col){
         if(chkbox.checked == true) { jQuery(col).show(); }
         else {jQuery(col).hide(); }
        }
      </script>';

    $element = array(
      '#type' => 'markup',
      '#markup' => $inline_script,
    );

    drupal_add_html_head($element, 'css');
  }
}


Thanks:
The Drupal community
http://www.fiendish.demon.co.uk/html/javascript/hidetablecols.html

related post about jquery
http://stackoverflow.com/questions/4673267/hide-table-columns-automatically-by-checking-a-checkbox-with-jquery

Wednesday, December 7, 2011

Create Custom Search Criteria Page in Drupal7


function my_module_menu(){
  $items = array();

  $items['my_search_page'] = array(
    'title' => t('my search screen'),
    'description' => 'when the present views filter can not suit your need such as dependent dropdown',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_search_page'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content')
  );

  return $items;
}


function my_search_page($form, &$form_state) {

  if (!isset($form_state['storage']['my_module']['search_criteria'])) {
    return drupal_get_form('my_search_form');
  }

  $build = array();
  $rows = array();

  $header = array(
    array('data' => 'Title', 'field' => 'title', 'sort' => 'asc'),
    array('data' => 'Node ID', 'field' => 'nid'),
    array('data' => 'Type', 'field' => 'type'),
    array('data' => 'Created', 'field' => 'created'),
    array('data' => 'Published'),
    );

  $title = $form_state['input']['title'];

  $query = db_select('node', 'n')
            ->condition('status', 1)  //Only published nodes, change condition as it suits you
            ->condition('title', $title.'%', 'LIKE')
            ->extend('PagerDefault')  //Pager Extender
            ->limit(10)               //10 results per page
            ->extend('TableSort')     //Sorting Extender
            ->orderByHeader($header)  //Field to sort on is picked from $header
            ->fields ('n', array (
              'nid',
              'title',
              'type',
              'created',
              'status',
            ));

  $results = $query->execute();

  foreach ($results as $node) {
    $rows[] = array(
                l($node->title, 'node/'. $node->nid),
                $node->nid,
                $node->type,
                format_date($node->created),
                $node->status
              );
  }

  //Theme the html table: http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_table/7
  $content = theme('table',
            array(
              'header' => $header,
              'rows' => $rows,
              'sticky' => TRUE,                  //Optional to indicate whether the table headers should be sticky
              'empty' => 'Find not found..',    //Optional empty text for the table if resultset is empty
            )
          );

  $build['content'] = array(
      'dummy1' => my_search_form($form, $form_state),
      'dummy2' => array('#markup' => $content,),
  );

  $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
  );

  return $build;
}


function my_search_form($form, &$form_state) {

  $form['criteria'] = array(
    '#type' => 'fieldset',
    '#title' => 'Search Criteria',
    '#attributes' => array('class' => array('container-inline')),
  );

  $form['criteria']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('title'),
    '#value' => (isset($form_state['input']['title'])) ? $form_state['input']['title'] : "",
    '#size' => 10,
    '#maxlength' => 20,
  );

  $form['criteria']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'search',
    '#submit' => array('my_search_form_submit'),
  );

  return $form;
}

function my_search_form_submit($form, &$form_state) {
  $form_state['storage']['my_module']['search_criteria'] = $form_state['values'];
  $form_state['rebuild'] = TRUE;
}



Thanks:
=======
Merge Search Criteria and search result in one page
http://drupal.org/node/1074920#comment-4529954

Create sortable and sticky-headers Table
http://www.rahulsingla.com/blog/2011/05/drupal-7-creating-drupal-style-tables-with-paging-sorting-and-sticky-headers

Multistep form
http://drupal.org/node/717750 + http://drupal.org/project/examples

Horizontal form elements
http://drupal.stackexchange.com/questions/7954/horizontal-form-elements


Wednesday, November 30, 2011

howto initial fields on Drupal 7 node creation screen


hook_form_alter
===============
# to find the element you want to change
install devel

$ cd sites/all/modules
$ mkdir mymodule
$ cd mymodule
$ vi mymodule.info

name = mymodule
description = mymodule description
core = 7.x


$ vi mymodule.module


function mymodule_form_alter(&$form, &$form_state, $form_id)
{
     // find out form_id you're interested
        drupal_set_message($form_id);
}

function mymodule_form_{content-type-machnie-name}_node_form_alter(&$form, &$form_state)
{
    // Prints a variable to the ‘message’ area of the page
        dpm($form);

    // print debuging infomation in order to find the element
        drupal_set_message($form['field_remark']['und']);

    // set default value as need
        $form['field_remark']['und']['0']['value']['#default_value'] = 'hello';
}

$ drush en -y mymodule


http://drupal.org/project/prepopulate
======================================
allows fields in most forms to be pre-populated from the $_REQUEST variable.


Thanks
- http://drupal.stackexchange.com/questions/5605/how-do-you-identify-a-form-element
- http://drupal.org/node/1248914
- http://drupal.org/node/1137562