Autocomplete field where title is replaced with NID I'm using Drupal 7 and I have made autocomplete function to be called on a field.
File my_module.module:
<?php

function my_module_menu() {

    $items = array();

    $items['/autocomplete'] = array(
        'title' => 'Autocomplete',
        'page callback' => 'companyAutocomplete',
        'access arguments' => array('autocomplete'),
        'type' => MENU_LOCAL_TASK,
        'weight' => 1,
        'file' => 'my_module.autocomplete.inc'
    );

    return $items;
}

File my_module.autocomplete.inc:
<?php

function companyAutocomplete($fieldInput) {

    $returnArray = array();

    $query = db_select('node', 'n')
        ->fields('n', array('nid', 'title'))
        ->condition('n.title', '%'.db_like($fieldInput).'%', 'LIKE')
        ->condition('n.type', 'company', '=')
        ->orderBy('n.title', 'ASC')
        ->range(0, 10);

    // print strtr((string) $query, $query->arguments());

    $results = $query->execute();

    foreach ($results as $result) {
        $returnArray[$result->title] = check_plain($result->title);
    }

    drupal_json_output($returnArray);
}

File template.php:
<?php

function my_theme_preprocess_field(&$vars) {

    if ($node = menu_get_object()) {

        if ($node->type == 'company') {

            if ($vars['element']['#field_name'] == 'field_company') {
                $company = entity_metadata_wrapper('node', $vars['items']['0']['#markup']);
                $vars['items']['0']['#markup'] = $company->label();
            }
        }
    }
}

and I have a field company (I use this field to enter NID):
$form['field_company'] = array(
    '#type' => 'textfield',
    '#default_value' => $defaultCompany,
    '#title' => 'Company',
    '#autocomplete_path' => '/autocomplete',
);

When I type something in field, autocomplete returns correct text value of the searched term and that is ok.
How can I modify companyAutocomplete() function or the field itself for autocomplete to works as it is, but to write NID instead title in $form['field_company']['und'][0]['value']?

You need the array keys to be nids, so change it to
$returnArray[$result->nid] = check_plain($result->title);


How to get content type data on basis of assigned taxonomy? I want to get the data of particular content type on the basis of taxonomy assigned to it. How can I get this using query.

$bloglist = db_select('node', 'n')
                    ->fields('n', array('nid'))
                    ->condition('type', 'product_list', '=')
                    ->condition('status', 1, '=')
                    ->orderBy('created', 'DESC')
                    ->execute()
                    ->fetchCol();

        // Get all of the article nodes.
        $bloglists2 = node_load_multiple($bloglist);

I have this query to get the data for product_list content type. Now I want to add one more condition of taxonomy to get data on basis of taxonomy and content type. How can I do that?

The EntityFieldQuery class was built to do pretty much exactly that:

$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'product_list')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_foo', 'tid', $term_id)
  ->propertyOrderBy('created', 'DESC')
  ->execute();

if (isset($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}


How to publish link programatically? I am creating Job portal and in that job portal When I create a Job post using admin and save that job as draft instead of posting it to all and for that draft one link is get created and I want to make that job draft link to be accessible to all users including guest.

following is the code for creating draft :

case 'draft':
        $new_node = node_load($job_node_nid,null,true);
        $new_node->status = 0;
        node_save($new_node);
        $_SESSION['bf_job_creation'] = array('step'=>1);
        header('Location: ' . url('my-account'));
        break;

 This above code creates job draft but link to access that draft I just want to make that link to be accessible to all by writing code.

I have tried following code to make link accessible but not succeed :

case 'draft':
    $new_node = node_load($job_node_nid,null,true);
    $new_node->status = 0;
        $new_node->field_job_status = array(array('value'=>'published'));//added this
    node_save($new_node);
    $_SESSION['bf_job_creation'] = array('step'=>1);
    header('Location: ' . url('my-account'));

break;

how to make the link to job draft public??

your problem is $new_node->status = 0;
This is setting the node to 'unpublished'.
either change the permissions to allow the users to see it or set $new_node->status = 1;
To create a link use the l() function eg. l('link text', 'node/'.$node->id);. http://api.drupal.org/api/drupal/includes!common.inc/function/l/7


delete URLs of all terms for a specific taxonomy vocabulary Using pathauto module,  I know we have a Delete aliases tab to delete URLs in bulk but what if we need to delete URLs of all terms for specific vocabulary?

Any idea how to do that?

To delete the aliases you will need a custom module or perhaps a custom VBO action based on the update taxonomy term alias action.  Here is a quick and dirty version of a custom module

aliases_delete.info

name = delete aliases
description = will delete vocabulary aliases for specific vocabulary
package = aliases_delete
version = 1
core = 7.x
dependencies[] = pathauto

aliases_delete.module

<?php

function aliases_delete_menu() {
  $items['aliases_delete/%'] = array(
    'page callback' => 'aliases_delete_delete_vocabulary',
    'page arguments' => array(1),
    'access callback' => 'taxonomy_term_edit_access',
    'access arguments' => array(2),
  );
  return $items;
}

function aliases_delete_delete_vocabulary($vocabulary_name){
  $vocab = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  $terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocab->vid));
  foreach ($terms as $term) {
    pathauto_entity_path_delete_all('taxonomy_term', $term, "taxonomy/term/{$term->tid}");
  }
  return 'Deleted aliases of all terms in ' . $vocabulary_name;
}

If you enable and install this module you can visit as admin aliases_delete/tags to delete all aliases of terms in vocabulary tags

To update the path aliases of specific taxonomy terms (instead of deleting) you can use VBO - views_bulk_operations

install and enable the module
create a view of taxonomy terms and use appropriate filters for vocabulary
add field "view bulk operations" and save your view
go to your view and select all terms that will be updated (VBO can select multiple pages of results)
choose the update taxonomy term alias action and press execute
all terms should be updated according to the new pathauto rules


How do I translate quicktab headings? I am a newcomer to Drupal. I am developing a website with multilingual support and I have translated most of the contents, blocks etc. but wasn't able to translate the Quicktab tab title.

I am using i18n, languageicons and languagedropdown modules for this purpose. How do I translate Quicktab tab title?

Ensure you have downloaded (if needed) and enabled the 'Locale', 'Internationalization', 'String translation' modules
Go to Configurations > Translate Interface > Strings (Tab) (admin/config/regional/translate/i18n_string)
Check the 'Quicktabs' checkbox under the 'Select text groups' heading, and click 'Refresh strings'
Go to the page where it the quick tabs is and refresh it a few times (normally, you WOULDN'T need to do this, but for me, if I didn't and it's not cached, it doesn't work)
Go back to Configuration > Translate Interface > Translate (Tab) (admin/config/regional/translate/translate) , and search, using the 'String contains' input box, for one of the tab titles. I.e. if your tab titles are 'Apples', 'Oranges' and 'Pears', search for 'Apples'.
You should be able to see an entry. Click 'edit' and translate away!


Add variable to rule before execution I'm looking for a way to alter the variables before a rule is executed. Specifically, I'm trying to add a list of users who should be notified of a new comment so that I can create a loop and send an email to each.

I have implemented hook_rules_event_info_alter as follows:

function mymodule_rules_event_info_alter(&$events)
{
    $events['comment_insert']['variables']['affected_users'] = array('type' => 'list<user>', 'label' => 'Anyone that should be notified about a new comment.');
}

However, I am at a loss as to which hook needs to be implemented in order to fill in this variable before it is used. (On my site the default will be the node author, however there are some nodes where several users should be notified).

The implementation should be placed into the file MODULENAME.rules.inc, which gets automatically included when the hook is invoked.


Combining different content types I do not have much experience with Drupal but I have a question.
I have a content type Hotels with general information about the hotel but also with a field country and country information.
I was thinking to make a content type Country with fields like country information (country Name (England), country description (England is an island), map (googlemaps).
So when I have to add 10 hotels in the same country I do not have to write the same country information again and again.
I want to combine the content type HOTEL and COUNTRY but I really don't know how to do it?

Set up two content types, "Hotel" and "Country" and use the Entity References module to define a relationship between the two. Then configure it to display a "Rendered entity" formatter, that renders the references entity using a configurable view mode


Add Button to Node View I want to add custom button on node page.

I tried with hook_node_view but it didn't show up.

like this:

function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

$build['mybutton'] = [
  '#type'       => 'button',
  '#name'       => 'mybutton_name',
  '#value'      => t('Click Here'),
  '#attributes' => [ 'class' => 'button button--primary'],
  '#weight'     => -11,
];

}

What am I doing wrong?

EDIT:

Here is the template

{#
/**
 * @file
 * Display Suite 2 column stacked template.
 *
 * Available variables:
 * - outer_wrapper: outer wrapper element
 * - header_wrapper: wrapper element around header region
 * - left_wrapper: wrapper element around left region
 * - right_wrapper: wrapper element around right region
 * - footer_wrapper: wrapper element around footer region
 * - attributes: layout attributes
 * - header_attributes: attributes for header region
 * - left_attributes: attributes for left region
 * - right_attributes: attributes for right region
 * - footer_attributes: attributes for footer region
 * - header: content of header region
 * - left: content of left region
 * - right: content of right region
 * - footer: content of footer region
 */
#}

<{{ outer_wrapper }}{{ attributes.addClass('ds-2col-stacked', 'clearfix') }}>

  {{ title_suffix.contextual_links }}

  <{{ header_wrapper }}{{ header_attributes.addClass('group-header') }}>
    {{ header }}
  </{{ header_wrapper }}>

  <{{ left_wrapper }}{{ left_attributes.addClass('group-left') }}>
    {{ left }}
  </{{ left_wrapper }}>

  <{{ right_wrapper }}{{ right_attributes.addClass('group-right') }}>
    {{ right }}
  </{{ right_wrapper }}>

  <{{ footer_wrapper }}{{ footer_attributes.addClass('group-footer') }}>
    {{ footer }}
  </{{ footer_wrapper }}>

</{{ outer_wrapper }}>

Just tried it out myself and for me it didn't work using your malformatted #attributes array. After I fixed it the following did work. class must provide another array.

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $build['mybutton'] = [
    '#type'       => 'button',
    '#name'       => 'mybutton_name',
    '#value'      => t('Click Here'),
    '#attributes' => ['class' => ['button', 'button--primary']],
    '#weight'     => -11,
  ];
}


Can we fire database query while flagging the node? Can we fire  database query on flagging the flag(pick_this_bid)
I want to update the database table column in which boolen value is saved true and false.

By default it shows true status in database but when someone flagged(pick_this_bid) the  status  should change to false in the database.

I want something like this on clicking flag how to achieve this?

if(status==1)
 $status=0;
 else
  $status=1;

UPDATE  `my_table`.`node` SET  `status` =  0 WHERE  ` node`.`nid`    =1059;

According to The Flag 3.x API (PHP)

mymodule_flag_flag($flag, $content_id, $account, $flagging) {
  // Do something in response to the flagging.
}

mymodule_flag_unflag($flag, $content_id, $account, $flagging) {
  // Do something in response to the unflagging.
}

In your case

mymodule_flag_flag($flag, $content_id, $account, $flagging) {

  if ($flag->name == 'pick_this_bid'){

     $nid = $content_id;
     db_update('my_table')
       ->expression('status', '0')
       ->condition('nid', $nid)
       ->execute();
  }

}


How to integrate a custom one page php app into drupal 7? I am trying to integrate a custom website into the drupal 7 system. On this website there is a lot of user interaction with buttons, database queries, ajax loaded elements, … . I need to get the the global user variable on this page.

My first question: What is the best way to integrate the webpage?

My first attempt was to create a content type (node—myPage.tpl.php):
I got permission problems using ajax, so I separated the code into two files (node—myPage.tpl.php and myPage.php). In the node—myPage.tpl.php I only included myPage.php. But now I have the next problem using ajax (for myPage.php). I cannot get my global user variable.

My second attempt was to create a custom module. So I created a callback page. But I think I have to make a renderable array. I want to avoid this because myPage.php has over 3000 lines of code. And I don’t think jquery ajax will work as it should.

Is there an easy way to integrate a custom website into the drupal 7 system with access to the drupal api (user variable, functions)? I also prefer to keep the custom page in a php file, not into database.

A custom module with a menu callback is the way to go. In general, themes and tpl.php files should only control what your site looks like. Modules should control what your site does.

I understand that you don't want to refactor your code completely and turn everything into render arrays. Fortunately, you don't have to. You can create a string of html and put it in a render array like this:

// Generate your html.
$html = '
Hello world!
';
// Wrap it in a render array.
$output = array (
  '#markup' => $html,
);

Now, this is the really simple version. I do recommend that you take advantage of some of Drupal's features.

First of all, if you didn't already do so, I would create separate menu callbacks for the ajax requests. If both the rendering of the page and the ajax requests are handled by the same menu router, you might get in trouble when Drupal starts caching things.

Second, I would take add all javascript (and possible css) to the page using the #attached property of your render array. This also allows Drupal to cache (parts of) your page without breaking things. Assuming that your module is called "mymodule" and your javascript is stored in mymodule.js, your render array could look like this:

$output = array (
  '#markup' => '
Hello world!
',
  '#attached' => array(
    'js'      => array(
      drupal_get_path('module', 'mymodule') . '/mymodule.js',
    ),
    // If your output requires certain CSS rules, regardless of the theme
    // that is used, add a CSS file like this.
    //'css'      => array(
    //  drupal_get_path('module', 'mymodule') . '/mymodule.css',
    //),
  ),
);


Pages displaying blank ONLY when Theme Developer module turned on i have a situation where the theme developer module, when turned on, is causing some pages to display as the white page (of death). it's probably because i've been doing tutorials, learning how to override theme functions and probably at one point had some errors. but there errors have been cleared up, but the pages display as blank pages ONLY when that module is turned on. it's as if it has it's own cache???,

anyone know how to remedy that?, i need module to work.

This might be due to version compatibility with Simplehtmldom module.

Download this library and install in your sites/libraries files.

This is taken from modules page,

  NOTE: Currently, Theme Developer does not work with the latest version of simplehtmldom API. You must use simplehtml API version
  7.x-1.12 if you want Theme Developer to function properly.

OR if that is not the case you can try putting this snippet end of  the settings.php file, this snippet will show error message on the browser while loading page instead of WSOD. and you can put your error message here in question and elaborate it.

  error_reporting(E_ALL);
  ini_set('display_errors', TRUE);
  ini_set('display_startup_errors', TRUE);


Why running cron tasks would hit a REST service endpoint? I can't run cron jobs from a single module or from core anymore. Somehow Drush hits a REST service endpoint.

I have configured some service endpoints for views, but why would cron jobs hit that? I cannot explain that myself.

The error message I get from Drush is the  following one.

  Services Endpoint "rest" has been setup successfully. Drush command terminated abnormally due to an unrecoverable error.

It's impossible to answer the question directly because we'd have to speculate about the all the possible states of your Drupal installation where rest_server_server() is hit in a a cron context.

However, since you know where the notification message is being produced, and you can trigger it in a Drush command, what you can do is insert something like debug_print_backtrace() in the rest_server_server() function then re-run the Drush command to get an idea of what module/configuration is causing that to occur and if it's causing cron to die on you.


Using views to create comic reader I'm trying to create a comic reader like a flip book. I think the views module can do this but I don't know how to do it.
I plan to structure like this:

Terms (Series)
     - Sub Term (Chapters)
           - Nodes using image field (Pictures)

What I want to do is I want make a views in the subterms to show only one node at a time but the node contains the image that is linked to the next node in sequence order. So how can I do this? I only want the nodes from the subterm to show up

There's a lot of moving parts here. I'm going to make some assumptions. First, you have nodes. Each node has 1 image on it (through a file / image field).

You then want to display the nodes in some sequence order (maybe through a slideshow or something).

Each time you look at the view, you should only look at one "flip book" at a time.

For this you need to use a Views "Contextual Filter" (or "argument" in the older language). You would build your page view to pull in all the images of all the nodes. You would probably set your views to display as a views_slideshow or something.

The first "contextual filter" your view will have is the term (I'm assuming from taxonomy) that you want to build the flip book from. So, you might go and view yoursite.com/flipbook/37 (where 37 is the term id that all the image nodes are tagged with for this book).


Check required directory structure on module install/enable I am working on a drupal 7 module which acts as a interface for real estates. The interface works with xml files. Because of this i need some folder in the private files system.

I have defined my required folders as constants in the .module file. Now i wanted test with file_prepare_directory if the folders exist and if not create them. I want to do this on module install (hook_requirements) because the module works in the background with crons, so i would never get an error message if there is something wrong with the folder structure. The problem is that i could not access the constants from the .module file in the hook_requirements function.

So what is the best way to do this in drupal 7? Should i use hook_requirements, and if yes, how could i get my constants working? Or is there an ever better way to do this?

The Drupal API function drupal_load() will let you preload your .module file so you can make its constants/functions available during your hook_requirements() invocation:

/**
 * Implements hook_requirements().
 */
function MYMODULE_requirements($phase) {

  // @TODO: misc code.

  drupal_load('module', 'MYMODULE');

  // @TODO: code that requires MYMODULE_CONST_DEFINITION
}


Getting the user picture URL when Gravatar is installed I'm trying to print a user's picture without the link to the user's profile which is what theme('user_picture', array('account' =>$user_item)) will render. If I use image_style_url('thumbnail', $user->picture->uri) the Gravatar hook will not be called.

So far the only way I have found to do this is:

if (function_exists('_gravatar_get_account_user_picture')) {
    $picture = _gravatar_get_account_user_picture($user);
} else {
    $picture = $user->picture->uri;
}
if (file_valid_uri($picture)) {
    $picture = image_style_url('thumbnail', $picture);
}

But this isn't very elegant, especially since I am developing a module and I'd rather not have to explicitly call the Gravatar module.

Any suggestions?

Thanks!

Obviously, handling directly in the Gravatar module would be best, but another option (though slightly hackish) would be to simply

$img = strip_tags(theme("user_picture", array('account' => $user_item)), "<img>");


What will happen to my existing panels if I reinstall the panels module? The need is to reinstall panels because of some issues with it. However what will happen to the already existing panels if you reinstall or even remove panels entirely?

You will lost your custom panel configuration. To prevent that you can export all your panels to code with features.

This is because modules should remove its own data on hook_uninstall.

Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

This way you will have a features module with all your panels configuration.

This are the steps:

Install features module.
Go to admin/structure/features/create
Give a name to the feature module.
Select panels configuration
Download the feature.
Move this module to the features folder (site/all/modules/features).
Uninstall panels
Enable panels
Active the feature on admin/structure/features

There are also 'export' and 'import' tabs/links on the Panels UI and Pages UI but this is a manual process and can be slower than using features.


Why this code cannot delete the rows that i want? i want keep the 100 rows that has the biggest timestamp and delete all the other rows... Here follow the code that i have create :

$values_to_delete = db_delete('table1', 't');
  $values_to_delete->orderBy('t.timestamp');
  $values_to_delete->range(101, 99999999);
  $values_to_delete->execute();

The DeleteQuery class doesn't have orderBy or range functions, so I would imagine you would need to write your own DELETE with SELECT subquery. An example from Stack Overflow


Copying Drupal to a webhosting service What is the correct procedure to copy (transfer) a whole Drupal web with database to a web-hosting service? What are the problems that could occur? I'd like to change only the website name from localhost to domainname. It seems that everything else will be the same. I'm using Ubuntu and Drupal 7.0, Apache, Mysql. Should I consider the operating system of web-hosting and their server, database and similar things?

Roughly speaking, the procedure is to

copy all files to your webserver
create a database on the webserver
export the local database
import the db export in the webserver db
edit settings.php and set the new db name, user and pass
enjoy

The recommended webserver specs can be found at http://drupal.org/requirements. Since you have been developing on Linux, Apache and MySQL, use the same on your webserver (unless there is an important reason to change it). Also pay attention to your PHP version. Recent Ubuntu versions come with PHP 5.3, so it's best to use that on your server as well.

To prevent problems while importing your database (especially if you're using a tool like phpMyAdmin), it can help to empty (truncate) all cache_ tables before exporting it.


Programmatically alter taxonomy term tree options I have a taxonomy term reference field in a form. This field has many options and I'm using the term_reference_tree module to display them.
I'm trying to add a filter to this form so it only displays certain options depending on some factors (the value of a different field).

The problem is editing this field's options. I can't find a way to programmatically alter a taxonomy term reference field's options when using the term reference tree widget.
I've tried using hook_field_widget_properties_ENTITY_TYPE_alter but this doesn't allow me to alter the actual options.

Any suggestions would be very welcome. Thanks in advance.

This can be accomplished by modifying the #after_build item of your term_reference_tree field in hook_form_alter:

function MYMODULE_form_alter(&$form, &$form_state) {
  // You might want to do this only for certain forms,
  // or only for forms that have the field to be altered.
  $language = $form['my_taxonomy_field']['#language'];
  $form['my_taxonomy_field'][$language]['#after_build'][] = 'MYMODULE_branch_group_form_element_after_build';
}

function MYMODULE_branch_group_form_element_after_build($form_element, &$form_state) {
  MYMODULE_taxonomy_tree_form_element_alter($form_element[0]);
  return $form_element;
}

function MYMODULE_taxonomy_tree_form_element_alter(&$element) {
  foreach ($element as $tid => $data) {
    if (($tid[0] != '#') && is_numeric($tid)) {
      // MODIFY HERE:  If you do not want to show the term with
      // a specified tid, hide() it here.
      if ($tid == 60) {
        hide($element[$tid]);
      }
      else {
        // OPTIONAL: Alter the way each individual term is rendered.
        // See BONUS ANSWER, below.
        MYMODULE_taxonomy_tree_form_element_term_alter($element[$tid][$tid], $tid);
        // Recursively alter the children of the tree -- the item we
        // want to modify may be nested somewhere inside the tree.
        if (array_key_exists($tid . '-children', $element[$tid])) {
          MYMODULE_taxonomy_tree_form_element_alter($element[$tid][$tid . '-children']);
        }
      }
    }
  }
}

BONUS ANSWER:  In addition to filtering out items, I also wished to add a rendered icon with each taxonomy term in the tree.  In order to allow the specific fields of the taxonomy vocabulary to be selected and ordered, and the rendering mode (i.e. thumbnail size) of the image field to be selected through the admin user interface, I used the entity_view_mode module to define a new view mode for my taxonomies.

/**
 * Alter the data built by term_reference_tree.widget.inc.
 * @see: _term_reference_tree_build_item()
 */
function MYMODULE_taxonomy_tree_form_element_term_alter(&$element, $tid) {
  $term = taxonomy_term_load($tid);
  // In order for this to work, you will need to install the
  // entity_view_mode module, and make a 'term_with_icon'
  // view mode for your taxonomy vocabulary.
  $term_render_array = taxonomy_term_view($term, 'term_with_icon');
  $element['#title'] = drupal_render($term_render_array);
}


Why is jQuery 1.6.x not an option? All the other versions of jQuery are listed; version 1.6.x is missing.

What is the reasoning for not including 1.6.x in the jQuery Update module?

There are compatibility problems with jQuery 1.6.x & D7. If you'd like to know the details here's the current outstanding feature request for it.


What is the "correct" way of reporting problems detected by sanity checks, or catching exceptions? Example I:
You do something with Entity API, which sometimes throws an EntityMalformedException. So you wrap it into a try/catch block. You develop a fallback behavior, but you also want the admin to know that something is wrong.

Example II:
You expect that a specific field on a node is mandatory. There is a block that only works correctly if this field is set, and not empty. You develop a fallback behavior for the case that the field is empty, but you also want to let the admin know that something is wrong.

Example III:
A file you need is not readable. You develop a safe fallback behavior, but also want to let the admin know that something is wrong.

So far what I came up with is to do two things, plus the fallback:

Call watchdog($module, $message, array(), WATCHDOG_WARNING).
Call drupal_set_message($message, 'warning'), if the user has user_access('administer site configuration'). Regular users will not see this message.
Move on with a safe fallback behavior. E.g. if we cannot render a specific block, we just return an empty block. If we cannot load an image, we show a placeholder image. Etc.

What I see in other parts of Drupal 7 is that corrupt data can travel quite far, without being checked, before something blows up. And mostly I get uncontrolled PHP errors and warnings like "trying to get property of non-object", instead of controlled and checked warnings.

So, what is the "correct" or recommended way to do this stuff?
The fact that I am manually doing two separate things here and manually doing the access check indicates that I might be missing something..

In core Drupal try-catch blocks are pretty rare, because code is consistent, and core (boldly) assumes that code in contrib and custom modules will be good, too. One core function simply won't send malformed data (like non-objects where object is expected) to another - and won't expect another code to send inconsistent data to it. So try-catch would only slow things down. On the database side, and on the user input side, checks are performed all right. This, of course, is by far most recommended approach. If you can make sure your data is coherent, do it. Don't call Entity API at all if you haven't ensure you will not cause EntityMalformedException.

The only place it's not possible is a border between Drupal and other systems (including database and http connection). There, you need to put safeguards up. Your points are correct then, but you need to add one more:

Call watchdog
Set message for admin
Tell your user that what he think he did might have not happened. For example, if your code failed to delete a photo user really, really need to have taken down and you won't tell him, he may be disappointed. In some situation, you may also find yourself in legal trouble.
And only now proceed


Views Block's machine name is being "hashed" (?) A Drupal newbie, so correct me if my understand is wrong, but normally, when a Block is created by Views, the machine name of the block is appended to the Views' machine name.

i.e. "article_listing_view-block_1"

When using block_load($module, $block_id) function, the way I've been doing it is to call it thus:
$block = block_load("views", "article_listing_view-block_1");

However, for some very odd reason, one particular Block with the machine name:

"flag_comments_as_offensive-block_1"

has a hashed machine ID of:

"92a591f5a81d13a3dd5492f073f9e135"

I say "hashed" because the machine ID changes based directly on the machine-name of the block. If I change it from block_1 to block, it will change, and when I revert back from block to block_1, it will revert the machine ID back to the above. So there's a direct correlation between the machine name and the "hashed" ID it generates.

Instead of calling block_load("views", "machine name"), I have to use the hashed machine ID, which isn't a problem but it did take me a long time to figure out. The way I figured it out was to go into Structure -> Blocks and hover over the "Configure" link and look at the URL. I noticed that all my other Blocks have a URL that included its machine ID, but for this particular block, it was the hashed machine ID. Once I put in the machine ID into block_load, viola, it worked like a charm!

So I guess the question boils down to: What's going on, and why is Drupal hashing my machine name? Is this a bug, or an error on my part?

This is because the block module expects a 'delta' (block id) up to 32 characters long. But a view block display can have up to 65 characters: up to 32 characters from the view name and 32 characters from the display name and an hyphen '-' between them.

When the delta exceeds the 32 characters limit, Views will hash it through md5 — it is not a random string. You can safely use it for CSS and jQuery selectors.


Showing a list of content that only authorised users can see Most of the site is public however certain nodes need to be only visible to authorised users. I've got this up and running using Content Access but now I want to show a list of content that Anonymous users can't see.

I thought I'd be able to do it using Views and Contextual Filters but I can't seem to get just that content to show.

So, how do I do it?

You can use use Nodeqeue and views module to create a nodeqeue and assign permission using views module.


Why are custom User Account fields not shown after account is saved? Just upgraded to Drupal 7.54 and now when a user account is saved, any other users (other than admin 1 user) are unable to view or update the custom fields associated with the user account. They just see the core fields. The admin 1 user is still able to see all fields.

When the updated user account is viewed or edited by any other user than the admin 1 user (they do have 'administrator' role assigned), they only see the following fields:-

email
password
status
roles
locality

I have disabled modules that act on fields, such as Field Permissions and Conditional Fields, but still getting this behaviour.

Any ideas why this could be happening would be much appreciated!

Turns out a developer had enabled the "og_field_access" module and this was preventing users from viewing custom fields on the user account pages.

We removed the module dependencies (they weren't needed!) and disabled the og_field_access module and the fields now appear again!


View of blog posts grouped by year Client wants a blog archive with the posts inside accordions whose toggle is the year. Two example years HTML below.

I have the individual fields exposed as tokens within my view with no problem.  What I can't see how to do is to enable conditional logic so I express the Year toggle structure once per year of posts.

Is this possible with a View?

I went over Blog monthly archive block - list of posts grouped by year then month
I read the 10 year old post at http://chrisshattuck.com/blog/how-create-monthly-archive-block-drupal-blog-views

I have a working view Block but not nesting the way I need it.  It outputs a whole accordion per post (as I knew it would).

2019

{Authored on} - {Linked title}

2018

{Authored on} - {Linked title}

You can do this with the Views Accordion module.

Add the Authored on field, choose the formatter that only shows the year of the created date. Then edit the Format settings to set the Grouping field Nr.1 field to your yearly Authored on field.

This way you get all the results split into groups by year.

Now you configure the Views Accordion to use the Grouping as accordion headings and the grouped results as accordion content.


How do I load a field collection from a node? I have a node that has a few field collections on it.

When I look at node_load() output, I see:

[field_rich_text_group] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 6
                        )

                    [1] => Array
                        (
                            [value] => 7
                        )

                    [2] => Array
                        (
                            [value] => 8
                        )

                )

        )

What API function can I use to actually load the field data contained in the collection that has an entity_id of 6, 7, 8, etc?

Doh! I should have looked in the field collection module:

entity_load('field_collection_item', array($item_id))


How can I prepopulate a field's value when creating a new entity I have a custom entity (foo) which contains an entity reference field to another custom entity (bar). I would like to create a URL on the bar's unique page to create a new foo entity, where the entity reference is pre-populated with the correct target_id.

For example, a link to /admin/structure/my_module/foo/add?target_id=2501

Is this feature already available? Can I add something to the entity buildForm method to prepopulate my value?

class FooForm extends ContentEntityForm {
  public function buildForm(array $form, FormStateInterface $form_state) {
    //SOMETHING LIKE THIS?
    //if (isset(REQUEST::get('target_id'))) {
    //  $form_state['edit-bar-id-0-target-id'] = REQUEST::get('target_id');
    //}
    /* @var $entity \Drupal\my_module\Entity\Foo */
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;
    return $form;
  }
}

I'm not familiar enough with the structure of the $form_state or best practices on get() to be comfortable testing this.

After adding dependency injection of a requestStack, this works.

/**
 * @var Symfony\Component\HttpFoundation\RequestStack
 */
protected $requestStack;

/**
 * Constructor.
 *
 * @param Symfony\Component\HttpFoundation\RequestStack $request_stack
 */
public function __construct(RequestStack $request_stack) {
  $this->requestStack = $request_stack;
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container) {
  return new static(
    $container->get('request_stack')
  );
}

public function buildForm(array $form, FormStateInterface $form_state)
  /* @var $entity \Drupal\my_module\Entity\Foo */
  $target_id = $this->requestStack->getCurrentRequest()->query->get('target_id');
  $this->entity->set('bar_id', $target_id);
  $form = parent::buildForm($form, $form_state);
  $entity = $this->entity;

  return $form;
}


Rules: How to send an email when an OG membership field changes its value? I have some OG groups in my site. Each group is an online classroom.

The membership has a few fields (I use the default membership), and one of those fields is a select field with "approved" or "not approved" information about each student's final exam.

I would like to use rules to send an email to each student that change that OG membership field status to "approved". I want this workflow only for users of "exchange-student" role.

But I cannot do that because it seems that I didn't fetched the OG membership. I don't know what I'm doing wrong here.

This is my Rule:

Event:

After updating an existing og membership

Conditions:

Entity exists by property (Parameter: Entity type: OG membership, Property: Exam, Value: Approved)

User has Role
(Parameter: User: [site:current-user], Roles: exchange-student)

Action:
Send a message
(Parameter: Receptáculo: [site:current-user], Private message author: [site:current-user], Private message subject: Aprobaste, Private message body: Mensaje de Prueba)

What am I doing wrong? What am I missing?

Thanks for your help.

I believe the answer lies in your Conditions.

You are checking whether the current user has the appropriate role.

See if you can find a token for the user whose membership has been changed.


How to import multiple images with Feeds importer from CSV? I am using feeds importer for importing images. I have mapped the column "Image" in my CSV to the "Image: URI (field_image:uri)" field in my importer configuration. It workds for now when I put only one image URL in the CSV file, but how to import multiple images?

You can accomplish this with choosing a character to separate your image urls with in the CSV file and using the Feeds Tamper plugin "Explode".

Separate the image URLs in your CSV file with a certain character, for example a pipe character: "|". Your CSV file could then look something like this:

title,image
Lorem Ipsum,http://www.example.com/image1.png|http://www.example.com/image2.png
Install the module Feeds Tamper. Also enable the Feeds Tamper Admin UI module (included with Feeds Tamper).
Go the Tamper page of your feeds importer (/admin/structure/feeds/[importer_id]/tamper).
Click "Add plugin" for the "Image: URI" mapper.
For the plugin to add, select "Explode". As string separator, choose the character that you used to separate your image URLs. If you followed the example, then this would be the pipe character: "|". See also the image:

The explode tamper plugin cares that your input data (for example "http://www.example.com/image1.png|http://www.example.com/image2.png") is handled as multiple values.


Huge CCK field export/import I am having troubles exporting and importing a large numbers of CCK fields using Content copy (I need to have a file download/upload option).

Is there a SQL (or drush) command that can export and import CCK fields? I am interested in anything that bypasses the PHP memory limitations, 504 gateway time-outs, and what not.

Maybe I could still use HTTP from the webserver's CLI, something like wget  <export from content copy> >data.txt and wget --post-data data.txt <import via content copy>.

There's two ways to solve this...

Easy/tedious way, export only a few fields at a time using content copy and try to find out what's the max number of field you can select before running into php errors. This could be pretty cumbersome as you have a lot of field but this is the recommended/safe way.
Hard/dangerous way is messing up directly with MySQL. You need to be a little SQL savy to do this and rigorous to not forget anything.

So a little explanation for the n°2, the information your looking for is in these tables:

content_type_CONTENT_TYPE_NAME, this table store all non multi-valued fields of your CT (CT = Content Type).
content_field_FIELD_NAME, there's one of these tables for each of your field that is set to be multi-valued.

Internals CCK tables:

content_node_field_instance, stores definitions of each of your fields (label, weight, widget, name of CT...)
content_node_field additionals settings (required, multivalue, db storage...)
content_group_fields and content_group informations regarding the grouping feature.

So now you have the table, now comes the tricky part.

If your CT and fields doesn't exists on the destination, it's quite easy, just export the tables of your CT and fields in SQL, export the content of the internal CCK tables using your CT and fields names.

If your CT or any of your fields (remember that fields can be shared between CT) exists on the destination you have to evaluate the changes and update the table structure to apply these changes, I think this easy pretty difficult to deal with so I wouldn't recommend you to do so.

Good Luck.


I need to display a different link for anonymous users and register users for same content I have a webform containing a link. I want to change the link depending on the users accessing the webform.
For anonymous users, the link should point to user/register?destination=[current page]; for authenticated users, the link should point to form/event-registration.

In build > elements you will need to create 2 html markup or Advanced HTML/Text elements

Each one will have the links mentioned

There is a setting access that you can choose who has access to it

For the other link you can choose anonymous

For one of the elements you will choose authenticated

If this solution is not satisfactory 100% you will need to override webform


Why does The special menu items module break the bootstrap dropdown? Hi Guys this is my issue on my parent menu item i am using the<nolink>shortcode to leave the link blank however in my tree i have 3 items underneath it.
If i add <nolink> the menu item becomes wrapped in a span tag with no link and the dropdown does not work. if i give the parent a link the dropdown works but only if i select the parent first.
Is this css or a js issue?

It's because bootstrap is expecting an anchor tag and by default Special Menu Items provides a span tag.

Go to admin/config/system/special_menu_items and specify an anchor tag as shown below:


display custom user fields with twig? I added for users a couple of fields : field_telephonenumber and field_company

how can i display them in user.html.twig or maybe page.html.twig

You can configure which fields are displayed in the view mode compact:

admin/config/people/accounts/display/compact

Then you can in twig display all fields with

{{ content }}

or single fields with

{{ content.field_example }}

To put a user in a page template you can use Twig Tweak:

{{ drupal_entity('user', 1, 'compact')

The third parameter is the view mode and you can use theme hook suggestions to catch this with your custom user twig to make adjustments of the user fields.


Conditional Stylesheets Set-up: Using the Module Problem

I'm trying to set-up conditional stylesheets. I've followed the instructions but it's still not registering. What have I done wrong?

Set-Up

I installed and enabled the conditional stylesheets module. I'm running a Tao sub-theme.

I then added the following lines to my theme.info file:

//these are my original stylesheets
stylesheets[all][] = reset.css
stylesheets[all][] = typography.css

//these are my conditional stylesheets
conditional-stylesheet [IE][all][] = styleie7.css
conditional-stylesheets [if !IE][all][] = style.css

I then cleared my cache and no style sheets were loaded.

At the moment I'm just trying to have one stylesheet for IE and one for everything else.

I took the syntax from the [link] in the conditional css directory.1

NOTE:

It's not clear whether you should put

conditional-stylesheet OR stylesheet-conditional

The documentation says one, a lot of posts suggest the other. However I can't get either of them to work.

Assuming you are using the conditional style module the format would be

; Set the conditional stylesheets that are processed by IE.
stylesheets-conditional[lt IE 7][all][] = ie6-and-below.css
stylesheets-conditional[IE 9][all][] = ie9.css
stylesheets-conditional[IE][print][] = ie-print.css
stylesheets-conditional[(gte IE 9)|(gt IEMobile 7)|(!IE)][all][] = modern-browsers.css

And there should be no space between the conditional-stylesheet and [IE].

If that doesn't work then you should make sure that the stylesheet it is referencing can be loaded. The stylesheet lines don't show up if the stylesheet doesn't exist or cannot be opened.


How to render a view programmatically and set as node field? I am trying to render custom view and put the result as content of the node.

Here is my code

function my_theme_preprocess_node(&$variables)
{
    if (isset($variables['node']) && $variables['node']->getType() == 'custom_type') {
        $reference_view = $variables['node']->field_reference_view->first();
        if (!empty($reference_view)) {
            $view_name = $reference_view->getValue()['value'];
            $view = \Drupal\views\Views::getView($view_name);
            $view->setArguments(array());
            $view->setDisplay('block');
            $view->preExecute();
            $view->execute();
            $variables['embedded_view'] = $view->buildRenderable();

        }
    }

}

But this code shows only debug message and when I try to get output in a twig template file it is empty

    {{ node.embedded_view }}

What is wrong with my code. How can I render a view and set it as a content of node or just node field in order to print it in a twig template file.

Because your variable reference is incorrect. It should be:

{{ embedded_view }}

Since you added it to the $variables array as $variables['embedded_view'].

As an alternative you can get the Twig Tweak module. Example on the docs page:

{# You can pass arguments to the view if needed. #}

View:

{{ drupal_view('view_name', 'page_1') }}


Override login form submisssion I try to call a SOAP web service before an users authentication. I've try this

function beneficiaire_user_login(&$edit, $account){
    die('hello from login override'); }

Unfortunately, if my SOAP request is bad I cannot prevent the authentication.

What I want to do is:
click the login > check via a WS is the user exists > if yes create the user on Drupal, else show an error message.
Can I perform this action before the session opening ?

With a form_alter hook, it doesn't works, I do not see the "form alter" text

function beneficiaire_form_alter(&$form, $form_state, $form_id){
    exit('form alter');
}

Thanks

I'm working on something similar. I think you can do this using a validation rule.

/**
 * Implements hook_form_alter().
 * We replace the local login validation handler with our own.
 */
 function beneficiaire_form_alter(&$form, &$form_state, $form_id) {
    // In this simple example we authenticate on username to see whether starts with dave
    if ($form_id == 'user_login' || $form_id == 'user_login_block') {
        $form['#validate'][] = 'beneficiaire_user_form_validate';
    }
 }

/**
 * Perform validation rules and set error states
 */
function beneficiaire_user_form_validate($form, &$form_state) {
    if (!beneficiaire_authenticate($form_state)) {
        form_set_error('name', t('You are not on our super-secret list.'));
    }
}

/**
 * Custom user authentication function
 */
 function beneficiaire_authenticate(&$form_state) {
     // Check the webservice here and return false if user not found.
 }


What is the difference between base tables and data tables for content entities? Recently, Views was updated to use data tables (the data_table annotation on @ContentEntityType) by default. See the change record at https://www.drupal.org/node/2433153.

This caught me out since I had both defined on my entity. I hadn't thought much about it, and I don't even know which example got me to do that. I think I may have based mine off \Drupal\comment\Entity\Comment.

Anyway, what's the difference in terms of when they get used? It seems that, despite having defined data_table, all my data was being saved in the base_table anyway, and this caused Views not to work until I removed the data_table property from my @ContentEntityType definition altogether.

It seems my fields ought to be using data_table. What did I do wrong in my entity? I'm porting a module and thus using 8.0.0-beta9.

My guess is that you didn't actually set the translatable flag to TRUE. The data_table is only used then, but I guess views gets confused if you have it set but the entity type is not translatable, sounds like a bug in views but it also doesn't make sense to define the table and not have your entity type translatable.

The difference of those two tables is that it contains a row for each translation of your entity type. For example, {ńode} has just the nid, vid (which is the current revision), type and uuid. All the other fields are in the data table, like the node title, status, changed date, and so on.


Drupal 7 check all solution for 2017, is it possible? I looked online, tried the checkall module, nothing works, found info from posts in 2013...

Is there a way to provide a Select All / Check All checkbox for a field that displays multiple checkboxes in Drupal 7?

Nothing conclusive, just half baked hacks that might or might not work.

Any solution that works for 2017?

Even the Google chrome check all extensions are buggy...only thing that works in older versions of firefox for this...

Any suggestions?

You want to create a custom module for this

my_module.module

function my_module_form_node_form_alter(&$form,&$form_state,$form_id) {
     if($form['#node']->type == "my_content_type") {
        $form['#attached']['js'][] = array(
          'data' => drupal_get_path('module', 'my_module') . '/js/example.js',
          'type' => 'file',
        );
     }
}

Change all my_module to the actual name of your module
Change my_content_type to the actual name of your content type.

my_module/js/example.js  (using code from the link you gave)

(function ($) {
    Drupal.behaviors.selectAll = {
      attach: function (context, settings) {
        $('body.page-node .form-type-checkboxes > label').click(function() {
            $(this).nextAll('.form-checkboxes').find('input[type="checkbox"]').trigger('click');
        });
      }
    };
}(jQuery));

If it doesn't work, try changing the line

$(this).nextAll('.form-checkboxes').find('input[type="checkbox"]').trigger('click');

to

$(this).nextAll('input:checkbox').trigger('click');


Search a content type based on certain criteria I am faced with a challenge for my company's new website.  We are using Drupal 7 and here is the situation:  We have approximately 250 doctors in our group and I am tasked with creating a custom search page where users can search our doctors based on certain criteria (e.g. specialty, gender, location, etc.).

I have created a content type of "doctor" and entered all of the physician data that will be needed.  My question is:  how is the best way to go about setting up the search that I want to give my visitors?  I would assume that I need to restrict a search based on content type, but how can I throw the additional search parameters in there?  Are there some modules that give very granular options like I'm looking for, or am I looking at having to create and code a custom module??

I'm a little lost and any direction would be very helpful.

You will need to make use of the views module  to create the functionality you are looking for.

Create a new display of type page
Then select show content of type [Your content type]
Add fields you want users to be able to search on
Create filters and expose the filters


After updating from drupal 6 to 7: No content types under node/add I am updating a Drupal/Tripal site on a test system. When I try to add content after migrating core using /#overlay=node/add or /node/add I get:

You have not created any content types yet. Go to the content type creation page to add a new content type.

However, under content types it lists all my content types (page, article, blog, etc).
I notice that this looks very similar to
No content types showing under 'Add content'

but the accepted answer doesn't help me, because it is not about the state after a d7 update, and I don't know how to apply the steps in a d7 install.

The Navigation contains:
Add content
Blog entry
Book page
Forum topic
Page
Poll
RNAi
Story

Sub-type links like node/add/page work, still node/add lists no content types.

I finally managed to fix this by accident while trying to fix a different issue.

Following this post: https://drupal.stackexchange.com/a/82222/25238
Similar to https://www.drupal.org/node/997444

I first tried drush eval 'menu_rebuild();' drush cc menu which didn't have an effect, then I found the hint in a comment by nilsun to the above post, that sometimes a complete reset might be necessary. This seems to be caused by a corrupt menu system.

$drush sqlc
Password for user user:
psql (8.4.20)
Type "help" for help.
## if you want to try to keep your own menus you could
## first try:

DELETE FROM menu_links WHERE module = 'system';
# edit: typo, it's module, not menu
## Tested, did keep my custom menus

## D_ELETE FROM menu_links # Don't this will delete your custom menus too!
DELETE 748
d7=# DELETE FROM menu_router;
DELETE 909
d7=# \q
$ drush updb
No database updates required                                                          [success]
'all' cache was cleared.                                                              [success]
Finished performing updates.                                                          [ok]
$ drush cc menu
'menu' cache was cleared.                                                             [success]
$ drush eval 'menu_rebuild();'
$ drush cc menu
'menu' cache was cleared.                                                             [success]

Maybe one or two steps can be omitted, but that brought back the content types under "Add content", Edit Warning: while some of my self defined menu entries disappeared, but this should be easy to fix editing them manually.


Creating Custom Modules tutorial doesn't work - help! I'm trying to teach myself how to create a custom module using Drupal 8, and followed the instructions on their website at this Drupal.org documentation page

I created the folders, hello_world.info.yml, hello_world.routing.yml and HelloController.php pages and have been over them time and time again looking for typos, but can't find any.

I've got to the step to add add a routing file.  The module appears in the Extend area, but when I enable it and click Install, after a short pause I get the error "The website encountered an unexpected error. Please try again later."

When I go back to thet Extend, the module is ticked and I presume installed.

However when I then try to display it using the URL "/hello", I get a "Page Not Found".  Not only that, but every time I try to clear the cache, there is a delay and I get the same "Website encountered..." error again.  I can only clear the cache by uninstalling the module.

I've included the content of the three files below:

/modules/hello_world/hello_world.info.yml

name: Hello world Module
description: Creates a page showing "Hello world"
package: Custom
type: module
core: 8.x

/modules/hello_world/hello_world.routing.yml

hello_world.content:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloController::content'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

/modules/hello_world/src/Controller/HelloController.php

<?php
    namespace Drupal\hello_world\Controller;

    use Drupal\Core\Controller\ControllerBase;

    class HelloController extendes ControllerBase {

        public function content() {
            return array(
                '#type' => 'markup',
                '#markup' => $this->t('Hello World'),
            );
        }
    }

Does anyone have any suggestions what might be wrong?

class HelloController extendes ControllerBase {

You spelled extends incorrectly.


Injecting Views blocks into another View template I have a View containing the latest news in a very standard way (ie: one below the other)... I would like to inject, at certain points, other blocks containing other views (ie: latest news with a certain tag), like in this image:

http://i.imgur.com/6wghpJH.jpg

An easy but impractical approach would be to create different views: one for the latest 2, then one for another 3 news with an offset of 2, etc...

But is there some magic that the new D8 theme layer can do to make this more practical?

You could create a new View field in modules/yourmodule/lib/Drupal/yourmodule/Plugin/views/Field and "attach" it via hook_views_data_alter() or hook_views_data(). This field would returns a hardcoded view or dynamic, depends on your needs. Another way would be to use Views templates.


Custom validation for profile type? I used profile2 module and create some profile types,in one of them I have a custom field require custom validation .
I did use drupal validation with custom validation function .
Lets suppose  I have a field with name  'nationalcode' if it was form element just need this in my custom module hook_form_alter(&$form,&$form_state)

$form['field_nationalcode']['#validation'][] = 'my_custom_validation_function';

And determine my_custom_validation_function function with my custom validation

function my_custom_validation_function(&$form,&$form_state) {
  if(!mycustomvalidation)
     form_set_error('field_nationalcode','my custom message');
        // I am not sure mayebe this one
     form_set_error('nationalcode','my custom message');
 }

But really what I should do in profile type cusotm validation?

I  set #validation  but How can i set form_set_error with profile type? .I means what i should  use in first parameter in form_set_error ?

I found The good solution for validate nested form elements
according to drupal 7 form_set_error api need to use

form_set_error('myporifletypename][myfieldname', 'my error message');

As example

 form_set_error('user_info][field_nationalcode', 'Your National code not valid');


Force Drupal to attach Drupal behavior to new ajaxed content [only Drupal.attachBehaviors() is not working the right way] I was doing lot of posts on drupal.org about this topic, but unfortunately in the wrong context.

Ajaxed content is not attaching needed JS and CSS (forum)
Ajaxed content is not attaching needed JS and CSS (issue)

I think that is not the problem, so i try it with a different approach, and maybe this could be the solution. Loading the whole PHP Page and extract a certain div with ajax didn't works the right way. So i thought, that i could let drupal load just the content and inject it with ajax into the div. I made a query with the hook_preprocess_page and hook_preprocess_node that is looking for a "ajax=1" in the requested URL and then only gives out the content without the whole page. And now with help of certain tpl.php files, in theory, i could limit the output of drupal to only $content. And here is the problem. My approach is working even when i leave the tpl.php files the original way, but removing the "$content" from node-ajax.tpl.php. With "working the right way", i mean that drupal doesn't reload the whole page, but off course not the content. But i can not explain that to myself, cause in the $content variable, so i thought, is only the html of the generated content. So my question is, how can i limit the output of drupal, to just the content, or am i doing the wrong steps to get this working. Here is the module and js file i'm using: my_ajax.module:

<?php

function my_ajax_init()
{
    drupal_add_js(drupal_get_path('module', 'my_ajax') . '/my_ajax.js');
}

function my_ajax_preprocess_page(&$vars, $hook)
{

    if (isset($_GET['ajax']) && $_GET['ajax'] == 1)
    {
        $vars['template_file'] = 'page-ajax';
    }
}

function my_ajax_preprocess_node(&$vars, $hook)
{

    if (isset($_GET['ajax']) && $_GET['ajax'] == 1)
    {
        $vars['template_file'] = 'node-ajax';
    }
}

my_ajax.js:

Drupal.behaviors.my_ajax = function (context) {
    $('#content-group-inner .node a').live('click', function (e) {
        var url = $(this).attr('href');
        //$('#content-region-inner').slideUp('slow');
        $('#content-region-inner').empty().html('<img src="ajax-loader.gif" style="margin-left:50%;"/>');
        xhr = $.ajax({
            data: 'ajax=1',
            type: 'GET',
            url: url,
            success: function (data) {
                $('#content-region-inner').html(data);
                Drupal.attachBehaviors(context);
            }
        });
        return false;
    });
};

Please help me with this. Every suggestion is appreciated.

I've got it.
This is working the right way:

Drupal.behaviors.my_ajax = function (context) {
    $('#content-group-inner a').live('click', function (e) {

        $('#content-group-inner a').addClass('my_ajax-processed');
        var url = $(this).attr('href');
        $('#content-region-inner').empty().html('<img src="ajax-loader.gif" style="margin-left:50%;"/>');
        $('#content-region-inner').load(url,'ajax=1',function() {
                        Drupal.attachBehaviors('#content-region-inner');
                        });
        return false;
        });
   };

Thank you for all your help.


Make Author Field in Comments Required How I could make from my template.php author/user field in comments required for those who are anonymous users

I tried with this but it didn't work for me

  function MYTHEME_theme() { $form['author']['_author']['#required'] =
  TRUE; }

I've been searching around but can't find a proper answer :/

You have to create a little module and implement hook_form_FORM_ID_alter() to alter the form.


How to allow for manual HTML & CSS changes? I'm using CK Editor to insert a table into my content (Body field).

I would like to set a background color, so I extended the style="width:100%" to be style="background-color: #FFEEE4; color: black;width: 100%". And this by clicking on Switch to plain text editor.

But now, once I save, the background-color style disappears again (Test Format FULL HTML). How can I make it stick?

go to:
/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)
/admin/config/content/ckeditor/edit/Full (for Full HTML)
Then under Advanced Content Filter, select disabled.

If the above does not do it, depending on which one you are using (filter or full html) You need to go to
/admin/config/content/formats/filtered_html
OR
/admin/config/content/formats/full_html
Uncheck the correct faulty and chopped off html box.


How can I theme some blocks with the same theme? I'm seeking the best practises for theming some blocks using a same template file, but my problem is that blocks may not be used in a same region, and they can also be used in one module that has a bundle of different blocks with different themes.

How can I achieve this?

Block Theme module will be really helpful. You have a select box where you can choose different tpl.php files for each block you configure


Tree structure based on parent-child relationship among content types I want to store technical_specifications of various products. As different product categories obviously have very different types of specifications, what I had in mind was a tree structure of content types, only to find out that Drupal's content types don't support parent - child relationship out of the box (ie. a content type cannot inherit fields from another one)
I'm thinking something along the lines of
- PRODUCT
- price
- weight
- url
    - COMPUTER
    - (inherits everything from product, plus)
    - processor
    - RAM
    - (...)
        - LAPTOP
        - (inherits everything from computer, plus)
        - battery
        - touchscreen?
        - screen size
        - (...)
    - TV
    - (inherits from product, then)
    - screen size
    - contrast ratio
    - resolution
    - refresh rate
    - (...)
    - BOOK
    - (inherits from product, plus)
    - author
    - title
    - genre
    - publication date

...you get the idea.
What is the 'Drupalish' way to achieve this?
I could, of course, create separate content types for every product category (since you only create every content type once, and you can re-use existing fields, it's not a whole lot of extra work), but that wouldn't reflect the structure and hierarchy of the product categories
Or I could dump every field in one big content type, make them optional and only fill out what's relevant to that specific product (or category, rather)
Neither of these sound optimal. Any better ideas?
thanks!
(I'm running Drupal 8, btw, if that is of any importance)

I think there is a lot more to unpack here than it seems at first sight.
Usually when we talk about inheriting things it's actual data referencing other data (sets of data), it's not structures inheriting structures automatically.
Just because a laptop shares properties with a computer doesn't mean that a laptop node will reference a particular computer node, so it's not data referencing data.
Although you can choose to implement things in different ways, and there are usually reasons why you should go with a chosen option, I think in this case it makes the most sense to create a separate structure for each data set that is "standalone".
Without any other info about your site, assuming from your current description and my past experience building sites I would structure it this way:
Content types and their fields:
COMPUTER
- processor
- RAM
- (...)
LAPTOP
- processor
- RAM
- battery
- touchscreen?
- screen size
- (...)
TV
- screen size
- contrast ratio
- resolution
- refresh rate
- (...)
BOOK
- author
- title
- genre
- publication date
PRODUCT
- price
- weight
- URL
- !! Entity Reference Field !!

Notice the computer fields in laptop that are the same as in computers are repeated under laptop. You can reuse existing fields, I recommend you do especially if you plan to do any comparisons between different nodes that may be different category product but share the same properties/fields. But there are no field references between computer and laptop, they are independent from each other, even if they share some properties.
Different product categories have different product properties, and it makes sense to keep them separate.
When selling products they all share the same properties with regards to selling, and when selling a product you're selling one set of data, not the structure. You're selling one specific computer, not category of computers in general.
That's why it makes sense to have the saleable entity as a separate structure, and you pull specific data from a particular node that exists of some product category.
Through the Entity Reference field you can show entire node information on the Product node that references it.
Structurally you could have a specific computer node, lets say node ID 5 with all the computer fields describing it (RAM, CPU).
Then you would have another node, of the Product type, node ID 6 for example, that would list the price and reference node 5. Node 6 would show everything on its page. Node 5 can even be hidden from public, better SEO whatnot...
With the module Inline Entity Form (which was created with excommerce in mind) or some similar solution you can solve the editors problems of having to first create the "computer" node before creating the "sell computer" node. With this module you will be able to create both at the same time, in one go.
This way you're fast when entering content and maintaining your site, while your structure is still flexible enough that it's easy to create different lists you might need with Views (using Paragraphs and keeping everything in the same type can hinder you there) and you can change things in one place because it's all kept in sane compartments.
For example if in the future you need to add some sales tax field you can do it on the Product type and it will appear for all saleable products, you won't have to edit many CTs (in case you have them all separate without ER to product) and you won't have to do complex Views to gather different Paragraph interconnections just because you have everything in one Conent Type.
If you've read it, I think it will help no matter what you decide because it at least gives you some other considerations to think about. If I've been clear enough that is :þ


Using Views for a custom table with multi-value fields I have a custom table with two columns - the primary is simply entity IDs (nids), and then there is a data column, but it it can be a multi-value (from 1 to anything).

How can I structure the MySQL table and create a view that will blend a list of entities (nodes in my case) with data from the custom table without losing their multi-value character (probably using relationship)?
Basically I need to achieve that next to a node with a given field I can also show data (separated by commas or otherwise) from the multi-value column from my custom table.

There is some excellent help about doing this with single-value columns at Using views with a custom table/schema but I guess it is a bit more tricky with multi-values.

You'll probably need 2 MySQL tables (to overcome the many-to-many relationship): one to link the nids to data-ids and one to link the data-ids to the actual data. One with three columns and the other with two: (primary key, nid, data-id) and (data-id, data).

    +------------+-----+--------+     +---------+--------+
    |nid-data-id | nid | data-id|     | data-id | data   |
    +------------+-----+--------+     +---------+--------+
    |1           | 1   | 1      |     | 1       | value  |
    |2           | 1   | 2      |     | 2       | value  |
    |3           | 2   | 1      |     +---------+--------+
    +------------+-----+--------+

This way  you can use either multi-select or new values every time. Linking these tables can be done in the same manner as the article you provided (linking two can be found at Views - join tables or the views table API ) but I do not have any experience with that.


Drupal 8 multi fields in one fields can Someone explain how can i make one field in Drupal 8 that can contain multiple fields in it... I am not allowed to use Paragraph module. I want to make it full programmatically, By the way i know how to make simple field in Drupal 8 but don't know how to set schema or form form dynamic field that can have multiple fields in it.
 For Example when we want to add some field in user or in node, we go to ~/fields/add-field and then select the field type, after in the field setting i want to have one form element that says add filed and the type of the field. and after saving setting, i will generate the field widget and formater depending on the field type selection that i made before.

Is there a solution for this problem (only programmatically)?

If you prefer another approach, a little more clean and following the Drupal structure, you can use Inline Entity Form to do that.

I don't like Paragraphs and Field Collection for just one reason. They don't follow the way that Drupal storages data in DB. If you open your database and search for the tables that this modules create, you will be able to see some strange patterns.

https://www.drupal.org/project/inline_entity_form


drupal_add_js and variables into anonymous functions, objects undefined? Pulling my hair out. Read a lot of stuff about scopechain and closure to tackle this one myself. And as i understand at some level, i can't get this to work.

I wrote a module for likebuttons (like facebook twitter etc). It's working ok, but I want to make it more generic and multilingual. I did the following. In my facebook function I have this:

<?php
  $lang = 'en_EN'; //

  // Load javascript
  $settings['lang'] = $lang;
  drupal_add_js(array('mymodule' => $settings), 'setting');
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/myscript.js');
?>

This is working ok. The javascript gets loaded and the $settings['lang'] is passed to browser too (as I can see in chrome console it gives me 'en_EN' on Drupal.settings.mymodule.lang).

In myscript.js script I have the following (simplified to be a more generic question

(function() {

  var language = Drupal.settings.mymodule.lang;
  console.log(language); //undefined

}());

UPDATE:
So it's anonymous.... All those terms.
Ok, got the object inside now. Now i got to figure out how to get the 'en_EN' from the object.

Updated script:

(function(language) {

var my_var = language.settings.mymodule.lang;
console.log(my_var); // undefined
console.log(language); //Object { settings={...}, behaviors={...}, locale={...}, meer...}
console.log(language.settings); //Object {}
console.dir(language.settings) // There are no underlying objects
}(Drupal));

Here language contains the complete object drupal has passed. (I can see that in console).

Why can't I go in the object language like normal and get my value by using language.settings.mymodule.lang?

Seems like Drupal.settings is empty inside the anonymous function, but has all elements there in the DOM tree. I don't know what causes this to be an empty object inside an anonymous function.

As of Drupal 6 javascript is put inside function that we assign as a property of Drupal.behaviors. Example,

Drupal.behaviors.myModuleBehavior = function (context) {
  //Do some fancy stuff
};

Drupal 7.x:

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
    // Apply the myCustomBehaviour effect to the elements only once.
    });
  }
};

So your code should be

(function($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      var my_var = Drupal.settings.mymodule.lang;
      console.log(my_var);
      console.log(language);
    }
  };
})(jQuery);


Store Fields in an external database I'm interfacing an external database with Drupal 7.  I have created custom entities and custom fields to represent the tables in the external database.  Is there a simple way to set the fields up so all CRUD uses the external database?

I still want to use Drupal's default field_sql_storage.module, but have it switch to the external database and back for these fields automatically.  Can I say "for this field, use this other database".

Something simple like:

function mymodule_field_info() {
  return array(
    'customfield' => array(
      'label' => t('My Custom Field'),
      'description' => t('This field stores text in the external database.'),
      'settings' => array('max_length' => 255),
      'instance_settings' => array('text_processing' => 0),
      'default_widget' => 'text_textfield',
      'default_formatter' => 'text_default',
      // Simple setting to change database.
      'database' => 'externaldb', // From settings.php $database connections.
    ),
}

The hard way is to create a custom storage backend and use it for these fields like the Mongodb module. I've tested this and it works, but it seems like there should be any easier way if you want to use Drupal's default field_sql_storage.module.

Would the strategic placement of db_set_active() allow me to avoid creating a full custom storage backend?

There is a Field Storage API you can use for external storage in fields.


Drupal 8: "Page cache maximum age" is not working for anonymous users I have set a page cache maximum age for anonymous users in Drupal 8, but it seems not to have any effects. Accesing the pages as an anonymous user, changes are visible immediately, and I can't see any headers about max-age on the source code.

I have installed some cache modules as Internal Dynamic Page Cache,     Internal Page Cache and Supercache, but I don't think these should interfere with the cache on the client side.

Any suggestions?

There was discussion in the chat, but there are still some things that can be answered.

The maximum age setting actually has not much to do with the built-in caching mechanisms of Drupal, as confusing as that is. It only controls the Cache-Control max-age header that is sent if the page is considered cacheable.

If you don't see a X-Drupal-Cache: HIT/MISS header in the response then that means your page is not cacheable. There are a number of things that can cause that, check if you have a session cookie (if yes, you need to figure out what's in there and who sets it), check that no module that you are using disables the page cache. For example captcha.module does that if you display a captcha as that can't be cached (not something like the built-in image captcha at least).

If you see that header then it is working. The Page cache modules actually don't care about that setting, they cache the page forever. However, any relevant change on the page automatically invalidates that page and fresh content is served. See https://www.drupal.org/docs/8/api/cache-api/cache-tags for more information on how that works.


Fatal error wheen running update.php Kindly assist me in solving this error. It appears once I try to run update.php

  Fatal error: Class CToolsCssCache contains 1 abstract method and must therefore be declared abstract or implement the remaining methods

This is how my css-cache.inc file looks like;

<?php

/**
 * @file
 * Custom cache implementation for the CTools CSS cache.
 */

class CToolsCssCache implements DrupalCacheInterface {

  /**
   * {@inheritdoc}
   */

  public function clear($cid = NULL, $wildcard = FALSE) {
    // Only clear the caches if the wildcard is set, this ensures that the cache
    // is only cleared when the full caches are cleared manually (eg by invoking
    // drupal_flush_all_caches()), and not on a cron run.
    // @see drupal_flush_all_caches()
    // @see system_cron()
    if ($wildcard) {
      ctools_include('css');
      ctools_css_flush_caches();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function get($cid) {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getMultiple(&$cids) {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function set($cid, $data, $expire = CACHE_PERMANENT) {
  }

}

I think it is affecting the site such that any updates done cannot display on the live site. I will really appreciate your help.

there are a few steps you need to do:

Please upgrade you  Drupal Core
Apply this patch: Patch to your Ctools Module, you can be found the file here /includes/css-cache.inc


Where is the entity in code field? [Display suite module] I create a code field in Display Suite module and I need to insert a format_plural in it like

print format_plural([node:comment-count],  '1 Comment',  '@count Comments');

but token do not work in php block so I tryed:

dsm($node);
dsm($entity);
dsm($object);

but they do not work because 'Undefined variable' error.
Where is the node variable in display suite code field?

How can I achieve this output?

There is the screenshots

SOLVED!

I needed to enable 'Display Suite Format' module.
If enable it give me a new text format 'Display Suite code' which give an $entity variable inside a code field!


Node form – self changing theme I'm adding different way of node editing so I have this code in my module:

$items['node/%node/edit-full'] = array(
'title' => 'Full edit',
'page callback' => 'node_page_edit',
'page arguments' => array(1),
'access callback' => 'node_access',
'access arguments' => array('update', 1),
'weight' => 0,
'type' => MENU_LOCAL_TASK,
'file' => 'node.pages.inc',
'file path' => drupal_get_path('module', 'node'));

What is disturbing.. it changes theme from admin to regular. Instead of Seven Theme I see regular website theme. Am I missing some variable in my definition?

You need to implement hook_admin_paths() to tell Drupal to use the admin theme for your URL pattern:

  Modules may specify whether or not the paths they define in hook_menu() are to be considered administrative. Other modules may use this information to display those pages differently (e.g. in a modal overlay, or in a different theme).

In your case the code would look a lot like this:

function MYMODULE_admin_paths() {
  $paths = array(
    'node/*/edit-full' => TRUE
  );
  return $paths;
}

Once you've cleared the caches your pages should now be using the admin theme.


Administrative page still accessible by anonymous users? It's almost 2 years I don't program modules in D7.
I'm creating a module that shows 2 forms.
One is public (and to's working) and one is a setup form under /admin space.
The issue is that the one in the admin still accessible to anonymous, even when I check the checkbox into the "permission" page.
Could you help me please to find out what I miss?

Please here part of the code

function MyModule_permission() {
  return array(
    'administer MyModule' => array(
      'title' => t('Administer MyModulemodule'),
      'description' => t('Perform administration tasks for MyModule module.')
    ),
  );
}

here below the address of the 2 forms

/**
 * Implements hook_menu().
 *
 * Displays module information.
 */
function MyModule_menu() {
  $items = array();

  // It should be accessible by everybody
  $items['fillin'] = array(
    'title' => 'Participation Data',
    'description' => 'Please fill here below the fields in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_form'),
    'access callback' => TRUE
  );

  // it should be accessible only by admin
  $items['admin/config/setup_collection'] = array(
    'title' => 'Participation Text',
    'description' => 'Text for the presentation',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_setup_form'),
    'access arguments' => array('administer'),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE
  );

  return $items;
}

Here below the setup form with the default content, that should be accessible only by the administrator

/**
 * Implement hook_form()
 *
 * Creates the form for the setup page
 *
 */
function MyModule_setup_form($form, &$form_state) {
  $form['MyModule_message'] = array(
    '#type' => 'textarea',
    '#title' => t('TEXT '),
    '#wysiwyg' => TRUE,
    '#default_value' => variable_get('MyModule_message', 'Subscribe fill in the form below'),
  );

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('SUBMIT'),
  );
  return $form;
}

Here below just a part of the form accessible by the anonymous user

/**
 * Implements hook_form().
 *
 * Creates the form for the user.
 */
function MyModule_form($form, &$form_state) {

  global $conf;

  $form['MyModule_main_message']['hello'] = array(
    '#markup' => variable_get('MyModule_message'),
  );

  $form['first_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Put your first name'),
    '#size' => 50,
    '#maxlength' => 50,
    '#required' => TRUE,
  );

            ...
            ...
            ...

The problem is you are setting
'access callback' => TRUE
this gives access to all.
I also to sure that administer is a valid permission in 'access arguments' => array('administer'), instead try 'access arguments' => array('administer site configuration'),.


Has Pressflow 6 been discontinued? There is a week since Drupal 6.30 is released to fix some XSS vulnerability, but Pressflow is still on 6.29.

I am wondering if it is discontinued. If so, are there any new forks that up to date?

There are a few questions here:

What was the timeline of events for the 6.30 release of core and Pressflow?

Core security release on January 15th, 2014 which had been in the works for a few days beforehand and the Pressflow maintainers are welcome to participate in that process to help them review the patch and be able to apply it quickly
January 15th, 2014: Some commits and pull request for Pressflow 6 to incorporate that change
January 21: a merge commit merging in that pull request and probably making the tag

Why isn't there news about Pressflow 6?

Well, it depends on where you want to go to get news and what your expectation is. Drupal 6 and Pressflow 6 are pretty slow in terms of news. They are stable except for these security updates. I think it's reasonable that the promotion/updates about it are minimal beyond what is necessary for development. If you want to know what's going on (including the sate of the last release) check the issues and pull requests. And if you went there on January 15th you'd see a pull request that you could try out to get the security update and help in the process of releasing the next version by providing a review.

Will there be timely updates moving forward?

Peter Wolanin (and Gabor Hojtsy, I'm told) are now able to commit changes to the Pressflow repository on github. It seems likely that they are interested in Pressflow because many of the users of Pressflow are clients of Acquias. Peter and Gabor are both Security Team members (and Gabor a D6 maintainer) who stay aware of the core security releases. So, I think it's safe to say that updates will flow more quickly in the future.


Assign field permission to individual users? Here the idea is to avoid defining dozens of roles to account for delicate permission requirements of users.

Say, on a certain node that has 100 fields, a webmaster may eventually need to define several hundreds of permission sets, many of them are needed for very few users on and ad hoc manner. Being able to define field permissions for particular users gives the webmaster ultimate flexibility and avoids insane proliferation of roles.

I appreciate your hints about this possibility.

You can manage this with #access if you're using hook_form_alter to make and manage the fields.

  Description: Whether the element is accessible or not; when FALSE, the
  element is not rendered and the user submitted value is not taken into
  consideration.

Another idea is get help of access callback in hook_menu

  "access callback": A function returning TRUE if the user has access
  rights to this menu item, and FALSE if not. It can also be a boolean
  constant instead of a function, and you can also use numeric values
  (will be cast to boolean). Defaults to user_access() unless a value is
  inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK
  items can inherit access callbacks. To use the user_access() default
  callback, you must specify the permission to check as 'access
  arguments'

The idea is to make a function that resolves permissions for individual user for certain pages.


How to set a term reference field value from a text field with Rules? In the user entity, there are 2 fields: a single-valued field_department_text A (a text field) and a multi-valued term reference field_department B.
Now, I need to use Rules to append A's value to B when a user was created. I tried, but failed.

Looks like you could just use the "add to list" Rules Action.

For multi value fields you should not use "Set a data value" (which is possibly what you've tried, a common mistake when using Rules for such fields).

Refer to the answer to "How to set multiple values to an unlimited Term Refence field with Rules" for "some" more details ...


Pass multiple ids as Views Arguments in the Rule action Save PDF as file on server I'm using views PDF to print out a list of nodes on a single PDF, one per page.
Now I have more than 1000 nodes/pages on a single generated pdf, so I'm trying to use VBO and Rules to create a view where I can filter/select the nodes I need and execute a Rule component that saves the resulting pdf on the server and sets a field "printed" to "yes" on those nodes.

The problem is that every time I fire my Rule the saved PDF has just the last selected node via VBO.
On the "Views Arguments" of the "Save PDF as file on server” action, instead of [node:nid] I've tried writing manually some node ids (eg. 1,2,3...)  and it works fine: the saved PDF has all the written nodes printed out.

Probably I have to write some PHP code to print the VBO-passed ids as a single csv argument.
I've tried something like this and doesn't work, blank pdf page. How to debug?

<?
$vboNids=arg(1);
echo implode(",",$vboNids);
?>

Thanx in advance.

If I would like to save those files using vbo then I would try to create drupal action in your own module. And in this case you wouldn't need rules. Or you could revoke rules event if you would want to with rules_invoke_event function;

function mymodule_action_info() {
  return array(
    'dosomethinggoodfunction' => array(
      'type' => 'node',
      'label' => t('Do something'),
      'configurable' => FALSE,
      'triggers' => array('node_save'),
    ),
  );
}
function dosomethinggoodfunction($node) {
  // function to do some good stuff.
}


Best practice for custom module variable names? I've gotten into the habit of doing pretty robust configuration panes for my modules now, and I'm finding the variable names & management to be quite the pain.

I have variables like mymodule_section_subvar_varname_type_context and I not only loose track of the order of the elements in my variable names but I feel as if having a variable name that long is a design flaw.

I've been considering using a serialized array in a variable mymodule_section_settings in conjunction with a set of functions that make it easy to maintain that array but I'd love some input in what (if any) best practices have been established outside of prefixes and/or examples of modules that we trust and what they are doing for large sets of variables.

Thanks!

It is possible to use a Drupal variable to contain an array; that is what Drupal core modules do too (see book_type_is_allowed()).

It is possible to use a single Drupal variable to contain different settings used by a module into an array. With the form #tree attribute is still possible to use system_settings_form() to save the array into a Drupal variable without writing any additional code. Serializing the de-serializing the code is automatically done by the Drupal core functions that handle Drupal variables (see  the code of variable_set()).

The question is then: when should a single Drupal variable be used to contain different settings? I would use a single variable for settings that are used by a function, or a group of functions; if the array contains values used by (for example) 10 different functions, but those functions access a single value (or a couple of values) from that array, then I would not use a single persistent variable for the settings.


How can I redirect users upon password reset? The solution shown in How can I redirect users upon login sometimes but not break the "Forgot password?" function? work for Drupal 7.

In Drupal 6, with the User:user has logged in event and the following PHP conditions, nothing happens.

if (arg(0) == 'user' && arg(1) == 'reset') {
  return false;
} else {
  return true;
}

How can I redirect users upon password reset in Drupal 6?

PS. The only variable for this event is $account for the logged-in user.

This is the exported rule I am using.

array (
  'rules' =>
  array (
    'rules_passwordreset' =>
    array (
      '#type' => 'rule',
      '#set' => 'event_user_login',
      '#label' => 'passwordreset',
      '#active' => 1,
      '#weight' => '0',
      '#categories' =>
      array (
      ),
      '#status' => 'custom',
      '#conditions' =>
      array (
        0 =>
        array (
          '#weight' => 0,
          '#type' => 'condition',
          '#settings' =>
          array (
            'code' => 'if (arg(0) == \'user\' && arg(1) == \'reset\') {
  return false;
} else {
  return true;
}',
            'vars' =>
            array (
            ),
          ),
          '#name' => 'rules_condition_custom_php',
          '#info' =>
          array (
            'label' => 'Execute custom PHP code',
            'module' => 'PHP',
            'eval input' =>
            array (
              0 => 'code',
            ),
          ),
        ),
      ),
      '#actions' =>
      array (
        0 =>
        array (
          '#weight' => 0,
          '#info' =>
          array (
            'label' => 'Page redirect',
            'module' => 'System',
            'eval input' =>
            array (
              0 => 'path',
              1 => 'query',
              2 => 'fragment',
            ),
          ),
          '#name' => 'rules_action_drupal_goto',
          '#settings' =>
          array (
            'path' => 'http://www.sample.com',
            'query' => '',
            'fragment' => '',
            'force' => 0,
            'immediate' => 0,
          ),
          '#type' => 'action',
        ),
      ),
      '#version' => 6003,
    ),
  ),
)

You can define submit function in your password form_alter and then $form_state['redirect'] = 'user'; or 'user/register'


How to echo block title render in specific  D7 After creating a dynamic block I need to print block title in specific div or customize it to add css class .
Please check image for more details

To add classes to block you can use below module:

https://www.drupal.org/project/block_class

To add class to block title there is similar question before:

Adding classes to block title

Thanks!


How to navigate in a view result from node full view I have a view which displays a list of nodes. When I click a node link from the view to see node's full view, I want in this node full view to add "back to list", "previous" and "next" links to let user navigate in view results.

I think to add view name and exposed filters selected values as parameters to node links in  the view, so I can compute navigation links in node full view. First question : isn't it an easier, cleaner, or more drupal compliant way to achieve this ?

If not : is there a better way to modify the links that in node teaser tlp.php ? I guess I could use hook_node_view_alter (I'm D7), but wouldn't it cause potential performance issue (I mean it need to test if I'm in my particular view for every node everywhere in the site, though it's a very specific feature)

Thanks for your help,

Philip

Check out Views Navigation module. This seems to be a good fit for your requirement.

  This module adds next and previous links on content pages when
  accessed from a view. It is intended for dynamic and/or paged view
  results, where the result set changes according to exposed filters,
  current user access rights,...

Also here is the link to the comparison other node based navigation modules.