Drupal Developers' Pastebin

WE HAVE MOVED!

Please visit our new Drupal Website at https://www.xenyo.com我們的新網頁設計公司網頁.

This is a pastebin for Drupal Developers to easily share Drupal related source code and snippets.
Note: To maintain quality, paste permission is only available upon request to Drupal.org members.

Drupal Version: 8.x
Posted: Jan 29th, 2018
Tags: migrate source csv
Rating:
0
No votes yet
Using migrate source csv module, you can import the following types :
 
1. Title, body with text format, body summary
2. Date field with different format
3. Taxonomy (create if not exist)
4. Multiple images per field (need a separate csv file for images, file name as key value)
5. Multiple paragraphs per field (need a separate csv file for paragraph, id as key value)
6. Multiple values per field
7. uid (user reference)
8. created, updated date (timestamp)
 
# enable your custom migrate module first.
 * drush en custom_migrate
 
 # If you have changed the config file, you need to import the config to take effect
 * drush config-import --partial --source=modules/custom/custom_migrate/config/install/ -y
 
# first we need to import images and paragraph data first so that these items can be refereced by migrate_test.
 * drush migrate-import migrate_images --update
 * drush migrate-import migrate_paragraph --update
# run migrate_test
* drush migrate-import migrate_test --update
 
If you got php error during import, you can clean up the queue manually using sql query
 * delete from key_value where collection = "migrate_status"
 
 
-- /modules/custom/custom_migrate/custom_migrate.info
 
name: Custom Migrate
type: module
description: Custom Migrate
core: 8.x
package: Migration
dependencies:
  - migrate_source_csv
  - migrate_plus
  - migrate_tools
 
 
# we need “key_wrapper” plugin in order to import paragraph field.
 
-- /modules/custom/custom_migrate/src/Plugin/migrate/process/KeyWrapper.php
 
<?php
namespace Drupal\custom_migrate\Plugin\migrate\process;
 
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
 
/**
 * Determine the most recent entity revision id given an entity id
 *
 * @MigrateProcessPlugin(
 *   id = "key_wrapper"
 * )
 */
class KeyWrapper extends ProcessPluginBase {
 
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $new_value = array(
        'key_wrapper' => $value,
    );
    $value = $new_value;
    return $value;
  }
}
 
 
-- /modules/custom/custom_migrate/config/install/migrate_plus.migration.migrate_test.yml
 
uuid: 5c12fdab-6767-485e-933c-fd17ed554b49
status: true
dependencies:
  enforced:
    module:
      - custom_migrate
id: migrate_test
label: migration test
migration_tags:
  - CSV
source:
  plugin: csv
  path: private://artifacts/test.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    # this id must be unique, it is used for rollback or update.
    0:
      id: 'ID'
    1:
      title: 'Title'
    2:
      body: 'Body' 
    # taxonomy “category”
    3:
      category: 'Category', example : cat1 (can use with explode plugin here, but I didn’t test it)
    # images field “unlimited”
    4:
      images: 'Images',;as separator, example : filename.png;filename2.png
    # text field “unlimited”, 
    5:
      group: 'Group'  
    # date field (Date only), example : 22-02-2017
    6:
      date: 'Date'
    # paragraph id, “+” as separator, example : 1+3+4+5+6+7
    7:
      paragraph: 'Paragraph'  
process:
  type:
    plugin: default_value
    default_value: test
  title : title
  body/value: body
  body/format:
    plugin: default_value
    default_value: full_html
  # generate category if not exist
  field_category:
    plugin: entity_generate
    source: category
    value_key: name
    bundle_key: vid
    bundle: category
    entity_type: taxonomy_term
  # this will import multiples images per cell, here the separator is “;”
  field_image:
    -
      plugin: explode
      source: images
      delimiter: ;
    -
      plugin: callback
      callable: trim
    -
      plugin: migration
      migration: migrate_images
      no_stub: true
  # import the “alt” value for each image
  # field_image:
  #  -
  #    plugin: explode
  #    source: alt
  #    delimiter: ;
  #  -
  #    plugin: get
  #    source: alt
  # import multiple values here
  field_group:
    -
      plugin: explode
      delimiter: ,
      source: group
  field_date/value:
    -
      plugin: skip_on_empty
      method: process
      source: date
    -
      plugin: format_date
      from_format: 'd-m-Y'
      to_format: 'Y-m-d'
      source: date
  # import link field (link format)
  field_link: link
  # imoprt multiple paragraphs
  field_paragraph:
    -
      plugin: skip_on_empty
      method: process
      source: paragraph
    -
      plugin: explode
      delimiter: +
      source: paragraph
    -
      plugin: key_wrapper
    -
      plugin: iterator
      process:
        target_id:
          -
            plugin: migration
            migration: migrate_paragraph
            source: key_wrapper
            no_stub: true
          -
            plugin: extract
            index:
              - 0
        target_revision_id:
          -
            plugin: migration
            migration: migrate_paragraph
            source: key_wrapper
            no_stub: true
          -
            plugin: extract
            index:
              - 1
  created:
    plugin: callback
    source: created
    callable: strtotime
    created: date
  changed: '@created'
  uid:
    -
      plugin: entity_lookup
      source: created_by
      ignore_case: true
      value_key: mail
      entity_type: user
      bundle_key: status
      bundle: 1
    -
      plugin: default_value
      default_value: 1
  status:
    plugin: default_value
    default_value: 1
    source: status
destination:
  plugin: entity:node
migration_dependencies:
  required:
    - migrate_images
    - migrate_paragraphs
  optional: {}
 
 
--  /modules/custom/custom_migrate/config/install/migrate_plus.migration.migrate_images.yml
 
uuid: 5c12fdab-6767-485e-933c-fd17ed554b99
dependencies:
  module:
    - file
id: migrate_images
migration_tags:
  - CSV
label: Images
source:
  delimiter: ','
  enclosure: '"'
  constants:
    source_base_path: 'private://assets/images'
    uri_file: 'public://images'
  plugin: csv
  track_changes: true
  path: private://artifacts/images.csv
  header_row_count: 1
  keys:
    - name
  column_names:
    1:
      name: Images
process:
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - name
    -
      plugin: urlencode
  uri_file:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/uri_file
        - name
    -
      plugin: urlencode
  filename:
    -
      plugin: skip_on_empty
      method: row
      source: name
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - '@uri_file'
destination:
  plugin: 'entity:file'
migration_dependencies:
  required: { }
  optional: { }
 
 
 
/modules/custom/custom_migrate/config/install/migrate_plus.migration.migrate_paragraph.yml
 
uuid: 5c12fdab-6767-485e-933c-fd17ed234567
dependencies:
  module:
id: migrate_paragraph
migration_tags:
  - CSV
label: "Paragraph"
source:
  delimiter: ','
  enclosure: '"'
  plugin: csv
  path: private://artifacts/paragraph.csv
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: "id"
    # just a text field here
    1:
      test: "test"
process:
  field_test: test
  type:
    plugin: default_value
    default_value: paragraph
destination:
  plugin: 'entity_reference_revisions:paragraph'
migration_dependencies:
  required: {  }
  optional: {  }
Drupal Version: 7.x
Posted: Jun 5th, 2015
Tags: views, template, hook_theme
Rating:
0
No votes yet
function {{modulename}}_theme($existing, $type, $theme, $path) {
  return array (
    'views_view__{{viewsname}}__block' => array (
      'variables' => array('view' => NULL,),
      'template' => 'views-view--{{viewsname}}--block' ,
      'base hook' => 'views_view',
      'path' => drupal_get_path('module', '{{modulename}}'). '/templates',
    ),
  );
}
Drupal Version: n/a
Posted: Mar 23rd, 2015
Tags: SEO, htaccess
Rating:
0
No votes yet
#
#301 Redirects for .htaccess
#
 
#Redirect a single page:
Redirect 301 /pagename.php http://www.domain.com/pagename.html
 
#Redirect an entire site:
Redirect 301 / http://www.domain.com/
 
#Redirect an entire site to a sub folder
Redirect 301 / http://www.domain.com/subfolder/
 
#Redirect a sub folder to another site
Redirect 301 /subfolder http://www.domain.com/
 
#This will redirect any file with the .html extension to use the same filename but use the .php extension instead.
RedirectMatch 301 (.*)\.html$ http://www.domain.com$1.php
 
##
#You can also perform 301 redirects using rewriting via .htaccess.
##
 
#Redirect from old domain to new domain
RewriteEngine on
RewriteBase /
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
 
#Redirect to www location
RewriteEngine on
RewriteBase /
rewritecond %{http_host} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]
 
#Redirect to www location with subdirectory
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/directory/index.html [R=301,NC]
 
#Redirect from old domain to new domain with full path and query string:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*) http://www.newdomain.com%{REQUEST_URI} [R=302,NC]
 
#Redirect from old domain with subdirectory to new domain w/o subdirectory including full path and query string:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/subdirname/(.*)$
RewriteRule ^(.*) http://www.katcode.com/%1 [R=302,NC]
 
#Rewrite and redirect URLs with query parameters (files placed in root directory)
#Original URL:
http://www.example.com/index.php?id=1
 
#Desired destination URL:
http://www.example.com/path-to-new-location/
 
#.htaccess syntax:
RewriteEngine on
RewriteCond %{QUERY_STRING} id=1
RewriteRule ^index\.php$ /path-to-new-location/? [L,R=301]
 
 
#Redirect URLs with query parameters (files placed in subdirectory)
#Original URL: 
http://www.example.com/sub-dir/index.php?id=1
 
#Desired destination URL:
http://www.example.com/path-to-new-location/
 
#.htaccess syntax:
RewriteEngine on
RewriteCond %{QUERY_STRING} id=1
RewriteRule ^sub-dir/index\.php$ /path-to-new-location/? [L,R=301]
 
#Redirect one clean URL to a new clean URL
#Original URL:
http://www.example.com/old-page/
 
#Desired destination URL:
http://www.example.com/new-page/
 
#.htaccess syntax: 
RewriteEngine On
RewriteRule ^old-page/?$ $1/new-page$2 [R=301,L]
 
 
#Rewrite and redirect URLs with query parameter to directory based structure, retaining query string in URL root level
#Original URL:
http://www.example.com/index.php?id=100
 
#Desired destination URL:
http://www.example.com/100/
 
#.htaccess syntax:
RewriteEngine On
RewriteRule ^([^/d]+)/?$ index.php?id=$1 [QSA]
Rewrite URLs with query parameter to directory based structure, retaining query string parameter in URL subdirectory
 
#Original URL:
http://www.example.com/index.php?category=fish
 
#Desired destination URL:
http://www.example.com/category/fish/
 
#.htaccess syntax:
RewriteEngine On
RewriteRule ^/?category/([^/d]+)/?$ index.php?category=$1 [L,QSA]
 
 
#Domain change – redirect all incoming request from old to new domain (retain path)
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example-old\.com$ [NC]
RewriteRule ^(.*)$ http://www.example-new.com/$1 [R=301,L]
 
#If you do not want to pass the path in the request to the new domain, change the last row to:
RewriteRule ^(.*)$ http://www.example-new.com/ [R=301,L]
 
#From blog.oldsite.com -> www.somewhere.com/blog/
#retains path and query, and eliminates xtra blog path if domain is blog.oldsite.com/blog/
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI}/ blog
RewriteRule ^(.*) http://www.somewhere.com/%{REQUEST_URI} [R=302,NC]
RewriteRule ^(.*) http://www.somewhere.com/blog/%{REQUEST_URI} [R=302,NC]
Drupal Version: 7.x
Posted: May 13th, 2014
Tags: Email registration
Rating:
0
No votes yet
/*
* Enable email_registration.module
* Implements hook_email_registration_name()
*/
function MY_MODULE_email_registration_name($edit, $account) {
  return $account->mail;
}
Drupal Version: 7.x
Posted: Apr 28th, 2014
Tags: drupal_commerce
Rating:
0
No votes yet
/*
 * Implements hook_commerce_checkout_router()
 * Skip shipping page in checkout flow
 */
function MY_MODULE_commerce_checkout_router($order, $checkout_page) {
  if ($checkout_page['page_id'] == 'shipping') {
	//calculate shipping charge
	commerce_shipping_collect_rates($order);
 
	//update order status - @see commerce_checkout_form_submit
	$order = commerce_order_status_update($order, 'checkout_' . $checkout_page['next_page'], FALSE, TRUE, t('Shipping Page was skipped'));
 
	$form_state = array(
	  'order' => $order,
	  'checkout_page' => $checkout_page,
	  'rebuild' => FALSE,
	);
	$form_state['build_info']['args'][0] = $order;
	$form_state['build_info']['args'][1] = $checkout_page;
	$form_state['values']['commerce_shipping']['shipping_rates'] = $order->shipping_rates;
	foreach ($order->shipping_rates as $key => $shipping_method) {
	  if (empty($form_state['values']['commerce_shipping']['shipping_service'])) {
	    $form_state['values']['commerce_shipping']['shipping_service'] = $key;
	  }
	}
	$form = drupal_get_form('commerce_checkout_form_shipping', $order, $checkout_page);
 
	//run commerce_shipping_pane callback include validate and submit function
    commerce_checkout_form_validate($form, $form_state);
 
    drupal_goto('checkout/' . $order->order_id . '/' . $checkout_page['next_page']);
  }
}
Drupal Version: 7.x
Posted: Mar 29th, 2014
Tags: drupal, migration, umbraco
Rating:
0
No votes yet
Requirement:
- sql server management studio
- mdb viewer plus / MS access
- mdb2sqlite
- java opensdk-jdk
 
1. download mdb viewer plus
open mdb view plus , create a blank mdb file (test.mdb) without password.
2. open sql server management, cmd > ssms.exe    
3. right click on database you want to export > tasks > export data .
4. select data source > sql server native client 11.0 > fill in auth information and make sure connection is working.
5. click next > select destination > Microsoft access (microsoft jet database engine) > select test.mdb
6. select all tables and all data will be exported to test.mdb.
7. download https://code.google.com/p/mdb-sqlite/  >
wget https://mdb-sqlite.googlecode.com/files/mdb-sqlite-1.0.2.tar.bz2
tar -zxvf mdb-sqlite-1.0.2.tar.bz2
cd mdb-sqlite-1.0.2/
8. install opensdk > apt-get install openjdk-6-jdk
9.  upload your test.mdb to mdb-sqlite-1.0.2 directory.
10.  java -jar dist/mdb-sqlite.jar test.mdb test.sqlite
11. we will use test.sqlite for drupal migration
 
umbraco database structure : 
http://blog.hendyracher.co.uk/wp-content/uploads/Umbraco-Schema-with-Constraints-v2.gif
 
Example :  article content type migration:
<?
/**
 * @file
 * test_migrate.module
 */
/**
 * Sqlite db connection helper.
 */
function _test_migrate_sqlite_connect() {
  $other_database = array(
    'database' => '/home/test/test.sqlite',
    'host' => 'localhost',
    'driver' => 'sqlite',
  );
  $key = md5('testmigrate');
  Database::addConnectionInfo($key, 'default', $other_database);
  return $key;
}
/**
 * Implements hook_menu().
 */
function test_migrate_menu() {
  $items = array();
  $items['admin/test_migrate'] = array(
    'title' => 'test data migration',
    'page callback' => 'test_migrate_page_test',
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );
/**
 * Migrate entry.
 * Get all node data from umbraco
 */
function test_migrate_page_test() {
  $key = _test_migrate_sqlite_connect();
  db_set_active();
  db_set_active($key);
  // Dsm all data.
   $sql = db_query('
select * from cmsPropertyData as cpd
inner join (select * from cmsDataType as dt left join cmsPropertyType as cpt on cpt.dataTypeId = dt.nodeId) as data on data.id = cpd.propertytypeid left join
cmsDocument as cd on cd.versionId = cpd.versionId left join
cmsContentVersion as ccv on ccv.versionId = cd.versionId left join
umbracoNode as ubn on ubn.id = ccv.ContentId inner join
cmsContentXml as ccx on ccx.nodeId = ubn.id left join
cmsContent as cc on cc.nodeId = ubn.id left join
cmsContentType as cct on cct.nodeId = cc.contentType left join
cmsDocumentType as cdt on cdt.contentTypeNodeId = cct.nodeId left join
cmsTemplate as ct on ct.nodeId = cdt.templateNodeId
where
cd.newest = -1 and
order by cpd.contentNodeId asc
limit 0, 4000');
  db_set_active();
  foreach ($sql as $k => $v) {
    dsm($v); // dsm all whole record.
    $nids[$sql_v->nid]['xml'] = $sql_v->xml; // XML node from umbraco.
  }
  foreach($nids as $nid_k => $nid_v) {
    debug = 1; // Debug mode.
    // Actually we can grab all node data from xml
    $doc = new DOMDocument();
    $doc->recover = TRUE;
    $xml = $nid_v['xml'];
 
    $doc->loadXML($xml);
    $xpath = new DOMXPath($doc);
    $article = $xpath->query("//Article");
    $creatorId = $article->item(0)->getAttribute('creatorId');
    $sortOrder = $article->item(0)->getAttribute('sortOrder');
    $createDate = $article->item(0)->getAttribute('createDate');
    $updateDate = $article->item(0)->getAttribute('updateDate');
    $nodeName = $article->item(0)->getAttribute('nodeName');
    $writerName = $article->item(0)->getAttribute('writerName');
    $pageTitle = $xpath->query("//Article/pageTitle");
    $metaDescription = $xpath->query("//Article/metaDescription");
    $metaKeywords = $xpath->query("//Article/metaKeywords");
    $articleTitle = $xpath->query("//Article/articleTitle");
    $articleImage = $xpath->query("//Article/articleImage");
    $bodyText = $xpath->query("//Article/bodyText");
    $articleDate = $xpath->query("//Article/articleDate");
    $author = $xpath->query("//Article/author");
    $articleSynopsis = $xpath->query("//Article/articleSynopsis");
    $articleTags = $xpath->query("//Article/articleTags");
    $issueNumber = $xpath->query("//Article/issueNumber");
    $node->title = $articleTitle->item(0)->nodeValue;
    $node->type = 'article';
    $node->uid = 1;
    $node->status = 1;
    $body = $bodyText->item(0)->nodeValue;
    $node->body['und'][0]['value'] = $body;
    $node->body['und'][0]['format'] = 'full_html';
    $imagepath = $articleImage->item(0)->nodeValue;
    $img = _test_migrate_create_img($imagepath, $debug);
    if (!empty($img)) {
      $node->field_image[LANGUAGE_NONE][] = (array) $img;
    }
    if (!$debug) {
      node_save($node);
    }
    else {
      dsm($node);
    }
  }
  return '';
}
/**
 * Create image by file path.
 * we are using file entity module here.
 *
 * @Return file obj.
 */
function _test_migrate_create_img($imgpath, $debug) {
  if (empty($imgpath)) {
    return 0;
  }
  $filename = str_replace('\\', '/', $imgpath);
  $file->uri = 'private:/' . $imgpath;
  $target_dir = 'public://articles' . dirname($filename);
  if (!file_exists(drupal_realpath($file->uri))) {
    return 0;
  }
  file_prepare_directory($target_dir, FILE_CREATE_DIRECTORY);
  $file->filemime = file_get_mimetype($file->uri);
  $file->status = 1;
  $file->uid = 1;
  $file->type = 'image';
  $file->display = 1;
  if (!$debug) {
    $file = file_copy($file, $target_dir, FILE_EXISTS_REPLACE);
    return $file;
  }
  else {
    dsm($file);
    return 0;
  }
}
Drupal Version: 7.x
Posted: Oct 31st, 2013
Tags: drupal, passlock, paypal, password
Rating:
0
No votes yet
// Snippet to allow exceptions on passlocks for things such as Paypal Callback
// implement hook_boot()
function custom_boot() {
  require_once DRUPAL_ROOT . '/includes/password.inc';
 
  $exception_path = "/url_required_to_bypass_passlock";
 
  // Allow Paypal callback through
  if ($_SERVER["REQUEST_URI"] == $exception_path)
    return;
 
  // Allow logged in user through
  if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $query = "SELECT pass FROM {users} WHERE name = :name";
    $result = db_query($query, array(':name' => $_SERVER['PHP_AUTH_USER']));
    $account = new stdClass();
    foreach ($result as $row) {
      $account->pass = $row->pass;
    }
    if (isset($account->pass)) {
      if (user_check_password($_SERVER['PHP_AUTH_PW'], $account)) {
        return;
      }
    }
  }
 
  // Allow cron through
  if (basename($_SERVER['PHP_SELF']) == 'cron.php')
    return;
 
  // Allow PHP CLI/Drush through
  if (isset($_SERVER['argc'])) {
    if (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0))
      return;
  }
 
  header('WWW-Authenticate: Basic realm="Development"');
  header('HTTP/1.0 401 Unauthorized');
  exit;
}
Drupal Version:
Posted: Jun 17th, 2013
Tags: year, date, select options, key values
Rating:
0
No votes yet
2010|2010
2009|2009
2008|2008
2007|2007
2006|2006
2005|2005
2004|2004
2003|2003
2002|2002
2001|2001
2000|2000
1999|1999
1998|1998
1997|1997
1996|1996
1995|1995
1994|1994
1993|1993
1992|1992
1991|1991
1990|1990
1989|1989
1988|1988
1987|1987
1986|1986
1985|1985
1984|1984
1983|1983
1982|1982
1981|1981
1980|1980
1979|1979
1978|1978
1977|1977
1976|1976
1975|1975
1974|1974
1973|1973
1972|1972
1971|1971
1970|1970
1969|1969
1968|1968
1967|1967
1966|1966
1965|1965
1964|1964
1963|1963
1962|1962
1961|1961
1960|1960
1959|1959
1958|1958
1957|1957
1956|1956
1955|1955
1954|1954
1953|1953
1952|1952
1951|1951
1950|1950
1949|1949
1948|1948
1947|1947
1946|1946
1945|1945
1944|1944
1943|1943
1942|1942
1941|1941
1940|1940
1939|1939
1938|1938
1937|1937
1936|1936
1935|1935
1934|1934
1933|1933
1932|1932
1931|1931
1930|1930
1929|1929
1928|1928
1927|1927
1926|1926
1925|1925
Drupal Version: 7.x
Posted: Apr 23rd, 2013
Tags: ajax, views, ajax_views
Rating:
0
No votes yet
/**
 * js file
 */
 
(function ($) {
  /* this code stole from ajax_view.js , just use this to override the ajax path */
  if (Drupal.views != undefined) {
    Drupal.views.ajaxView.prototype.attachPagerLinkAjax = function(id, link) {
      var $link = $(link);
      var viewData = {};
      var href = $link.attr('href');
      $.extend(
        viewData,
        this.settings,
        Drupal.Views.parseQueryString(href),
        Drupal.Views.parseViewArgs(href, this.settings.view_base_path)
      );
      $.extend(viewData, Drupal.Views.parseViewArgs(href, this.settings.view_base_path));
 
      this.element_settings.submit = viewData;
      if (this.element_settings.submit['view_name'] == 'yourviewname') {  //if viewname matched
        this.element_settings.url = '/result_ajax';  //change views/ajax to your ajax path
        var query = $('#modulename-ajax-compare-result-form').serialize();  //add any data you want to pass before ajax call
        this.element_settings.submit['data'] = query;
      }
      this.pagerAjax = new Drupal.ajax(false, $link, this.element_settings);
    };
  }
})
Drupal Version: 7.x
Posted: Apr 23rd, 2013
Tags: views api, add_item, views query alter
Rating:
0
No votes yet
/**
 * Add filters programmatically.
 */
function modulename_views_page() {
  $display_id = 'viewname-block_3';
  $nodeblock = array($display_id);
  $block = block_load('views', 'viewname-block_3');
  $block->subject = "";
  $views = views_get_view ('viewname');
  $views->set_display('block_3');
  $views->set_arguments(array('nid')); 
  if (!empty($_GET['delta'])) {
    $views->add_item('block_3', 'filter', 'field_data_field_fieldname', 'delta', array('value' => array('value' => $_GET['delta']), 'operator' => '=','relationship' => 'none', 'group_type' => 'group','group' => 1 ));
  }
 
  if ($_GET['color']) {  //filter taxonomy
    $views->add_item('block', 'filter', 'field_data_field_color', 'field_color_tid', array('relationship' => 'field_product_product_id', 'value' => $color));
  }
  //order by price
  $views->add_item('block_3', 'sort', 'field_data_commerce_price', 'commerce_price_amount', array('relationship' => 'field_product_product_id', 'order' => 'asc'));
  $views->set_current_page($_GET['page']); //set page number
  $views->pre_execute();
  $block = $views->display_handler->execute();
  $views->post_execute();
  views_add_block_contextual_links($block, $views, 'block'); //add views contextual link
  $nodeblock[$display_id] = $block['content'];
  $nodeblock[$display_id]['#block'] = $block;
  $nodeblock[$display_id]['#theme_wrappers'] = array('block');
  $nodeblock['#sort'] = TRUE;
  $nodeblock = drupal_render($nodeblock); //theme as block
  $output = $nodeblock;
  return $output;
}
 
/**
 * Add filters programmatically.
 */
function modulename_views_query_alter(&$view, &$query) {
  if ($view->base_table == 'node' && $view->name == 'views_display_id_here') {
    $join = new views_join();
    $join->table = 'field_data_field_dummy';
    $join->field = 'entity_id';
    $join->left_table = 'node';
    $join->left_field = 'nid';
    $join->type = 'left';
    $query->add_relationship('field_data_field_dummy', $join, 'field_data_field_dummy');
    $query->where[$c]['conditions'][] = array(
        'field' => 'field_data_field_dummy.field_field_dummy_value',
        'value' => '1234',
        'operator' => '=',
        );
    $query->where[$c]['conditions'][] = array(
        'field' => 'field_data_field_dummy.field_data_field_dummy_value',
        'value' => '',
        'operator' => 'is null'
        );
    $query->where[$c]['type'] = 'OR';
    $query->where[$c]['args'] = array();
  }
}
Drupal Version: 7.x
Posted: Apr 22nd, 2013
Tags: block
Rating:
0
No votes yet
/**
 * store default variables in code
 */
function modulename_block_content ($delta) {
  $data =  array (
    'nodeblock_en_title' => 'xxxxxxxx',
    'nodeblock_en_link' => 'xxxxxxxx',
    'nodeblock_en_image' => 'xxxx.png',
    'nodeblock_en_content' => 'xxxxxxxx',
    'nodeblock_en_more' => 'xxxxxxxx',
    'nodeblock_zh-hans_title' => 'xxxxxxxx',
    'nodeblock_zh-hans_link' => 'xxxxxxxx',
    'nodeblock_zh-hans_image' => 'xxxxxxxx',
    'nodeblock_zh-hans_content' => 'xxxxxxxx',
    'nodeblock_zh-hans_more' => 'xxxxxxxx',
  );
}
 
 
/**
 * define your blocks
 */
function modulename_block_info() {
  foreach ($i=0; $i <= 10 ; $i++ ) {
    $blocks['nodeblock' . $i] = array(
      'info' => t('nodeblock' . $i),
      'cache' => DRUPAL_NO_CACHE,
    );
  }
}
 
/**
 * block content output here
 */
function modulename_block_view($delta = '') {
  $block = array();
  global $language;
  $lang_id = $language->language;
  foreach ($i=0; $i < 10 ; $i++ ) {
    if ($delta == 'nodeblock' .$i) {
    $image = variable_get("nodeblock_image_" . $lang_id, '');
    if (!empty($image)) {
      $file = file_load($image);
      $presetname = 'thumbnail';
      $src = $file->uri; 
      $dst = image_style_path($presetname, $src); 
 
      if(!file_exists($dst)) {
        image_style_create_derivative(image_style_load($presetname), $src, $dst);
      }
      $background = file_create_url ($dst);
    }
    else {
      $background = modulename_block_content('nodeblock_image_' . $lang_id);
    }
    $output = '<div class="banner" style="background:url(\'' . $background . '\')"></div><div class="content">';
    $output .= '<h3 class="bannertitle"><a href="' . variable_get("nodeblock' . $i . '_link_" . $lang_id, modulename_block_content('nodeblock' . $i . '_link_' . $lang_id)) . '">' . variable_get("nodeblock' . $i . '_title_" . $lang_id, modulename_block_content('nodeblock' . $i . '_title_' . $lang_id)) . '</a></h3>
  <div class="bannerbody">' . variable_get("nodeblock_content_" . $lang_id, modulename_block_content('nodeblock_content_' . $lang_id)) . '</div>';
    $output .= l(t('SEE MORE'), variable_get("nodeblock' . $i . '_more_" . $lang_id, modulename_block_content('nodeblock_more_' . $lang_id)));
    $output .= '</div>';
    $block['content'] = $output;
  }
}
 
 
/**
 * save variables
 */
function modulename_block_save ($delta, $edit) {
  global $language;
  $lang_id = $language->language;
  for($i=1; $i < 10; $i++) {
    if ($delta == 'nodeblock' . $i) {
      if ($edit['nodeblock' . $i . '_revert']) {
        variable_del('nodeblock' . $i . '_title_' . $lang_id);
        variable_del('nodeblock' . $i . '_image_' . $lang_id);
        variable_del('nodeblock' . $i . '_content_' . $lang_id);
        variable_del('nodeblock' . $i . '_link_' . $lang_id);
        variable_del('nodeblock' . $i . '_more_' . $lang_id);
      }
      else {
        variable_set('nodeblock' . $i . '_title_' . $lang_id, $edit['nodeblock' . $i . '_title']);
        variable_set('nodeblock' . $i . '_image_' . $lang_id, $edit['nodeblock' . $i . '_image']);
        variable_set('nodeblock' . $i . '_content_' . $lang_id, $edit['nodeblock' . $i . '_content']['value']);
        variable_set('nodeblock' . $i . '_link_' . $lang_id, $edit['nodeblock' . $i . '_link']['value']);
        variable_set('nodeblock' . $i . '_more_' . $lang_id, $edit['nodeblock' . $i . '_more']['value']);
      }
    }
  }
}
 
 
 
 
function ediamonds_block_configure($delta) {
  global $language;
  $lang_id = $language->language;
  $form = array();
  $block_arr = array (
    'nodeblock1' => array('dimension' => '283 x 141px','nomore' => 1),
    'nodeblock2' => array('dimension' => '283 x 141px'),
    'nodeblock3' => array('dimension' => '283 x 141px'),
    'nodeblock4' => array('dimension' => '283 x 141px'),
    'nodeblock5' => array('dimension' => '283 x 141px'),
    'nodeblock6' => array('dimension' => '283 x 141px'),
    'nodeblock7' => array('dimension' => '237 x 264px', 'notitle' => 1, 'nocontent' =>1 , 'nomore' => 1),
    'nodeblock8' => array('dimension' => '237 x 264px', 'notitle' => 1, 'nocontent' =>1 , 'nomore' => 1),
  );
 
  if ( !empty($block_arr[$delta])) {
    if (empty($block_arr[$delta]['notitle'])) {
      $form[$delta . '_title'] = array(
        '#type' => 'textfield',
        '#title' => 'Title',
        '#default_value' => variable_get($delta . '_title_' . $lang_id, ediamonds_block_content($delta . '_title_' . $lang_id)),
      );
    }
    if (empty($block_arr[$delta]['nolink'])) {
      $form[$delta . '_link'] = array(
        '#type' => 'textfield',
        '#title' => t('title link'),
        '#default_value' => variable_get($delta . '_link_' . $lang_id, ediamonds_block_content($delta . '_link_' . $lang_id)),
      );
    }
    if (empty($block_arr[$delta]['nocontent'])) {
      $form[$delta . '_content'] = array(
        '#type' => 'text_format',
        '#title' => 'Content',
        '#default_value' => variable_get($delta . '_content_' . $lang_id, ediamonds_block_content($delta . '_content_' . $lang_id)),
      );
    }
    if (empty($block_arr[$delta]['noimage'])) {
      $form[$delta . '_image'] = array(
        '#type' => 'managed_file',
        '#title' => 'Image',
        '#description' => t('dimension w x h:') . $block_arr[$delta]['dimension'],
        '#default_value' => variable_get($delta . '_image_' . $lang_id, ''),
        '#upload_location' => 'public://'
      );
    }
    if (empty($block_arr[$delta]['nomore'])) {
      $form[$delta . '_more'] = array(
        '#type' => 'textfield',
        '#title' => 'More link',
        '#default_value' => variable_get($delta . '_more_' . $lang_id, ediamonds_block_content($delta . '_more_' . $lang_id)),
      );
    }
    $form[$delta . '_revert'] = array (
      '#type' => 'checkbox',
      '#title' => t('REVERT TO DEFAULT VALUE')
    );
  };
}
 
 
/**
 * print your block
 */
$nodeblock1 = block_load('modulename', 'nodeblock1');
$nodeblock1 = _block_get_renderable_array(_block_render_blocks(array($nodeblock1)));
$nodeblock1 = drupal_render($nodeblock1);
print $nodeblock1;
Drupal Version: 7.x
Posted: Feb 9th, 2013
Tags: salesforce
Rating:
0
No votes yet
/*  
require enable salesforce.module
*/
 
//custom function
function _get_data($queryString){
	$sfapi = rfg_salesforce_api_connect();		
 
	$results = $sfapi->query(urlencode($queryString));  
 
	$data = array();	
	foreach($results['records'] as $record){
			$data[] = $record;
	}	
return $data;
}
 
//get client name on Lead
$query = "SELECT Name FROM Lead WHERE Email='[email protected]' AND LeadSource='something'";
$data = _get_data($query);
$name = $data[0]['Name'];
print $name;
Drupal Version: 7.x
Posted: Feb 9th, 2013
Tags: search index
Rating:
0
No votes yet
/*  
using rule
Eventa:  'After saving new content'
Actions: 'Execute custom PHP code'
*/
 
 
//custom PHP code
 
drupal_register_shutdown_function('search_update_totals');
_node_index_node($node);
Drupal Version: 7.x
Posted: Feb 7th, 2013
Tags: export csv, VBO
Rating:
0
No votes yet
function modulenameaction_info() {
    'modulenameexport_action' => array(
      'type' => 'user',
      'label' => t('Export User operations'),
      'configurable' => FALSE,
      'aggregate' => TRUE, //see modulenameexport_action param $users
      'triggers' => array('user_update'),
    ),
  );
}
 
function modulenameviews_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
  if ($form_state['step'] == 'views_bulk_operations_confirm_form' && $form_state['operation']->operationId == 'action::modulenameexport_action') {
    $form['actions']['submit']['#value'] = 'Export these users';
    $form['actions']['cancel']['#title'] = 'Exit';
  }
}  
 
function modulenameexport_action(&$users, $context = array()) {
  modulenameexport_bs_data($users);
}
 
function modulenameexport_bs_data($users) {
  $count = 0;
  $data = array();
  foreach ($users as $user) {
    $data[$count][] = $user->uid;
    $data[$count][] = $user->mail;
    $data[$count][] = empty($user->field_xxx[LANGUAGE_NONE][0]['value'])?"":$user->field_xxx[LANGUAGE_NONE][0]['value'];
    // multiple values
    $loc_str = '';
    if (!empty($user->field_location[LANGUAGE_NONE])) {
      foreach ($user->field_location[LANGUAGE_NONE] as $loc_key => $loc_val) {
        $loc_arr[] = $loc_val['postal_code'] . ' ' . $loc_val['street']  . ' ' . $loc_val['city'] . ' ' . $loc_val['province'] . ' ' . $loc_val['country'];
      }
      if (!empty($loc_arr)) {
        $loc_str = implode (' | ', $loc_arr);
      }
    }
    $data[$count][] = $loc_str;
    $count++;
  }
 
  $header = array('uid','field xxx','multiple values location string');
  $output ='';
  foreach($header as $k => $v) {
    $output .= $v.',';
  }
  $output .= "\r\n";
 
  for($i=0 ; $i<count($data);$i++) {
    foreach($data[$i] as $k => $v) {
      $output .= str_replace(array("\r\n","\n\r", "\r", "\n" ,"\t","\"","'" ,","), ' ',$v) . ',';
    }
    $output .= "\r\n";
  }
  $filename =  'bs_data_export' . time() . '.csv';
 
  header('Content-type: text/csv;charset=utf-8');
  header('Content-disposition: attachment; filename='.$filename);
  echo "\xEF\xBB\xBF".$output;
  exit;
}
Drupal Version: 7.x
Posted: Feb 4th, 2013
Tags: ajax without form, ajax links
Rating:
0
No votes yet
function modulename_menu() {
  $items['modulename_ajax'] = array(
    'page callback' => 'modulename_searchfunction_ajax',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}
function modulename_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'book') {
    $body = field_get_items ('node', $node, 'body');
    $code = $body[0]['value'];
    $pattern = '/function[\s\n]+(\S+)[\s\n]*\(/';
 
     if (preg_match_all ($pattern, $code, $matches)) {
       $function_name = $matches[1];
     }
  }
 
  if (!empty($function_name)) {
    foreach($function_name as $fun_key => $fun_value) {
      $link = array(
        '#type' => 'link',
        '#title' => $fun_value,
        '#href' => 'modulename_ajax/nojs/' . $fun_value,
        '#suffix' => '<div id="ak"></div>',
        '#ajax' => array(),
      );
      $node->content['function_name'][] = $link;
    }
  }
}
 
function modulename_searchfunction_ajax($type = 'ajax', $term = '') {
  if ($type == 'ajax') {
    $view = views_get_view('search');
    $view->set_display ('block_1');
    $view->set_arguments(array(check_plain($term)));
    $output = $view->render();
    $commands = array();
    $commands[] = ajax_command_replace ('#ak', $output);
    $page = array (
      '#type' => 'ajax',
      '#commands' => $commands,
    );
    ajax_deliver($page);
  }
  else {
    $output = t("This is some content delivered via a page load.");
    return $output;
  }
}
Drupal Version: 7.x
Posted: Feb 4th, 2013
Tags: VBO, views bulk operations, userpoints
Rating:
0
No votes yet
function modulename_action_info() {
  return array(
    'modulename_adduserpoint_action' => array(
      'type' => 'user',
      'label' => t('userpoint operations'),
      'configurable' => TRUE,
      'triggers' => array('user_update'),
    ),
  );
}
 
function modulename_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
  if ($form_state['step'] == 'views_bulk_operations_confirm_form' && $form_state['operation']->operationId == 'action::modulename_adduserpoint_action') {
    $form['desc'] = array (
      '#markup' => 'Action : Add userpoints ' . $form_state['operation']->formOptions['add_userpoint'] ,
    );
  }
}
 
function modulename_adduserpoint_action_form ($context) {
  $options = array();
  $options = array (
    'add' => 'Add userpoint',
    'substract' => 'Substract userpoint',
    'modifiy' => 'Fixed value'
  );
  $form['userpoint_operations'] = array (
    '#type' => 'select',
    '#required' => true,
    '#options' => $options,
  );
  $form['modulename_adduserpoint'] = array (
    '#type' => 'textfield',
    '#required' => true,
    '#title' => 'Userpoints value',
  );
  return $form;
}
 
function modulename_adduserpoint_action_submit ($form, $form_state) {
  return array (
    'add_userpoint' => check_plain($form_state['values']['modulename_adduserpoint'])
  );
}
 
function modulename_adduserpoint_action(&$user, $context = array()) {
  if (is_numeric ($user->uid)) {
    userpoints_userpointsapi(
      array(
        'uid' => $user->uid,
        'points' => $context['add_userpoint'],
        'moderate' => variable_get('userpoints_votingapi_moderation', 0),
        'event' => 'coupon',
        'entity_id' => $user->uid, 
        'entity_type' => 'user',
        'operation' => t('Add userpoint'),    
        'tid' => variable_get('userpoints_votingapi_tid', 0),  
        'description' => t('Add userpoint: !entity_type !entity_id.', array('!entity_type' => 'user', '!entity_id' => $user->uid)),    
      )
    );
  }
}
Drupal Version: 7.x
Posted: Feb 2nd, 2013
Tags: security, valid token
Rating:
0
No votes yet
/**
 * create a link with token.
 */
$valid_token= drupal_get_token('checktoken');
$link = l('checktoken', 'Link', array('query' => array('token', $valid_token));
echo $link;
 
modulename_menu() {
  $items['checktoken'] = array(
    'page callback' => 'modulename_checktoken',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );  
}
 
modulename_checktoken() {
  $token = empty($_GET['token'])?"":$_GET['token'];
  $valid = drupal_valid_token($token, 'checktoken');
  if ($valid) {
    dsm ('This is local site request');
  }
  else {
    dsm ('This is external site request');
    drupal_access_denied();
  }
}
Drupal Version: 7.x
Posted: Feb 2nd, 2013
Tags: ajax, drupal way, ajax framework, ajax_command
Rating:
0
No votes yet
function modulename_crm_form($form , $form_state) {
  $form['notes'] = array (
    '#type' => 'textarea',
    '#title' => 'Notes',
  );
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Add a note'),
    '#ajax' => array(
      'callback' => 'modulename_crm_ajaxcallback',
      'wrapper' => 'modulename-crm-form',
       'method' => 'replace',
    ),
  );
  return $form;
}
function modulename_crm_ajaxcallback($form, $form_state) {
  $values = $form_state['values'];
  /* do your logic here , example : save a node */
  $commands = array();
  $commands[] = ajax_command_invoke(NULL, 'crm_view_ajax', array($uid) );  //Drupal ajax framework api
  return array(
    '#type' => 'ajax',
    '#commands' => $commands
  );
}
 
/* js */
(function ($) {
  $.fn.crm_view_ajax = function() {
    alert('Do something here');
  }
})(jQuery);
Drupal Version: 6.x
Posted: Feb 2nd, 2013
Tags: custom import, node import
Rating:
0
No votes yet
/* Just a sample script on node import */
<?php
  define('DRUPAL_ROOT', getcwd());
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
 
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  setlocale(LC_ALL, 'zh_TW.utf8');
 
function fetch_remote_image($url) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  $data = curl_exec($ch);
  curl_close($ch);
  if ($data) {
    if (file_save_data($data, '/'.$filename, TRUE)) {
      return $filepath;
    }
  }
}
 
$filename = "./data.csv";
$log_filename = "./log.log";
global $user;
$log = file_get_contents($log_filename);
 
if (!empty($name) && ($handle = fopen($name, "r")) !== FALSE) {
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    foreach($data as $k => $v) {
      switch ($k) {
        case 0:  //Add node or Update node ?
          if (empty($v)) {
            $node = (object) array(
              'uid' => $user->uid,
              'name' => (isset($user->name) ? $user->name : ''),
              'language' => LANGUAGE_NONE,
              'type' => 'nodetype'
            );
          }
          else {
            $node = node_load($v);
          }
          break;
        case 1:  //node title
          $node->title = $v;
          break;
        case 2:  //node body
          $node->body[LANGUAGE_NONE][0]['value'] = $v;
          break;
        case 3:  //add taxonomy ?
          $term = taxonomy_get_term($v);
          if (!empty($term)) {
            $node->field_taxonomy[0]['value'] = $term->tid;
            $node->taxonomy = array();
            $node->taxonomy[$term->tid] = $term;
          }
          else {
            //create taxonomy
          }
        break;
        case 4: //multiple field ?
          $data = explode(',', $v);
          if (!empty($data)) {
            foreach ($data as $data_key => $data_val) {
              $node->field_multiplefieldname[LANGUAGE_NONE][$data_key]['value'] = $data_val;
            }
          }
        break;
        case 5: //image field ?
          $path = fetch_remote_image($v);
          if (!empty($path)) {
            $file = field_file_save_file($path);
            $node->field_images[] = $file;
          }
        break;
      }
    }
    node_save($node);
    if ($node->nid) {
      $log .= $node->nid . ' : ' . $node->title .'\n';
    }
  }
file_put_contents($file, $log);
exit;
?>
Drupal Version: 7.x
Posted: Jan 30th, 2013
Tags: mail edit, tokens, HTML mail
Rating:
0
No votes yet
function modulename_mailkeys() {
    return array(
      'modulename_category_mail' => t('email alert'),
    );
  return NULL;
}
 
function modulename_mail_edit_text($mailkey, $language) {
  global $base_url;
  $message = array();
  switch ($mailkey) {
    case 'modulename_category_mail':
      $message['subject'] = 'A node is created [node:title]';
      $message['body'] = 'node link:[node:url], your selected category : [modulename:maincat]';
    break;
  }
  return $message;
}
 
function modulename_mail_edit_token_types($mailkey) {
  return array('modulename', 'node');
}
 
function modulename_token_info() {
 $type = array(
    'name' => t('modulename'),
    'description' => t('Tokens from modulename module.'),
  );
  return array(
    'types' => array('modulename' => $type),
    'tokens' => array('modulename' => $obj),
  );
}
 
function modulename_token_list($type) {
  $tokens = array();
  if ($type == 'modulename') {
    $tokens['maincat'] = array(
      'maincat' => t('Main category'),
    );
  }
}
 
function modulename_tokens($type, $tokens, $data = array(), options = array()) {
  $values = array();
  foreach ($tokens as $tokens_key => $tokens_val) {
    if ($type == 'modulename') {
      switch ($tokens_key) {
        case "maincat":
          $values[$tokens_val] = $data['modulename']['maincat'];
        break;
      }
    }
  }
  return $values;
}
 
function modulename_sendmail() {
  $maincat = 'cat1';
  $subcat = 'cat2';
  $module = 'modulename';
  $key = 'modulename_category_mail';
  $language = language_default();
  $params['modulename'] = array('maincat' => $maincat);
  $from = NULL;
  $send = TRUE;
  $email = variable_get('site_mail', ''); //send to
  drupal_mail($module, $key, $email, $language, $params, $from, $send);
}
 
/**
 * Send HTML Mail
 * You need *mailsystem, *HTML Mail module enabled.
 * 1. goto admin/config/system/mailsystem
 * 2. Add new setting, select modulename, input "Key" as "modulename_category_mail"
 * 3. After save, "modulename_category_mail" selects HTMLMailSystem
 */
Drupal Version: 7.x
Posted: Jan 25th, 2013
Tags: views
Rating:
0
No votes yet
/*    method 1   */
global $user;
$arg1 = $user->uid;
$arg2 = 1; // may be nid .. the second Contextual Filter argument
print views_embed_view('view_name', 'display_id', $arg1, $arg2);
 
/*    method 2   */
$view = views_get_view('view_name');
$view->set_display('display_id');
$args = array($arg1, $arg2);
$view->set_arguments($args);
$view->pre_execute();
print $view->render(); 
Drupal Version: 6.x
Posted: Jan 9th, 2013
Tags: First time login
Rating:
0
No votes yet
/**
 * Implementation of hook_user
 */
function modulename_user ($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'insert':
      $edit['first_time_login'] = 1;
      break;
    case 'login':
      $data = unserialize($account->data);
      if ($data['first_time_login']) {
        user_save($account, array('first_time_login' => 0));
        drupal_set_message (t('This is your first time login.'));
      }
      break;
  }
}
Drupal Version: 6.x
Posted: Dec 11th, 2012
Tags: external images, field_file_save_file, multiple images
Rating:
0
No votes yet
<?php
function modulename_get_remote_image($url) {
if (!$url) return FALSE;
if (preg_match('/([^\/]+)$/', $url, $matches)) {
$filename = $matches[1];
}
else{
return FALSE;
}
 
$filepath = file_directory_path().'/'.$filename;
if (file_exists($filepath))
return $filepath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
if ($data) {
if (file_save_data($data, '/'.$filename, TRUE))//replace
  return $filepath;
}
}
 
 url = 'http://www.xxx.com/xxx.jpg';
url2 = 'http://www.xxx.com/xxx2.jpg';
 $path = modulename_get_remote_image($url);
 $file = field_file_save_file($path);
 $path = modulename_get_remote_image($url);
 $file2 = field_file_save_file($path);
 
 $node->field_images[] = $file;
 $node->field_images[] = $file2;
node_save($node);
 
?>
Drupal Version: 7.x
Posted: Dec 10th, 2012
Tags: jquery ui, dialog
Rating:
0
No votes yet
 <?php
 jquery_ui_add('ui.dialog');
  drupal_add_js('$(document).ready(function(){
$("body").after("<div id=\'dialog\'></div>");
$('#dialog').dialog({autoOpen: false,draggable:true,width:500,modal: true,title: "title"});});', 'inline');
  $path = jquery_ui_get_path();
  drupal_add_css($path . '/themes/base/ui.all.css');
?>
 
 
  /* call dialog box with custom message */
  $('#dialog').text('Your message here').dialog('open');
Drupal Version: 6.x
Posted: Dec 6th, 2012
Tags: token
Rating:
0
No votes yet
function modulename_tokentest() {
  $text = 'simple text with [token-use1] , [token-use2]';
  $node = node_load(123);
  $token2 = node_load(234);
  $text = token_replace_multiple($text, array('node' => $node , 'token2' => $token2));
  dsm($text); //output : simple text with 123 , 234
}
 
function modulename_token_list($type) {
  $tokens = array();
  if ($type == 'node') {
    $tokens['node'] = array(
      'token-use1' => t('token description here.'),
    );
  }
}
function module_token_values($type = 'all', $object = NULL) {
  if ($type == 'node') {
    $values['token-use1'] = $object->nid; // $object->nid = 123
  }
  elseif ($type == 'token2') {
    $values['token-use2'] = $object->nid; // $object->nid = 234
  }
  return $values;
}
Drupal Version: 7.x
Posted: Dec 4th, 2012
Tags: input filter
Rating:
0
No votes yet
function modulename_node_form_after_build(&$form) {
   $form['body'][LANGUAGE_NONE][0]['format']['format']['#value'] = 'full_html';
   $form['body'][LANGUAGE_NONE][0]['format']['#attributes']['style'] = 'display:none';
  return $form;
}
 
function modulename_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'article_node_form') {
    $form['#after_build'][] = 'modulename_node_form_after_build';   
  }
}
Drupal Version: 7.x
Posted: Dec 3rd, 2012
Tags: form alter, custom search default text
Rating:
0
No votes yet
<?php
function YOURthemeORmodule_form_search_block_form_alter(&$form, &$form_state, $form_id) {
 $form['search_block_form']['#default_value'] = t('your default text');     
 $form['search_block_form']['#attributes'] = array('class' => array('your_class'), 
                                                              'onfocus' => "if (this.value == '". t('your default text'). "') {this.value = '';}",
                                                              'onblur' => "if (this.value == '') {this.value = '". t('your default text'). "';}"); 
 
}
?>
Drupal Version: 7.x
Posted: Dec 2nd, 2012
Tags: gmap, jquery ui tabs
Rating:
0
No votes yet
        $(".ui-tabs-anchor").live("click", function() {
          $("div.gmap-gmap").each(function(i,e){
          var id = $(this).attr("id");
          var idArr = id.split("-");
          var mapId = idArr[1];
          var mapObj = Drupal.gmap.getMap(mapId);
          google.maps.event.trigger(mapObj.map,"resize");
          var myLatLng = new google.maps.LatLng(mapObj.map.markers[0].position.$a, mapObj.map.markers[0].position.ab);
          mapObj.map.setCenter(myLatLng);
          })
        })
Drupal Version: 7.x
Posted: Dec 1st, 2012
Tags: getlocations, google.map, jquery ui tabs, profile2, multiple profile2
Rating:
0
No votes yet
  //we need profile2 + field_group + field_multiple + getlocations modules
  drupal_add_css("http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css", array('type' => 'external'));
   drupal_add_js("http://code.jquery.com/ui/1.9.2/jquery-ui.js");
 
    drupal_add_js( '
    $= jQuery;
    $(document).ready(function() {
      $(".ui-tabs-anchor").live("click", function() {
        $.each(Drupal.settings.getlocations_fields, function (key, settings) {
          if(getlocations_map[key] != undefined) {
             google.maps.event.trigger(getlocations_map[key], "resize");   // this will fix google map display problem
           }
        })
      })
    function tabme() {   //create ul list for jquery ui tabs
      window.tabstr = "<ul>";
      $(".field-group-multiple .multiple-inline-element").each(function(i,e) {
        var tabname = "tabs-"+i;
        $(this).attr("id", tabname);
        window.tabstr += "<li><a href=\'#" + tabname + "\'>" + "Profile" + (i+1) + "</a></li>";
      })
      window.tabstr += "</ul>";
      $(".field-group-multiple").prepend(window.tabstr);
      $(".field-group-multiple").tabs();
      getlocations_init();   //reinitialize map display , see getlocations.js
      getlocations_fields_init();  //reinitialize geocoder , see getlocations_fields.js
      Drupal.attachBehaviors(document);
  }
    $("body").ajaxComplete(function(event,request, settings){
      if(settings.context.extraData._triggering_element_value != undefined && settings.context.extraData._triggering_element_value  == "Add another item") {  // while mulitiple profile add more button is clicked
        tabme();
      }
    });
    tabme();
  });
   ', 'inline');
Drupal Version: 7.x
Posted: Nov 28th, 2012
Tags: autosubmit, ajaxcomplete
Rating:
0
No votes yet
// upload complete event 
Drupal.behaviors.fileUpload = {  
  attach: function(context, settings) {
    jQuery("body").ajaxComplete(function(event,request, settings){
      if (form_build_id = settings.url.match(/file\/ajax\/uploadcoupon\d*\/(.*)$/)) {
        if(jQuery('[value="'+form_build_id[1]+'"]').closest('form').find('[id$=remove-button]').length) {
          jQuery('[value="'+form_build_id[1]+'"]').closest('form').find('[id^=edit-submit]').click();  //trigger form submit
        }
      }
    })
  }
}
Drupal Version: 7.x
Posted: Nov 22nd, 2012
Tags: feeds, multiple images, feed tamper
Rating:
0
No votes yet
Use Feeds , Feeds Tamper to import field with multiple values
use sql to group multiple value with separator "|"
multiple values field will look like this
xxx|xxx|xxx
SELECT p.program_id , GROUP_CONCAT(i.img_url SEPARATOR '|') as uri , GROUP_CONCAT(i.img_caption SEPARATOR '|') as title FROM event as p left join images as i on p.program_id = i.ref_id group by p.event_id order by p.event_id limit 0,2000
 
Feed Tamper > set the field with multiple values with "explode" rule with "|" as separator.
 
to import image with title description , alt description
csv will look like this
img path           img title           img alt
xxx|xxx|xxx      xxx|xxx|xxx     xxx|xxx|xxx
Drupal Version: 7.x
Posted: Nov 22nd, 2012
Tags: generate imagecache on the fly, image_style, create imagecache
Rating:
0
No votes yet
<?php
/** drupal 7 **/
$presetname = '800x421'; //presetname
$src = $image->uri; 
$dst = image_style_path($presetname, $src); //create image uri
if(!file_exists($dst)) {
  image_style_create_derivative(image_style_load($presetname), $src, $dst)); // create imagecache 
}
/** drupal 6 **/
$presetname = '800x421';
$preset = imagecache_preset_by_name($presetname);
$src = $image["filepath"];
$dst = imagecache_create_path($presetname, $src);
if(!file_exists($dst)) {
 imagecache_build_derivative($preset['actions'], $src, $dst)) ;
}
?>
Drupal Version: n/a
Posted: Nov 20th, 2012
Tags: jsonp
Rating:
0
No votes yet
function crossript(nid) {
  var urlto = "http://www.xxx.com/xxx.php?url=http://www.xxx.com/" + nid;
  $.ajax({
    url:urlto, 
    dataType:"jsonp",
    jsonp : "callback",
    success:function(data){
     console.log(data.message);
    }
  })
}
/***** php ****/
<?php
 header("content-type: application/json"); 
$url = $_GET['url'];
$obj = new stdClass;
$obj->message = $result;
echo $_GET['callback']. '('. json_encode($obj) . ')';  
?>
Drupal Version: 7.x
Posted: Nov 20th, 2012
Tags: external image
Rating:
0
No votes yet
   $image = file_get_contents('http://www.xxxx.com/xxx.png');  
   $file = file_save_data($image, 'public://' . filename ,FILE_EXISTS_REPLACE); 
   $node->field_image[LANGUAGE_NONE]['0']['fid'] = $file->fid; // save image into node field
 
/***************/
$option = array('method' => 'post');
$result = drupal_http_request('http://www.xxxx.com/xxx.png', $option);
if ($result->code == 200) {
  print $result -> data; //display 
}
Drupal Version: 7.x
Posted: Nov 19th, 2012
Tags: call add node form
Rating:
0
No votes yet
<?php
function create_node_form(){
module_load_include('inc', 'node', 'node.pages'); 
 
  global $user;
  $type = 'content_type_name';
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE,
	'field_name' => array('und' => array(0 => array('value' => 'default_value'),),),  
  );
 
  drupal_set_title(t('Create New Content'), PASS_THROUGH);
  $output = render(drupal_get_form($type . '_node_form', $node));
 
  return $output;
}
 
?>
 
 
//call add node form 
<?php
  print create_node_form();
?>
Drupal Version: 7.x
Posted: Nov 17th, 2012
Tags: wysiwyg, ckeditor, autogrow, extraplugin
Rating:
0
No votes yet
function modulename_wysiwyg_editor_settings_alter(&$settings, &$context) {
  if ($context['profile']->editor == 'ckeditor') {
     if (!empty($settings['extraPlugins'])) {
       $settings['extraPlugins'] .= ',autogrow';
     }
     else {
       $settings['extraPlugins'] .= 'autogrow';
     }
     $settings['resize_enabled'] = FALSE;
     $settings['autoGrow_maxHeight'] = 500;
  }
}
Drupal Version: 7.x
Posted: Nov 16th, 2012
Tags: custom theme, node type
Rating:
0
No votes yet
function modulename_menu_alter(&$items) {
  $items['node/%node/edit']['theme callback'] = 'jungle_edit_node_theme';
  $items['node/%node/edit']['theme arguments'] = array(1);
}
/**
 * return custom theme for article
 */
function modulename_edit_node_theme($node) {
  if ($node->type == 'article') {
    return 'themename';
  }
  else {
    modulename_default_node_theme();
  }
}
 
/**
 * default theme  
 */
function modulename_default_node_theme() {
  return 'seven';
}
Drupal Version: 7.x
Posted: Nov 16th, 2012
Tags: permission, restrict access
Rating:
0
No votes yet
function modulename_permission() {
  $permissions = array(
    'administer recurly' => array(
      'title' => t('Administer Recurly'),
      'restrict access' => TRUE, // OPTIONAL : set TRUE to display "Warning: Give to trusted roles only; this permission has security implications." 
      )
  )
}
Drupal Version:
Posted: Nov 15th, 2012
Tags: facebook share
Rating:
0
No votes yet
<?php
        $title=urlencode('Title of Your iFrame Tab');
	$url=urlencode('http://www.facebook.com/yourfanpage');
	$summary=urlencode('Custom message that summarizes what your tab is about, or just a simple message to tell people to check out your tab.');
	$image=urlencode('http://www.yourdomain.com/images/share-thumbnail.jpg');
?> 
<a onClick="window.open('http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo $title;?>&amp;p[summary]=<?php echo $summary;?>&amp;p[url]=<?php echo $url; ?>&amp;&amp;p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=548,height=325');" href="javascript: void(0)">Insert text or an image here.</a>
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: add thumbnail in search result
Rating:
5
Average: 5 (1 vote)
function modulename_preprocess_search_result(&$variables) {
  switch($variables['result']['node']->type) {
    case 'nodetype1':
      $n = node_load($variables['result']['node']->nid);
      $n && ($variables['node'] = $n);
      break;
  default:
  break;
}
 
 
search-result.tpl.php
<?php if ($variables['result']['node']->type == 'nodetype1' && isset($variables['result']['node']->field_image[LANGUAGE_NONE][0]['uri'])): ?>
<?php
$image = theme('image_style', array('style_name' => 'thumbnail', 'path' => $variables['result']['node']->field_image[LANGUAGE_NONE][0]['uri']));
?>
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: imagecache, theme
Rating:
0
No votes yet
$image = theme('image_style', array('style_name' => 'thumbnail', 'path' => $node->field_image[LANGUAGE_NONE][0]['uri']));
Drupal Version: n/a
Posted: Nov 14th, 2012
Tags: nodejs, nvm
Rating:
0
No votes yet
git clone git://github.com/creationix/nvm.git ~/.nvm
. ~/.nvm/nvm.sh  //nvm can install and switch to multiple version of nodejs easily
nvm install v0.6.7 
nvm ls //list all nodejs version installed
cd ~/.nvm/v0.6.7/bin  //nodejs default directory 
 
curl http://npmjs.org/install.sh | sh  //install npm
npm -d install //install dependent module from package.json
Drupal Version: n/a
Posted: Nov 14th, 2012
Tags: git, commit module
Rating:
0
No votes yet
ssh-keygen -t rsa -C "your key"
cat /root/.ssh/id_rsa  //check your key , copy and paste to your drupal account .
 
git clone --branch 7.x-1.x http://git.drupal.org/sandbox/[your acc name]/[project id].git module_name  //git download your module
goto .git folder and edit config file
change "url = ......." to "url = [your acc name]@git.drupal.org:sandbox/[your acc name]/[project id].git"
git config --global user.name "[your acc name]"
git config --global user.email [your acc e-mail]
git config -l
git add -A
git commit -m 'commit comment here.'
git push
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: rule, action, event trigger
Rating:
0
No votes yet
function recurly_account_save () {
..............
rules_invoke_event('recurly_account_save',$recurly_account);
}
 
/* define event trigger */ 
function modulename_rules_event_info() {
  return array(
    'recurly_account_save' => array(
      'label' => t('update role'),
      'variables' => array(
        'user' => array(
          'type' => 'array',  // can be define as text, array, user , integer ....
          'label' => t('user'),
        ),
      ),
    ),
  );
}
 
/* define action */ 
function modulename_rules_action_info() {
    $actions['modulename_getresult'] = array(
      'label' => t('update role'),
      'parameter' => array(
        'user' => array(
          'type' => 'array',
          'label' => t('user'),
        ),
      ),
    );
   return $actions;
}
 
function modulename_getresult($account) {
  //$account is the variable passed in from event trigger
 //do your logic here
}
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: loop all content type field, get all content type field
Rating:
0
No votes yet
  $contentinfo = node_type_get_types();
  foreach ($contentinfo as $content_type) {
    $field_instances = field_info_instances('node', $content_type->type);
    $allow_field = array();
    foreach ($field_instances as $field) {
      if ($field['widget']['module'] == 'image' || $field['widget']['module'] == 'file') {
        $allow_field[$field['field_id']] = t($field['field_name']);
      }
    }
    //.................................
   }
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: system setting form, admin form, variables
Rating:
0
No votes yet
function weibo_autopost_admin_config() {
  $form['global'] = array(
    '#type' => 'fieldset',
    '#title' => t('Global settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
 
  $form['global']['weibo_autopost_enable'] = array(
    '#type' => 'checkbox',
    '#title' => t('Default enable Weibo AutoPost in node form.'),
    '#default_value' => variable_get('weibo_autopost_enable', 1), /* variable name must be sane as the element name, otherwise cannot save automatically.
  );
  return system_settings_form($form);
}
Drupal Version: 6.x
Posted: Nov 14th, 2012
Tags: user autocomplete, ajax, json
Rating:
0
No votes yet
function signupst_autocomp($string) {
   global $user;
  if(empty($user->uid)) {
    print drupal_to_js(array());exit();
  }
  $matches = array();
  $result = db_query("SELECT name, uid, mail FROM {users} WHERE (LOWER(name) LIKE LOWER('%%%s%%')) or (LOWER(mail) LIKE LOWER('%%%s%%') and name != '')", $string, $string);
  while ($searchuser = db_fetch_object($result)) {
    //your logic filter here
    $matches[$searchuser->name] = check_plain($searchuser->name . $emailstr . $parentstr);
  print drupal_to_js($matches);
  exit;
}
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: file_save, permanent status
Rating:
0
No votes yet
<?php
function modulename_siteconfig_validate($form , $form_state) {
  if(!empty($form_state['values']['image']) {
    $f = file_load($form_state['values']['image']);
    $f->status =1;
    $foutput = file_save($f);
    file_usage_add($foutput, 'modulename', 'modulename', $foutput->fid);  /*** ****/
  }
}
?>
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: jplayer, ajax, views
Rating:
0
No votes yet
$=jQuery;
$(document).ready(function(){
  var selector = $("#block-views-jplaylist-block a");
  selector.click(function (event){
    event.preventDefault();
 $.ajax({
      url: "/views/ajax",
      type: "POST",
      dataType:"json",
      data: {
        "js":0,
        "view_name":"ontopjplayer",
        "view_display_id":"block",
        "view_args": $(this).attr('rel')
      },
      success: function(view) {
        $(".view-ontopjplayer").replaceWith(view[1].data);
           Drupal.settings.jPlayer = view[0].settings.jPlayer;
           Drupal.settings.jplayerInstances = view[0].settings.jplayerInstances;
           Drupal.attachBehaviors(document);
    }
    });
  });
}); 
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: ctools, multistep form
Rating:
5
Average: 5 (1 vote)
<!--?php
function ctools_multistep_menu() {
  $items['add/%ctools_js/multistep'] = array(
      'title' =--> 'Ctools 4 steps form',
      'page callback' => 'ctools_add_multistep',
      'page arguments' => array(1),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
  );
  return $items;
}
 
function ctools_add_multistep($js = NULL, $step = NULL) {
  if ($js) {
    ctools_include('modal');
    ctools_include('ajax');
  }
 
  $form_info = array(
    'id' => 'add_multistep', //form id
    'path' => "add/" . ($js ? 'ajax' : 'nojs') . "/multistep/%step", //pass the step we're on to the form, step1, step2, ..etc
    'show trail' => TRUE, //show the breadcrumb / path trail for the forms
    'show back' => TRUE, //show the back button
    'show cancel' => TRUE, //show the cancel button
    'show return' => FALSE, //show the update and return button
    'next callback' =>  'ctools_multistep_wizard_next', //a callback function to run when the next button is pressed
    'finish callback' => 'ctools_multistep_wizard_finish', //callback when finish button is pressed
    'cancel callback' => 'ctools_multistep_wizard_cancel', //callback when cancel button is pressed
    'order' => array( // this controls order, as well as form labels
      'step_1' => t('Basic Info'),
      'step_2' => t('File upload'),
      'step_3' => t('Step 3'),
      'step_4' => t('Step 4'),
    ),
    'forms' => array( // here we map a step to a form id.
      'step_1' => array( //What we're doing here is telling the wizard when step1 is passed as arg show the form with form_id ctools_multistepstep_1
        'form id' => 'ctools_multistep_step_1'
      ),
      'step_2' => array(
        'form id' => 'ctools_multistep_step_2'
      ),
      'step_3' => array(
        'form id' => 'ctools_multistep_step_3'
      ),
      'step_4' => array(
        'form id' => 'ctools_multistep_step_4'
      ),
    ),
  );
 
  $object_id = 'ctools_multistep';
 
  if (empty($step)) {
    ctools_multistep_cache_clear($object_id);
    $step = "step_1";
  }
 
 
  $object = ctools_multistep_cache_get($object_id);
 
  $form_state = array(
    'ajax' => $js,
    'object_id' => $object_id,
    'object' => &$object,
  );
 
  // Send this all off to our form. This is like drupal_get_form only wizardy.
  ctools_include('wizard');
  $form = ctools_wizard_multistep_form($form_info, $step, $form_state);
  $output = drupal_render($form);
 
  return $output;
}
function ctools_multistep_step_1_submit(&$form, &$form_state) {
  $form_state['object']->name = $form_state['values']['name'];
  $form_state['object']->dateitem = $form_state['values']['dateitem'];
  $form_state['object']->dateitem2 = $form_state['values']['dateitem2'];
  $form_state['object']->user = $form_state['values']['user'];
  $form_state['object']->gender = $form_state['values']['gender'];
  $form_state['object']->desc = $form_state['values']['desc'];
}
 
function ctools_multistep_step_2_submit($form, &$form_state) {
  $form_state['object']->marker_fid = $form_state['values']['marker_fid'];
}
 
function ctools_multistep_step_1($form, &$form_state) {
  $form_state['title'] = t('4 steps form');
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => $form_state['object']->name,
    '#required' => TRUE,
  );
  $dateformat = 'm/d/Y';
  $d = new DateTime();
  $datevalue = $d->format($dateformat);
  $form['dod']['dateitem'] = array(
    '#type' => 'date_select',
    '#title' => t('Date1'),
    '#date_format'   => $dateformat,
    '#default_value' => $datevalue,
    '#default_value' => $form_state['object']->dateitem,
    '#date_label_position' => 'within',
    '#date_timezone' => date_default_timezone(),
    '#date_increment' => 1,
    '#date_year_range' => '-3:+3',
    '#value_callback' => 'date_select_element_value_callback',
    '#tree' => FALSE,
  );
 
  $form['dob']['dateitem2'] = array(
    '#type' => 'date_select',
    '#title' => t('Date2'),
    '#date_format'   => $dateformat,
    '#default_value' => $form_state['object']->dateitem2,
    '#date_label_position' => 'within',
    '#date_timezone' => date_default_timezone(),
    '#date_increment' => 1,
    '#date_year_range' => '-3:+3',
    '#value_callback' => 'date_select_element_value_callback',
    '#tree' => FALSE,
  );
 
  $form['user'] = array(
    '#type' => 'textfield',
    '#title' => t('Select taxonomy'),
    '#default_value' => $form_state['object']->user,
    '#required' => FALSE,
    '#autocomplete_path' => 'taxonomy/autocomplete/1',
  );
 
  $gender_arr = array();
  $gender_arr['Male'] = t('Male');
  $gender_arr['Female'] = t('Female');
  $form['gender'] = array(
    '#type' => 'select',
    '#title' => t('Gender'),
    '#default_value' => $form_state['object']->gender,
    '#required' => FALSE,
    '#options' => $gender_arr
  );
 
  $form['desc'] = array(
    '#type' => 'textarea',
    '#default_value' => $form_state['object']->desc,
    '#title' => t('Short "description" for the ctools'),
    '#required' => FALSE,
  ); 
 
 
 
  return $form;
}
 
function ctools_multistep_step_2($form, &$form_state) {
 
  $name = $form_state['object']->name;
  //$options = ctools_multistep_options();
  //$choice = $options[$form_state['object']['choices']];
 
  $form['marker_fid'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#default_value' => $form_state['object']->marker_fid,
    '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
    '#upload_location' => 'public://',
  );
  return $form;
}
 
function ctools_multistep_step_3($form, &$form_state) {
  return $form;
}
 
function ctools_multistep_step_4($form, &$form_state) {
  $form['story'] = array(
    '#type' => 'textarea',
    '#title' => t('Write Stories or Special Memories'),
    '#required' => FALSE,
  ); 
  return $form;
}
 
/**
 * Cache helpers
 */
function ctools_multistep_cache_set($id, $object) {
  ctools_include('object-cache');
  ctools_object_cache_set('ctools_multistep', $id, $object);
}
 
/**
 * Get the current object from the cache, or default.
 */
function ctools_multistep_cache_get($id) {
  ctools_include('object-cache');
  $object = ctools_object_cache_get('ctools_multistep', $id);
  if (!$object) {
    // Create a default object.
    $dateformat = 'm/d/Y';
    $d = new DateTime();
    $datevalue = $d->format($dateformat);
    $object = new stdClass;
    $object->name = '';
    $object->dateitem = $datevalue;
    $object->dateitem2 = $datevalue;
    $object->user = '';
    $object->gender = '';
    $object->desc = '';
    $object->marker_fid = '';
  }
  return $object;
}
/**
 * Clear the wizard cache.
 */
function ctools_multistep_cache_clear($id) {
  ctools_include('object-cache');
  ctools_object_cache_clear('ctools_multistep', $id);
}
 
/**
 * Next callback
 */
function ctools_multistep_wizard_next(&$form_state) {
  ctools_multistep_cache_set($form_state['object_id'], $form_state['object']);
}
/**
 * Finish callback
 */
function ctools_multistep_wizard_finish($form_state) {
  $form_state['complete'] = TRUE;
}
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: share this
Rating:
0
No votes yet
/**
 * reinitialise "Share This" script on ajax page refresh. 
 **/
delete stLight;delete stButtons;delete stFastShareObj;delete stIsLoggedIn;delete stWidget;delete stRecentServices;
$.getScript("http://w.sharethis.com/button/buttons.js", function() {
var switchTo5x= true;
stLight.options({publisher:'dr-37136bf8-87b-54c5-da06-aef5bbe9cb52'});
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: node_save, node, taxonomy, date
Rating:
0
No votes yet
/* date field */
  $form['dod']['dateitem'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of death'),
    '#date_format'   => $dateformat,
    '#date_label_position' => 'within',
    '#default_value' => '',
    '#date_timezone' => date_default_timezone(),
    '#date_increment' => 1,
    '#date_year_range' => '-3:+3',
    '#value_callback' => 'date_select_element_value_callback',
    '#tree' => FALSE,
    '#required' => TRUE,
  );
/* managed_file field */
  $form['marker_fid'] = array(
    '#title' => "Upload main image to put on marker",
    '#type' => 'managed_file',
    '#upload_location' => 'public://',
  );
 
/* taxonomy autocomplete field */
  $form['taxonomy_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Select Options'),
    '#required' => FALSE,
    '#autocomplete_path' => 'taxonomy/autocomplete/field_select_option',
  );
 
/* form_submit handler */
 
/* date field format */
 $value =  $form_state['value'];
    $dateitem = array();
    $dateitem['value'] = $value->dateitem . ' 00:00:00';
    $dateitem['timezone'] = date_default_timezone();
    $dateitem['timezone_db'] = date_default_timezone();
    $dateitem['date_type'] = 'datetime';
  }
 
/* taxonomy field format */
 $term = taxonomy_get_term_by_name($value->taxonomy_field);
 
/* node_save (new node) */
  global $user;
  $node = new stdClass();
  $node->type = "xxx";
  $node->status = 1;
  $node->language = LANGUAGE_NONE;
  $node->uid = $user->uid;
  $node->title = $obj->name;
  $node->field_date_of_death[LANGUAGE_NONE][] = $dateitem;
  $node->field_select_option[LANGUAGE_NONE][] = array("tid" => current($term)->tid);
  $image = (array)file_load($value->marker_fid);
  $node->field_main_image[LANGUAGE_NONE][] = $image;
  node_save($node);
Drupal Version: 7.x
Posted: Nov 14th, 2012
Tags: ajax, views, getlocations
Rating:
0
No votes yet
/**
 * Ajax view
 **/
$.ajax({
  url: "/views/ajax",
  type: "POST",
  dataType:"json",
  data: {
    "js":0,
    "view_name":"cakemap",
    "view_display_id":"block_1",
    "view_args": param
  },
  success: function(view) {
    Drupal.settings.getlocations = view[0].settings.getlocations;
    $(".cakebase-view").replaceWith(view[1].data);
    Drupal.attachBehaviors(".cakebase-view");
    getlocations_init();  
  }
})
/**
 * Get street view by latitude and longtitude 
 **/
function generate_stview(lat,lng) {
  var fenway = new google.maps.LatLng(lat, lng);
  var panoramaOptions = {
    position: fenway,
    pov: {
      heading: 34,
      pitch: 10,
      zoom: 1
    }
  };
  var panorama = new google.maps.StreetViewPanorama(document.getElementById('stview'), panoramaOptions);
  getlocations_map.key_1.setStreetView(panorama);
}
 
<style>
#stview img { max-width:none!important;}   // fix a bug on Zen responsive theme
#stview_close {
float:right;
z-index:2;
font-weight:bold;
color:#fff;
margin-top:5px;
margin-right:5px;
position:relative;
}
</style>
<div id="stview" style="display:none;width:800px;height:400px;position:absolute;"><a id="stview_close" href="javascript:void(0);" onclick="javascript:jQuery('#stview').hide();">Close</a></div>
Drupal Version: n/a
Posted: Nov 14th, 2012
Tags: phantomjs, installation, qt47
Rating:
0
No votes yet
#install qt47
rpm --import http://packages.atrpms.net/RPM-GPG-KEY.atrpms
yum install qt47 qt47-webkit qt47-webkit-devel qt47-x11 qt47-sqlite
vim /etc/profile
 
export QMAKESPEC=/usr/lib/qt47/mkspecs/linux-g++-32
export QTDIR=/usr/lib/qt47
export QTLIB=/usr/lib/qt47/lib
export QTINC=/usr/lib/qt47/include
export LD_LIBRARY_PATH=$QTDIR/lib:$LD_LIBRARY_PATH
export PATH=$QTDIR/bin:$PATH
 
source /etc/profile
/usr/lib/qt47/bin/qmake-qt47 && make
 
#install phantomjs
git clone git://github.com/jbraeuer/phantomjs-rpms.git
./build.sh --jobs 1
cd deploy
sh package.sh
 
#uninstall
git clean -xfd
make distclean
Drupal Version: 6.x
Posted: Nov 14th, 2012
Tags: menu_links, multisites
Rating:
0
No votes yet
  update menu_links as m1 
  inner join menu_links as m2
  on (m2.link_path = 'admin/content/signup' and m2.menu_name = 'primary-links') 
  set m1.weight = m2.weight-1 , m1.depth = m2.depth , m1.plid = m2.plid,m1.p1 = m2.p1, 
  m1.p2 = if((m2.depth = 2),m2.mlid,if((2>m2.depth), NULL,m2.p2)) ,
  m1.p3 = if((m2.depth = 3),m2.mlid,if((3>m2.depth), NULL,m2.p3)) ,
  m1.p4 = if((m2.depth = 4),m2.mlid,if((4>m2.depth), NULL,m2.p4)) ,
  m1.p5 = if((m2.depth = 5),m2.mlid,if((5>m2.depth), NULL,m2.p5)) , 
  m1.link_title = 'xxxxxx'
  where m1.link_path = 'admin/settings/xxx/signupst' and m1.menu_name = 'primary-links'
Drupal Version: 6.x
Posted: Nov 14th, 2012
Tags: views, join custom table in views
Rating:
0
No votes yet
<?php
function modulename_views_data() {
    $data = array();
    $data['modulename']['table']['group'] = t('modulename');
    $data['modulename']['table']['base'] = array(
    'field' => 'city_tid', 
    'title' => t('modulename table'), 
    'weight' => -10,
    );
 
    $data['modulename']['table']['join'] = array(
      'node' => array(
        'left_field' => 'nid',
        'field' => 'nid',
      ),
    );
 
    $data['modulename']['city_tid'] = array(
        'title' => t('modulename city ID'),
        'help' => t('modulename city ID.'),
        'relationship' => array(
          'base' => 'node',
          'field' => 'nid',
          'handler' => 'views_handler_relationship',
          'label' => t('Node id in this table that references a node.'),
        ),
        'filter' => array(
            'handler' => 'views_handler_filter',
        ),
        'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
        'argument' => array(
            'handler' => 'views_handler_argument',
        ),
    );
    return $data;
}
 
/**
* Implementation of hook_views_api().
*/
function modulename_views_api() {
 return array(
   'api' => 2,
   'path' => drupal_get_path('module', 'modulename'),
 );
}
?>