zoukankan      html  css  js  c++  java
  • drupal常用api

    最短的函数

    // 语言字串,除了可以获取对应语言外,还可以设置字串变量。可以是!var, @var或 %var,%var就添加元素外层。@var会过滤HTML,!var会原样输出HTML,%var会添加span外层。
    t('my name is @name', array('@name' => 'willam'));
    
    // 一个链接
    l('User Edit', 'user/1/edit');
    

    判断首页

    drupal_is_front_page();
    

    GLOBALS

    $GLOBALS['base_url'] // URL root
    

    GLOBAL 文档

    加载inc文件

    module_load_include('inc', 'mymodule', 'mymodule.field');
    

    得到ROOT目录

    getcwd()
    DRUPAL_ROOT
    把URI(public://)地址转换为绝对地址
    drupal_realpath('public://xxx.csv'); // 得到系统路径
    file_create_url('public://xxx.csv'); // 得到URL
    

    加载脚本&CSS

    drupal_add_js('misc/collapse.js');
    drupal_add_js('misc/collapse.js', 'file');
    drupal_add_js(drupal_get_path('module', 'content_glider'). '/srcipt.js');
    drupal_add_js(libraries_get_path('custom').'/srcipt.js');
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
        array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
    );
    drupal_add_js('http://example.com/example.js', 'external');
    drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
    

    关于javascript细节可以访问以下链接:

    https://drupal.org/node/756722

    激活behaviors

    Drupal.attachBehaviors(document);
    

    加载jquery ui

    drupal_add_library('system', 'ui.tabs');
    

    查某个URL得到程序所在

    SELECT * FROM dp_menu_router where path='admin/config/search/path/patterns'
    

    查实现某个HOOK的所有函数

    • dpm(module_implements('menu'));
    • 使用drush: drush hook menu

    跳转

    drupal_goto('node/1');
    drupal_goto(current_path());
    drupal_not_found(); // 跳转到404页面
    drupal_goto('<front>', array(), 301); // 301跳转
    

    URI

    • URI to URL: file_create_url('public://js/gmap_markers.js');
    • 临时目录URI: temporary://

    URL

    arg(1); // 提取URL第2个参数,例如node/1,会提取1
    $_GET['q']; // 得到当前URL路径
    url('node/1'); // 网站相对地址
    url('node/1', array('absolute' => true)); // 绝对地址
    url('<front>', array('query' => 'action=do', 'fragment' => 'top'));
    

    得到URL alias

    drupal_lookup_path('alias',"node/".$node->nid);
    drupal_get_path_alias("node/".$node->nid);
    

    路径匹配

    drupal_match_path($_GET['q'], 'node/*');
    

    图片

    image_style_url('image_style_name', $node->field_image[LANGUAGE_NONE][0]['uri']); // 缩略图片URL
    file_create_url($node->field_image[LANGUAGE_NONE][0]['uri']); // 原始图片URL
    // 显示缩略图片
    $variables = array(
        'style_name' => 'image_style_name',
        'path' => $node->field_image[LANGUAGE_NONE][0]['uri'],
        'alt' => $node->title,
        'title' => $node->title,
    );
    print theme('image_style', $variables);
    
    // 显示原图
    $variables = array(
      'path' => 'path/to/img.jpg',
      'alt' => 'Test alt',
      'title' => 'Test title',
      'width' => '50%',
      'height' => '50%',
      'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
      );
    $img = theme('image', $variables);
    
    // 带链接的图片
    l(theme_image_style(array('path' => $variables['node']->field_logo['und']['0']['uri'], 'style_name' => '100x100')), 'node/' . $variables['node']->nid, array('html' => TRUE));
    

    配置值存取

    • variable_get
    • variable_set
    • variable_del

    日期格式化

    format_date($timestamp, $type = 'custom', $format = '');
    
    date_default_timezone_set('PRC');
    strtotime('2013-6-5 20:11');
    

    返回JSON数据

    echo drupal_json(array('xxx'));
    drupal_json_output(array('xxx'));
    drupal_exit();得到请求
    arg(1); // 得到URI的第二个值
    

    跳转 destination

    任何表单,只要在URL上加?destination=xxx,提交后都会跳转到相应地址

    url('xxx',
      array('query' => array('destination' => 'yyyy'))
    );
    drupal_goto('user', array('query' => array('destination'=>'user/myorder')));
    drupal_goto(drupal_get_destination());
    

    自定义breadcrumb

    $breadcrumb = array();
    $breadcrumb[] = l('Home', 'node');
    $breadcrumb[] = l('Our Team', 'team');
    $breadcrumb[] = drupal_get_title();
    drupal_set_breadcrumb($breadcrumb);
    

    Log

    watchdog('event_type', 'name is :name', array(':name' => $name), WATCHDOG_WARNING);
    

    文件操作

    file_load($fid)->uri;
    file_move($file, 'public://xxx/');
    file_copy($file, 'public://xxx/');
    file_delete($file);
    file_scan_directory('public://','/.*.(png|gif|jpg|jpeg)$/'); // 扫描文件夹,返回file对象数组
    

    Form API File upload

    http://drupal.org/node/1537950

    entity edit form的form field element,以profile2为例

    $form = array();
    field_attach_form('profile2', profile2_load_by_user($user, 'general'),$form, $form_state);
    
    // node
    field_attach_form('node', $node, $form, $form_state);
    

    注意$form_state必须是form参数$form_state的原变量,clone的会报错。执行后会填充$form变量,可以附加到当前的form中。

    如果想只提取部分的field,可以使用multiple_entity_form module。

    node add form

    $type = 'news';
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
      'uid' => $GLOBALS['user']->uid,
      'name' => $GLOBALS['user']->name ?: '',
      'type' => $type,
      'language' => LANGUAGE_NONE,
    );
    $form = drupal_get_form($type . '_node_form', $node);
    

    还需要添加以下HOOK来处理AJAX时产生的错误

    /**
     * Implementation of hook_form_node_form_alter().
     */
    function mymodule_form_node_form_alter(&$form, &$form_state, $form_id){
      //ensuring the ajax upload still has all the includes
      $files = (isset($form_state['build_info']['files'])) ? $form_state['build_info']['files'] : array();
      $files[] = drupal_get_path('module', 'node') . '/node.pages.inc';
      $form_state['build_info']['files'] = $files;
    }
    
    

    得到element children

    element可以互相嵌套,通过render可以把element转换为HTML,而render之前,element只是一个大型数组,一般的数组操作很难区分element部分,所以可以用element_children:

    foreach (element_children($element) as $key) {
        $sub_element[]= $element[$key];
    }
    

    单实例

    $static = &drupal_static(__FUNCTION__, array());
    

    cache

    $cache_key = md5(serialize($values));
    if($cached = cache_get($cache_key)) {
      $cache_data = $cached->data;
    } else {
      $cache_data = getData();
      cache_set($cache_key, $cache_data);
    }
    

    session

    drupal_session_start();
    $_SESSION[$key] = $value;
    

    修改用户名的HOOK

    hook_username_alter();
    format_username($account); // 显示用户名
    

    301 redirects

    function mytheme_preprocess_html(&$variables, $hook){
      if(!drupal_match_path(current_path(), '<front>') && !(user_access("administer users") || drupal_match_path(current_path(), "user
    user/*"))) {
        if(module_exists('search404')) {
          search404_goto("<front>");
        } else {
          drupal_goto('<front>', array(), 301);
        }
      }
    }
    

    获取当前语言标识 (i18n)

    $language = i18n_language_interface();
    $lang = $language->language;
    

    生成用户的识别码

    user_pass_rehash($account->pass, $timestamp, $account->login);
    

    增删用户角色

    $role_name = 'admin';
    $role = user_role_load_by_name($role_name);
    user_multiple_role_edit($uids, 'add_role', $role->rid);
    user_multiple_role_edit($uids, 'remove_role', $role->rid);
    

    输出一个MENU(1 level)

    theme('links', array(
            'links' => menu_navigation_links('menu_name'),
            'attributes' => array(
              'id' => 'footer-menu',
              'class' => array('links', 'clearfix'),
            ),
          )
    );
    

    常用配置

    当前主题:$conf['theme_default']
    网站名:$conf['site_name']
    

    调试

    dpm($vars);
    dpq($query);
    

    javascript格式

    (function ($, Drupal, window, document) {
        Drupal.behaviors.myModule = {
            attach: function (context) {
                // ....
            }
        };
    })(jQuery, Drupal, window, document);


    注释:原文链接:http://segmentfault.com/a/1190000000359186;
  • 相关阅读:
    萌新向Python数据分析及数据挖掘 第三章 机器学习常用算法 第三节 梯度下降法 (上)理解篇
    萌新向Python数据分析及数据挖掘 第三章 机器学习常用算法 第二节 线性回归算法 (下)实操篇
    萌新向Python数据分析及数据挖掘 第三章 机器学习常用算法 第二节 线性回归算法 (上)理解篇
    萌新向Python数据分析及数据挖掘 第三章 机器学习常用算法 第一节 KNN算法 (下)实操篇
    萌新向Python数据分析及数据挖掘 第三章 机器学习常用算法 第一节 KNN算法 (上)理解篇
    萌新向Python数据分析及数据挖掘 第二章 pandas 第五节 Getting Started with pandas
    Oracle数据库安装和授权
    c# 如何获取JSON文件以及如何获取Config文件(framework 和 net .Core)
    C#Core查询数据库存储EXCEL文件
    如何在WINDOW系统下编译P12证书制作
  • 原文地址:https://www.cnblogs.com/wicub/p/6441531.html
Copyright © 2011-2022 走看看