Ajax rebuild form is calling all the code from my form function I have a form which when I click on on radio rebuild an element of the same form. Somehow when the ajax is called it's recalling everything from my form function.
How can I force him to reload only a part of the code, in that case the $form['container']['network'] and not the whole $form.

There must be some strange behavior during the callback, could it be reloading the whole form and get the part it wants then replace the old by the new?

$form['container']['ZoneId']['#ajax'] = array(
    'callback' => 'change_countries',
    'wrapper' => 'networks-list',
    'method' => 'replace',
    'effect' => 'fade',
);

$form['container']['network'] = array(
    '#type' => 'fieldset',
    '#prefix' => t('
'),
    '#suffix' => '
',
);

function change_countries($form, $form_state) {
    $form_state['rebuild'] = TRUE;
    return $form['container']['network'];
}

You shouldn't need:

$form_state['rebuild'] = TRUE;

Otherwise your callback looks correct.


True/False exposed Views checkbox for Computed Field Imagine a user has ten fields of type "List(text)" which each have for their widget "Check boxes/radio buttons". Each one is displayed to the user as a single value checkbox which asks the user to state whether they agree with something or not.

A distinct Computed Field of data type TinyInt uses custom PHP to examine the values of these List(text) fields checkboxes. If all are checked the Computed Field is set to have the value of 1. If any or all are unchecked the Computed Field is set to have the value of 0.

(Ideally I would like the Computed Field to be of Boolean type - so simple TRUE/FALSE - but this does not seem possible out of the box. Anyway, the real question is the following.)

In a View with exposed fields, how can you use the Computed Field as an exposed field that offers the user a single checkbox: "Find all users where the Computed Field value is 1: [•]".

If this isn't directly possible, I'm happy to have a workaround that involves creating a distinct (hidden) field in the user profile and then uses this for the Views exposed filter search. But I can't think of a way to do this right now... Thanks.

Change exposed computed field's filter type to "Grouped filters",
Widget type to "Radios",
Check "Allow multiple selections" checkbox,
Expose one option equal to 1 with your choice of label

See screenshot:

The view export:

<?php

$view = new view();
$view->name = 'computed_field_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Computed Field Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Computed Field Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['autosubmit'] = TRUE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: List 1 */
$handler->display->display_options['fields']['field_list_1']['id'] = 'field_list_1';
$handler->display->display_options['fields']['field_list_1']['table'] = 'field_data_field_list_1';
$handler->display->display_options['fields']['field_list_1']['field'] = 'field_list_1';
/* Field: Content: List 2 */
$handler->display->display_options['fields']['field_list_2']['id'] = 'field_list_2';
$handler->display->display_options['fields']['field_list_2']['table'] = 'field_data_field_list_2';
$handler->display->display_options['fields']['field_list_2']['field'] = 'field_list_2';
/* Field: Content: Computed */
$handler->display->display_options['fields']['field_computed']['id'] = 'field_computed';
$handler->display->display_options['fields']['field_computed']['table'] = 'field_data_field_computed';
$handler->display->display_options['fields']['field_computed']['field'] = 'field_computed';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Computed (field_computed) */
$handler->display->display_options['filters']['field_computed_value']['id'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['table'] = 'field_data_field_computed';
$handler->display->display_options['filters']['field_computed_value']['field'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['expose']['operator_id'] = 'field_computed_value_op';
$handler->display->display_options['filters']['field_computed_value']['expose']['label'] = 'Computed (field_computed)';
$handler->display->display_options['filters']['field_computed_value']['expose']['operator'] = 'field_computed_value_op';
$handler->display->display_options['filters']['field_computed_value']['expose']['identifier'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['expose']['multiple'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['is_grouped'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['identifier'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['group_info']['optional'] = FALSE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['widget'] = 'radios';
$handler->display->display_options['filters']['field_computed_value']['group_info']['multiple'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['group_items'] = array(
  1 => array(
    'title' => 'Find all users where the Computed Field value is 1',
    'operator' => '=',
    'value' => array(
      'value' => '1',
      'min' => '',
      'max' => '',
    ),
  ),
  2 => array(
    'title' => '',
    'operator' => '=',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
  ),
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'computed-field-test';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Computed Field Test';
$handler->display->display_options['menu']['name'] = 'devel';


How to create a content type that incorporates a batch upload and body field, with a gallery output I'm working on a client site that needs to include event recaps with a gallery of photos for each event under the text recap and event results. They're not very tech savvy so the standard method of creating a view through individually uploading images is going to be too complicated for them, So what I want for them to be able to do

Log in > Click add content > Click event recap or similar > Add a title and a date > Upload a thumbnail image > Put in their event results, who won what etc, probably just in a wysiwyg field > Batch upload images > Click save

And then for the front end, have a teaser sorted by date under an event recaps parent menu link, and on click the 'page' itself with the text recap, the thumbnail and the images in gallery format.

Is there some way I can combine taxonomy, views, and a batch upload module to make this come together for a less tech friendly user or a module that already does something similar?

You could make an image field accept multiple values and set its display to be gallery using one of that two modules galleryformatter, field_slideshow

And build a view list nodes ordered by the date field selecting one image image from the image field as a thumbnail (using relationships) by setting the delta to be just 1

take a look at how-control-display-multi-value-fields-drupal


Change field type from "text field" to "integer" I have a field that is numerical in nature and it was setup as text field. The problem is that sorting by ascending, the number 111 comes before 20.

One option could be to create another field, of integer format.

Then using PHPMyAdmin (or similar) copy the contents of the  field_data_field_FIELDNAME_TEXT_FIELD into your newly created field_data_field_FIELDNAME_INTEGER_FIELD.

If that works you can then delete the original text field.


Show Taxonomy Name not TID in Views Query String I'm using Views exposed filters (dropdown) based on Term Reference (taxonomy Fields.)

It works but the query string it generates uses the Term ID (TID) instead of using the more readable and clean term name.

How do I change the query string to use the term name instead of TID? For example:

Current: http://test.com/test?gender=1

Desired: http://test.com/test?gender=female

You can use taxonomy term names with this filter by adjusting Specify validation criteria settings. here's a screenshot:

Make sure Specify validation criteria is checked and you should be presented with more options. Under Validator choose Taxonomy term. You can optionally select with vocabularies to allow. Under Filter value type choose Term name converted to Term ID and check the Transform dashes in URL to spaces in term name filter values checkbox.


Using hook_query_alter I am using hook_query_alter to make changes in get taxonomy terms query.

    function MYMODULE_query_alter(QueryAlterableInterface $query) {
    global $user;
    if($user->uid > 1) {
        if ($query->hasTag('term_access') && strstr(current_path(), 'admin/structure/taxonomy')) {
            $permission = $query->leftJoin('term_permissions_user', 'tpu', "t.tid = tpu.tid");
            $ored = db_or();
            $ored->condition('uid', NULL, 'IS');
            $ored->condition('uid', $user->uid, '=');
            $anded = db_and();
            $anded->condition($ored);
            $query->condition($anded);
        }
    }
}

I want to have above query clause on the page which lists taxonomy terms only but this hook is adding the clause on all pages. I mean this hook is called on any page load of my drupal site.

Other issue is that the alias for table taxonomy_term_data is base on same pages and t on other pages and if i join using alias t it gives me error on most of the pages and vice versa.

I am checking the table alias to ensure the use of table alias used in my query and have changed the code as

function MYMODULE_query_alter(QueryAlterableInterface $query) {
    global $user;
    if($user->uid > 1) {
        if ($query->hasTag('term_access') && strstr(current_path(), 'admin/structure/taxonomy')) {
            $tables = $query->getTables();
            if(isset($tables['t']) && isset($tables['t']['alias']) && $tables['t']['alias'] == 't' && $tables['t']['table'] == 'taxonomy_term_data') {
                $permission = $query->leftJoin('term_permissions_user', 'tpu', "t.tid = tpu.tid");
                $ored = db_or();
                $ored->condition('uid', NULL, 'IS');
                $ored->condition('uid', $user->uid, '=');
                $anded = db_and();
                $anded->condition($ored);
                $query->condition($anded);
            }
        }
    }
}

But I am not sure if I have used a correct check, as of now my aim of adding query clause is fulfilled. Just to ensure this will work for long and will not break in any case.
Please help me to have this hook call on the page where I need this and use the exact table alias.

Thanks in advance for your help.

hook_query_alter() is executed for every dynamic query run by Drupal. If you want to execute the hook for queries having a specific tag, you should implement hook_query_TAG_alter().

The code for getting the alias for the main table is similar to the following one.

function mymodule_get_main_table_alias($tables) {
  $alias = '';

  foreach ($tables as $id => $info) {
    // If 'join type' is not set, then it's the main table.a
    if (empty($info['join type'])) {
      $alias = $id;
    }
  }

  return $alias;
}

I would write then the hook code as follows.

function mymodule_query_term_access_alter(QueryAlterableInterface $query) {
  global $user;
  if ($user->uid > 1) {
    if (strstr(current_path(), 'admin/structure/taxonomy')) {
      if ($alias = mymodule_get_main_table_alias($query->getTables())) {
        $alias = $query->leftJoin('term_permissions_user', 'tpu', "$alias.tid = %alias.tid");
        $query->condition(db_or()
          ->isNullcondition("$alias.uid");
          ->condition("$alias.uid", $user->uid, '=')
        );
      }
    }
  }
}

Notice that:

In $query->leftJoin(), %alias is replaced with the alias the query is using for the table  being joined. As you are altering an existing query, you cannot know if the alias you chose is already used.
The result of $query->leftJoin() is the alias being used for the joined table. It is better not to hard core that alias, for the reason said in the previous point.
To check if a field is NULL, you should not use QueryConditionInterface::condition(); as the documentation says, you should use QueryConditionInterface::isNull().
There is not need to create a QueryCondition object with db_and(); the conditions used to a query with $query->condition() are ANDed with each other.


Simple hit counter (as block)? I need to implement kind of a hit counter for the entire page (so how often the site was visited) in D7.

For D6 we got the Counter module, but is there any simple way to do it? Perhaps with a custom block and some PHP code?

You could use the core Statistics module as described here.

You could use Visitors module.

I use Google Analytics but this might be too heavy if you need a basic solution.


How to show the tabs according to the logged in user role? (Omega subtheme) I´m using an Omega subtheme in a Drupal 7 installation.
I´ve set at the theme configuration, that Drupal should show the tabs ($tabs).

What I want is to show the tabs only to a specific role.
I try this snippet out, wich didn´t worked. My guess is that it didn´t worked because I´ve told Drupal through the omega subtheme, to show the tabs. And the theme show them to everybody.

If I uncheck "show tabs" variable, they won´t show up, no matter what I do at my template file.

If I uncheck the tabs but add them inside my page template file, whey won´t show up either.

I want to be able to show the tabs or not according to the logged in user role.
Here´s my snippet that doesn´t worked (at my page.tpl.php file):

<?php
global $user;
if (!in_array('admin', array_values($user->roles))) {
print render($tabs);
  }
  else {}
?>

What should I do? Thanks for your help!!

If you are using the Omega sub theme then there would be a template file for each of the regions defined by the Theme.

The content comes in the template called region--content.tpl.php

You should see the tab printed there. you can put your logic there.


Why don't I get a value from drupal_static()? This post is basically a duplicate question of one I asked a little while back: Using Static Variables in a Custom Module. Unfortunately I can't get my own solution to work.

I'm trying to use a static variable in a custom module.

function tellafriend_userfullname_function() {
  global $user;
  $var = &drupal_static(__FUNCTION__);

  if (!isset($var)) {
    // generate contents of static variable
    $var = user_load($user->uid);
  }

  return $var;
}

The static variable will be used in the form submission handler and in hook_mail().

function tellafriend_form_submit($form, &$form_state) {
  $var = &drupal_static('tellafriend_userfullname_function');
  $params = array();

  if ($form_state['values']['cv_included'] == '1') {
    $params['1'] =  array('uri' => $var->field_cv_upload['und']['0']['uri'], 'filename' => $var->field_cv_upload['und']['0']['filename'],);
  };

  // Other email set-up goes here.

  $message = drupal_mail('tellafriend', 'notify', $email, language_default(), $params);
}

function tellafriend_mail($key, &$message, $params) {
   $message['headers']['MIME-Version'] = '1.0';
   $message['headers']['Content-Type'] = 'multipart/mixed;';
   $message['body'][] = $var->field_full_name['und']['0']['safe_value'];
}

What have I done wrong?

The default value returned by drupal_static() is NULL; this means that, when you call the function passing for $name a value that has not been used from another function, the value associated with that name is NULL, or the second argument passed to drupal_static().

In your case, you need to call tellafriend_userfullname_function() twice: once to initialize the static value, and once to get the static value.

function tellafriend_form_submit($form, &$form_state) {
  $var = tellafriend_userfullname_function();
  $params = array();

  if ($form_state['values']['cv_included'] == '1') {
     $params['1'] = array('uri' => $var->field_cv_upload['und']['0']['uri'], 'filename' => $var->field_cv_upload['und']['0']['filename'],);
  };

  // Other email set-up goes here.

  $message = drupal_mail('tellafriend', 'notify', $email, language_default(), $params);
}

function tellafriend_mail($key, &$message, $params) {
  $var = tellafriend_userfullname_function();

  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'multipart/mixed;';
  $message['body'][] = $var->field_full_name['und']['0']['safe_value'];
}

In this case, I would not use drupal_static(), for two reasons.

The value you set and get from drupal_static() is a value you can get from a global variable
Even if that would not be the case, you could simply use a static variable inside tellafriend_userfullname_function(), since drupal_static() is used for a static value that needs to be reset externally from the function that defines it

If you look at the code of drupal_bootstrap(), you will notice the following comments.

  // Not drupal_static(), because the only legitimate API to control this is to
  // call drupal_bootstrap() with a new phase parameter.
  static $final_phase;
  // Not drupal_static(), because it's impossible to roll back to an earlier
  // bootstrap state.
  static $stored_phase = -1;

drupal_static() is not a replacement for every static variable that could be used from a function; it should be used when the static variable is used to save a state another function could need to reset. The documentation for drupal_static() says:

  A guideline is that if a function's static variable does not depend on any information outside of the function that might change during a single page request, then it's ok to use the "static" keyword instead of the drupal_static() function.

As example of when drupal_static() is used, see menu_reset_static_cache(), which contains the following code.

  drupal_static_reset('_menu_build_tree');
  drupal_static_reset('menu_tree');
  drupal_static_reset('menu_tree_all_data');
  drupal_static_reset('menu_tree_page_data');
  drupal_static_reset('menu_load_all');
  drupal_static_reset('menu_link_get_preferred');

If menu_tree() didn't use drupal_static(), resetting the static variable it uses would not be possible, if not changing the function to use the following code.

function menu_tree($menu_name = NULL, $reset = FALSE) {
  static $menu_output = array();

  if ($reset) {
    $menu_output = array();
  }

  if (isset($menu_name)) {
    if (!isset($menu_output[$menu_name])) {
      $tree = menu_tree_page_data($menu_name);
      $menu_output[$menu_name] = menu_tree_output($tree);
    }
  }

  return $menu_output[$menu_name];
}

This would have been possible, but it would have changed the interface between the function and the functions using it. Since this is a common pattern among different Drupal functions, defining drupal_static() and using it in those functions needing it has been a Smart Thing™.


What is boost used for? When using Search API, editing an index and changing fields that get indexed, you can set the boost for some of the fields. What is this used for?

Boost column allows you to "boost" search results based on certain criteria. You can boost an entity which will make it have higher relevance. The way results are displayed will be by ranking and setting Boost value will add additional ranking to the field.

Currently you can only Boost Full Text fields.


How to use Rules to restrict the edit and delete options if a field has value "approved"? In my website I have 3 roles: user, tester and admin. When a user submits the content, tester will check and approve it.

As long as the content is not "approved", users can edit and delete their own content. But after the content is "Approved" (indicated via a field with value "approved"), users are not not allowed anymore to edit or delete their content.

How to do this with the Rules module based on roles?

Under permissions give the role ability to update only their own content. Then set a rule when node is published, author of role is set to another site user? That would be a quick implementation.


D8 - show view in comments depending on user role how i have to set up a view with Drupal 8 to show a field in the comments when the user_role is NOT "admin".

im not sure what kind of relationship and contextfilter i need to to this?

background: i want to show a label under the user_image of the comments
Thanks for help!

There is many ways to do it, but the simplest way is to check if user is admin or has exact role..

global $user;
   if ( !in_array('administrator', $user->roles) ) {
     ... do something ...
   }

OR

if( $user->uid !== 1 ){
  ... do something ...
}

OR

path_is_admin(current_path())


How to send the views record in an email to admin at regular time interval of 8 hours? I have created a rule to sent the view results, by using this:

<?php
$view = views_get_view('VIEWNAME');
print $view->preview('default');
?>

But I want this Rules Action to occur every 8 hours.

My question: What should be the "React on event" for this rule?

Edit: Based on the suggested answer, I'm now also using the Rules once per day module. Here is my rule (in rules export format):

{ "rules_send_emails_to_fuel_company_approved_client_list" : {
    "LABEL" : "Send emails to fuel company approved client list",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "mimemail", "rules_onceperday" ],
    "ON" : { "once_per_day" : [] },
    "DO" : [
      { "mimemail" : {
          "key" : "somebody@example.com",
          "to" : "ok",
          "subject" : "ok",
          "body" : "\u003C?php\r\n$view = views_get_view(\u0027calling_agent_summary\u0027);\r\nprint $view-\u003Epreview(\u0027default\u0027);\r\n?\u003E",
          "language" : [ "" ]
        }
      }
    ]
  }
}

But I'm still not receiving any emails. So I wonder what might be the cause of this.

Option 1: Using Rules and Rules Scheduler

Use the Rules module and Rules scheduler (submodule of Rules). What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 8 hours (instead of just 1 hour).

And as explained also in that tutorial: "Initially execute the component manually" (from then on every other 8 hours the rule will be executed again).

Option 2: Using modules Rules and Rules Once per Day

There is a fairly new module related to rules, i.e. the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

The way to understand/read this is like so:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

So by creating 3 similar rules, you could have 1 of them run around (say) 6 am, another one around 2 pm and the ast one at 10 pm. Adapt the 6am to any other timestamp you'd want, and do the same with the one from 2 pm and 10 pm


How do I customize the comment reply link? I'm trying to customize the comment reply link to direct the user to the comment submission form on the same page. I've tried:

<?php
$content['links']['#links']['comment-reply']['href'] = '#edit-comment-body-und-0-value';
?>

in my comment.tpl.php, but no luck. Also I need to add a JavaScript onclick to make the comment body in focus and add the user name of the user being replied to.

What should I do?

Have a look at the code of the AJAX comments module. It does simmilar things. There's a good chance that you can learn from theire code.


If multiple routes match a path pattern, how can I tell which one would be used? If multiple routes are returned by something like the following:
$route_provider = \Drupal::service('router.route_provider');
$found_routes = $route_provider->getRoutesByPattern('collection/%collection/items');

How can I find out which of those routes would be used if a path matched that pattern?
According to the docs:

getRoutesByPattern() returns a route collection of matching routes. The collection may be empty and will be sorted from highest to lowest fit (match of path parts) and then in ascending order by route name for routes with the same fit.

In my case, two routes with the same fitness are returned in alphabetical order:

Would the first or second one be considered more fit?

Your question is not clear enough.
Again, Your quote had full answer, the result is sorted by the fitness from highest to lowest fit. In case, they were equal, it would be sorted by alphabet of route name.
Return to your question, people usually use this function when they have a full or nearly full route name to check. or they have to add another condition that out of scope of this function.
You can not ask how Drupal determine which one wins when they are equal.


New module service is dependency on old module service - The service has a dependency on a non-existent service I have a new module moduleB. It defines a service that is used in the dependency injection of moduleA.
moduleA is already enabled, its changes are just to the services definition. The info.yml has moduleB as a dependency.
Both moduleA and moduleB are in the core.extension config to be enabled.
moduleB cannot be enabled using config (cim or csim) because the missing dependency from moduleA throws an exception.
How can I get config to enable the missing module before checking the service dependency? Or, how can I restructure to allow the existing module to use the new module service to allow enabling the module through drush ?
Thanks!

You can add moduleA to core.extension.yml on a new line (with the other modules) as module_a: 0.


How do I cache a custom module that has points? I am making a site with users that have points. I have a custom module that calculates points for each user, but the page is slow when is calculating the points in real time, so what I want to do is making a cache the points so they don't need to be calculated anytime someone open the page. The page will be cached; if users want the status for their points, they can update them pressing the "Update" button. So I will write a function for that button to clear the cache.

Yes, you can use the Drupal cache API to set and get the data from cache.

Assuming D7, The following resources have some good information on that:

https://www.lullabot.com/articles/a-beginners-guide-to-caching-data-in-drupal-7
https://www.drupal.org/docs/7/managing-site-performance-and-scalability/caching-to-improve-performance/caching-overview

For example:

function MYMODULE_function() {
  global $user;
  $user_point_data = &drupal_static(__FUNCTION__ . $user->uid);
  if (!isset($user_point_data)) {
    // User per user cache id for points.
    $cid = 'user_point_data:' . $user->uid;
    if ($cache = cache_get($cid)) {
      $user_point_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $user_point_data
      // with the correct stuff..
      cache_set($cid, $user_point_data, 'cache');
    }
  }
  return $user_point_data;
}

You can then clear the cached data, based on specific user id or all items, with:

cache_clear_all

// Clear all user point data from cache
cache_clear_all('user_point_data', 'cache', TRUE);
// Clear specific user point data from cache
$cid = 'user_point_data:' . $GLOBALS['user']->uid;
cache_clear_all($cid, 'cache');


Lightbox/colorbox slideshow and trigger thumbnails I a have problem getting a slideshow and colorbox to play together.

How would you go if you wanted to:

have a set of images in a node (let's say it's a multi-value image field)
display just a single thumbnail as a colorbox trigger
open up a colorbox with a slideshow of all images in that field.

The thing I want to emphasize is the distinction between having a single thumbnail on a node display level, and the slideshow on a colorbox level. By saying 'colorbox' I mean not necessarily that particular plugin/module. I'm open to any working solution, however I must say I gave up Lightbox2 after I found it poorly configurable.

I found my way of doing this. It's a litle bit tricky, but I hope it helps.

1) Get a View where you grab all node's fields, one of them is the "image" (multi-value).

2) To create a Custom Formatter with the Field API, put this code in a custom module (e.g. mymodule):

/**
* Implements hook_field_formatter_info().
*/
function mymodule_field_formatter_info() {
  return array(
    'mymodule_formatter' => array( //Machine name of the formatter
      'label' => t('Links to images'),
      'field types' => array('image'), //This will only be available to text fields
    ),
  );
}

/**
* Implements hook_field_formatter_view().
*/
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array(); // Initialize the var
  $settings = $display['settings']; // get the settings

  //get first image
  $firstimg = $items[0];
  $uri = file_create_url(file_load($firstimg['fid'])->uri);
  $html = '<img src="'. $uri. '" id="galeria1-button" class="btnSlideshow" href="#" />'. PHP_EOL;

  //get all images and put them as links but without being seen
  $options = array(
    'html' => TRUE, // This tells Drupal that we're sending HTML, not plain text, otherwise it would encode it
    'attributes' => array(
      'class' => 'galeria1',
    ),
  );
  foreach ($items as $delta => $item) {
    $uri = file_create_url(file_load($item['fid'])->uri);
    $html.= l('&nbsp;', $uri, $options);
  }

  //js will make that when you click on first image its as if you were clicking on first gallery image
  drupal_add_js('jQuery(document).ready(function(){jQuery("#galeria1-button").click(function(){jQuery(".galeria1").filter(":first").click();}); jQuery(".galeria1").colorbox({rel:\'galeria1\'});});', 'inline');

  $elements[0] = array('#markup' => $html);

  return $elements;
}


Form API: Show/Hide/Select option based on a previous option Possible Duplicate:
  Easiest method for conditional fields in a form

Essentially I have 2 select fields on a form:

EDIT: I should mention, this is an entirely custom form built with Form API, I'm not modifying a core/contrib form.

Type

Global
Regional

City

Any
London
New York
Paris
LA

If Type:Global is selected, then the City field is hidden and City:Any is selected.

If Type:Regional is selected, then City is revealed, City:London selected and City:Any hidden.

Is there a Drupal or Form API compliant method to achieve this or is it simply a case of loading a JS file with drupal_add_js and writing entirely custom JS?

If it's simply custom JS/JQuery no need to write it out for me, I can handle that, but I would like to try and stick to the standard and best practices if there are any for my problem.

Thanks!

You can solve this problem using AHAH on your Form API. The module AHAH Helper may be very useful for you... take a look there...


How to let simplenews send email instantly without through cron? I'm using simplenews and MIME mail in my drupal 7 site to send newsletter.

When I click send newsletter, the sending of newsletter is in pending status and waiting for cron to run and send email.

Is there any method I can send newsletter email directly without waiting for cron?

Instead of using cron (either manually or waiting for it) you could use:

Drush

drush simplenews-spool-count

  Print the current simplenews mail spool count

drush simplenews-spool-send

  Send the default amount of mails, as defined by the simplenews_throttle variable.

drush simplenews-spool-send 100

  Send 100 mails.

drush simplenews-spool-send 0

  Send all mails.

Alternative cronjob usage

If you can't use drush you can trigger cron manually at /admin/reports/status/run-cron, but this will also run all other cronjobs. As an alternative you could install and use elysia cron or ultimate cron (currently the later looks like to be the more active version). Both modules will allow you to run specific cronjobs manually and separated from others.


Problem trying to create a boolean view filter Drupal 7.22
Views 7.x-3.7

Hi,
I have two similar content types and have added a boolean field to both (x for one and y for the other).
I want to create a view that displays any of the two types if x or y is true.

If I add the first filter criteria: Content: x (= Yes), I see a result in the preview pane.
If I remove the first filter criteria and add the second filter criteria: Content: y (= Yes), I see a result in the preview pane.

So both work on their own.
If I try to 'or' them I get neither?

I have tried this in various ways (one filter group or two separate groups).
I have also tried simplifying this by changing the fields to text but the or is still not working?

Please can anyone help or point me in the right direction?

Thanks!
a.

Add a boolean value to both content types, should be the same boolean you created. no need to create a different boolean field for each content type.

create a view:

filter for the "Operator -  Is one of" and chose your two content types.
filter for you boolean field wich was added to both content types "Operator - Is one of" and select "yes" or 1 depending on your field yes value.
add what ever fields needed.

I have created two content types "content one" and "content two" and added the boolean field "check me" to both.

here is my view:


Region with block shows up in admin preview, but not on site I'm new to drupal and a bit confused by this. Using the standard Bartik theme (Drupal install 7.8) I see a search bar on the sidebar. Checking the Structure > Block it shows that the search is included in the Bartik theme on the sidebar. The preview while an admin shows the search.

However, as soon as I log out the entire sidebar_first region does not show. Just the content area.

EDIT: When adding a login box to the sidebar it does appear, however, the searchbar, and navigation do not. There are NO RESTRICTIONS applied.

EDIT2: View the screenshots below to see my settings.

Normal User sees:

Admin User sees:

Current settings for navigation block:

You've to allow anonymous use to access the search form, to add this permission, you've to go People > Permission and search "Search" and check the box "Search content".


Combine views sort criteria in exposed form Drupal 7, views 3.6.

I have a view with 2 sort criteria: date and category. The sort is exposed in a form block.
Currently the user only has the choice to select 1 sort criteria, ie: sort by date or sort by category.

Is there a way to have the combination of these 2 criteria exposed, ie: sort by date asc, and by category desc ?

Thanks for your input,
Jerome

Use Better Exposed Filters module:

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.


How do I pass a specific argument from a rules event to a condition? I am setting up a default rule for my custom Drupal 7 module, as follows:

$rule->event('commerce_cart_product_add')
->condition(
  'mymodule_condition_1',
  array('something' => 'something_else'))
->action(
  'drupal_message',
  array(
    'message' => t('Example message'),
  ),
));

I have written a function, mymodule_condition_1, which returns TRUE or FALSE based on what product is being added to the cart. I need to be able to get the product from the rules event, and pass this to the condition. I have looked through all the documentation and example code but I can't seem to see a way to do this.

In the above example, 'something' and 'something_else' need to be specific values, but I can't see what I can refer to in order to find out what they should be.

In a case like this, you'd going to have to use what Rules calls a data selector. If you were building this Rule through the UI, you would click the "Switch to data selection" and enter some token that corresponds to the type of parameter required.  In this case, the commerce_cart_product_add event provides the arguments commerce_order, commerce_product, quantity, commerce_line_item, and commerce_line_item_unchanged.  (See all this in the event's definition in commerce_cart.rules.inc.)  So when trying to select the product passed to the event through the UI, you'd use commerce-product as the value for your condition's product parameter.

When building this Rule in code, you specify a data selector by appending :select after your condition's parameter's name.  So, if the name of the product parameter for your condition (as defined in hook_rules_condition_info()) is commerce_product, your "something" would be commerce_product:select.  The "something_value" would be the same token you'd enter through the UI, commerce-product (as that's the name of the product argument passed to the Rule).

And touching on one more aspect, the event info defines the variables that must be passed to Rules when an event is invoked.  Your condition can use any, none, or all of these - it doesn't really matter. A condition or action's definition simply states what kind of parameters it needs, and the Rule configuration is responsible for passing the parameters to the condition from the pool of available variables (or from variables you load as part of the configuration).


Is there any way to create a discount that only discounts one product in an order? We have a Drupal 7 site using Commerce and Discounts and we need to create a discount that will discount one product in the order by 100%.

Basically, we need to give a coupon discount for ONE free product but so far we only see a way to discount ALL products on the order or the entire order.

We've tried Commerce Discount EXTRA (module) and it gets close by using the "Per Quantity Product Discount" but it forces you to select one specific product that the discount would apply to instead of ANY product.

So, does anyone know of a way to achieve creating a discount to only discount ONE of ANY product in an order?

With the offer types defined in Commerce Discount / Commerce Discount Extra, there isn't much you can do. The closest ones to what you've described are the per-quantity % off discounts, but as you've discovered, you have to specify either a target product or product category. If you're using a taxonomy configuration that allows the per-quantity category discount (i.e. you have a term reference field on your product display nodes that you can target in the "Products in these offer categories" field), then you can configure this by just identifying every product category in a comma separated list. Otherwise this is going to require custom code.

Since your requirement is also to tie this to a coupon code, you're going to have to write that custom code as a custom offer type. It could be that you simply copy the per-quantiy product discount and change the matching logic to allow discounting any product on the order, but I gotta be honest ... that code is hairy. I wrote the current implementation, and I'm sure it would take even me a full day just to remember what's going on in there and try out some potential solutions.

That said, you could try to "hack" it using existing pieces. Basically ... you could create a new taxonomy vocabulary with a term that identifies products that are eligible for the free product offer. You can then add a term reference to that vocabulary on every product display and select the term for them. You're basically creating a global product category that all of your products are assigned to ... and you can then hide the term from the UI so customers never see it. This may actually be a preferable solution in the future anyways, as the merchant may end up wanting to restrict certain products from these coupons. Give it a go, let us know how it turned out!


Building a username search by writing custom module My module simply allows a user to type in a user ID # in a field and hit the submit button.  The page should return the username.

function usersearch_form_submit($form,&$form_state) {
  $query = "SELECT name FROM users WHERE uid = :uid";
  $result = db_query($query,array(':uid' => $form_state['values']['uid']));
  foreach($result as $user) {
    echo "The username is $user<br>";
  }
  $form_state['rebuild'] =  TRUE;
}

Nothing really happens after I hit the submit button.  I get sent back to the form as if nothing happened.

A form submission handler doesn't use echo to output its result. You need to use a render array to render the result, such as with the following code. I assume usersearch_form() is the form builder function.

function usersearch_form($form, &$form_state) {
  // Add the form elements.

  if (!empty($form_state['username'])) {
    $form['username'] = array(
      '#markup' => t('The username is %username', array('%username' => $form_state['username']))
    );
  }

  return $form;
}

function usersearch_form_submit($form, &$form_state) {
  $username = db_query('SELECT name FROM users WHERE uid = :uid', array(':uid' => $form_state['values']['uid']))->fetchField();

  $form_state['username'] = $username;
  $form_state['rebuild'] =  TRUE;
}


How to use remote file source module I would like to use the Remote File Source Module.

But I could not find any documentation related to it.

Has anyone succeeded using it?

How to provide ftp hyper link inside a blog, article, forum.

I would like to insert a node url inside CKEditor. The node must be a custom node which will fetch a file from an FTP url some think like a reverse proxy.

Go to your content type and click edit on your file field in question.

Click on File Sources.
☑ Remote File.


How to set MINIMUM number of required fields? I need to set the minimum number of required values for several file fields in Drupal 7. I can only find options to make the field required or set a maximum number of allowed values. Is there any way to set the MINIMUM number of required values?

You can use the Field validation module, and set up a validation rule using "number of selections".
The Field validation module has many validation rules you can set for any of your fields. It works by defining a set of validation rules at first, then you can assign that set to a field.

To answer your question, the validation rule you need to use is the "number of selections". You can define a minimum and a maximum number of values required. Just leave blank the "Maximum number of selections" parameter and set "Minimum number of selections" to your needs.


How to block Webform spam based on keyword strings? Short Version: I would like to block Webform submissions that contain strings e.g. mail.ru in the webform textarea field.

Recently I am seeing a lot of fake webform submissions. I am already using honeypot contrib module and I have added quite a number of IP addresses to the server firewall. However there is still some spam coming through. For now I don't want use Captcha. Luckily those spammers always using recurring pattern e.g. same domain name.

How I can automatically block submission that contain certain strings? Using the rules + webform_rules module and Regex doesn't allow me to choose the Webform email field as data selector. selected-webform:0 doesn't look valid. What's the right way to block webform spam?

{ "rules_blocking_fake_registration" : {
"LABEL" : "Blocking fake registration",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "webform_rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "contactform" : "contactform" } }
    }
  },
  { "text_matches" : {
      "text" : [ "selected-webform:0" ],
      "match" : "plusgmail.ru",
      "operation" : "regex"
    }
  }
],
"DO" : [
  { "block_ip" : [] },
  { "mail" : {
      "to" : "admin@address.com",
      "subject" : "[site:name]: Blocking user [data:e_mail-value]",
      "message" : "E-Mail Adresse: [data:e_mail-value]",
      "language" : [ "site:current-user:language" ]
    }
   }
  ]
 }
}

I really appreciate any comments and help.

Try Webform Validation module. It adds validation options for webforms. One of these extra options is "words blacklist", where you can specify the list of strings that should not appear in your field. The spammers will get validation error and will not be able to submit the form.


Adding "onclick" event to links in text areas I need some help getting and "onclick" event onto some links in a couple drupal pages.

I've got 2 pages, each with a text entry field set to "full HTML", within which I've added my a tags.
the links work great in this format, however when I try to add my onclick event (which contains jquery info for analytics tracking), the only thing I see when I inspect element is the text "onclick" and nothing after it. Not even the " =" ", which would suggest a script error.

When that didn't work I added a class to the A tags and tried to use jquery to append the onclick attribute with these jquery functions:
setAttribute
attr
click

While it sounds simple none of what I've tried has worked (I had used both setAttribute and click successfully on other links), so now I'm looking for a new method.
the module Menu attributes doesn't work since it doesn't deal with "onclick" and my links are not menu items, they are just links in text.

I'm using Drupal 6.19 and jquery update.

If anyone has advice or suggestions, please let me know,

Thanks
Steph

Sorry all, I discovered my question was invalid.
I was able to user onclick directly in the "full html" text area, and while the value of the attribute didn't show in the view source, it was working.

I'm not sure if D6 always handles onclick in full html text areas or not. I choose to believe there is something causing this in my theme.

Thanks for your attention!!
Steph


How to deactivate the automatic emails sent to administrator? Is there any existing module to edit automatic emails sent to admin by Drupal 7?
Something like Mail Editor to edit the mail templates but not only for those sent to users.

I need to deactivate the automatic email sent to administrator when an user have created an account. I have created a Rule to have details on this new account with tokens and now I do not need the automatic core email anymore.

Thanks for any help. I can not find any solution to this, except this custom module and I would prefer a newbie solution.

Enable and Install the Mailcontrol module and then go to admin/config/people/accounts turn off the checkbox.

  This small module extends original Drupal 7 account settings page with
  the ability to globally turn ON/OFF all standard mails.

By default Drupal 7 provides no option to globally disable the following mails:

Welcome (new user created by administrator)
Welcome (awaiting approval)
Welcome (no approval required)
Password recovery


How to get the node title of a refernced node I'm using Drupal 7, and trying to work some magic from within a hook_node_presave() function.

I have a node reference field, and I'm trying to get the name of the referenced node rather than nid. When I trace out the field ($node->field_my_name) I get the following

Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [nid] => 23
                )

        )

)

I wondering if there is a way to get the title without doing a full load of the referenced node. Is there anyway I can do this with a token? Would this no be an issue if I were using entity reference rather than references?

You could use entity_label() function.

The function takes the entire entity as an argument, and it should already be loaded.
I would just load the node. As the other author suggested, it is very likely to be already cached in a hook_node_presave() call.


Sign up using google account I am trying to add a 'Login using Google' type login page. But I cant find any module that does it out of the box. Could anyone help me proceeding in the right direction as to creating a module that would allow user to sign up with their google account?

I have found a module called openid selector that does exactly what I am looking for.


Field Slideshow module in blocks Im trying to create a slide show banner for my home page in Drupal 7. I do not have enough skill to make my own or to edit the PHP, template files or JS.

So far the easiest module I have found to work with is "field slideshow" but I can only work out how to use this in content.

Does anyone know a way to enable this for use in blocks or a way to make a custom content type move to a different place than that of the main content block?

Thanks for your help!

All modules will need to be have some tradeoff between a simple solution, and a powerful tool. Field slideshow is a relatively simple solution, while Views slideshow is a vastly more powerful tool.
Utilizing the power of Views, you have far better control of your slideshow, one example being, that you can easily create blocks.


Rewrite results "read more" link death My rewrite result settings:

My general settings:

the "read more" link from the teaser doesn't redirect me to the article, When pressed, it redirects me to the main page (current one).

When leaving the "more link path" empty, it should redirect me to the blogpost (article).

Some values I've tried for "link more path":

[path]
[node/id]
[node:title]
[title]

Is this not working because I also got the "URL aliases" module installed? Which cleans my url like this:

www.mysite.com/blog/awesome-article-about-ducks

instead of this:

www.mysite.com/blog/node/41

There are 2 ways to do this.,

Step :1

  Add the nid to the views and exclude it from the display.
  Place this nid before all fields in the views. Only by placing it above the all fields, we can get this as a token in the replacement.
  Now use node/[nid] as the path to link.
  This will worl

Step : 2

  Add content:link as a field.
  Add set the nid in the replacement pattern.

Difference between the 2.

  Step:1 shows the read more only when the length is greater than the
  trim value. Else it will not show.

  Step:2 will show the read more in all the cases. Even the body is
  empty it will show read more, but this will not happen in step 1.


execute action on workflow transition I want to execute PHP script in my custom module, when transition occurs. Workflow is assigned to custom entity. I'm using Drupal's core modules Workflow and Content moderation. How can I do that programmatically?

You can use hook_ENTITY_TYPE_update to achieve this.

/**
 * Implements hook_ENTITY_TYPE_update().
*/

function mymodule_node_update(Drupal\Core\Entity\EntityInterface $entity) {

    //Get the current Moderation state;
    if (isset($entity->moderation_state) && isset($entity->moderation_state->getValue()[0]['target_id'])) {
        $currentState = $entity->hasField('moderation_state') ? $entity->moderation_state->getValue()[0]['target_id'] : null;
    }
    //Get the original Moderation state;
    if ( isset($entity->original->moderation_state ) && isset($entity->original->moderation_state->getValue()[0]['target_id']) ) {
        $originalState = $entity->original !== NULL ? $entity->original->moderation_state->getValue()[0]['target_id'] : null;
    }

    #Get the Transition;
    $workflowTransition = rtrim($originalState.'-->'.$currentState);

    switch ($workflowTransition) {
       case 'published-->needs_review':
       case 'draft-->needs_review':
       //Do something.
      break;
       case 'draft-->needs_review':
      //Do something else;
      break;
    }
 }


How did the ransomware get in? A site where the site owner put off having updates done has been compromised with ransomware. This situation brings up a lot of questions. A Google search has not produced any answers. The server is on a university system where they lock things down pretty tight.

Are there any stats on the ransomware infection rates for Drupal sites, esp. compared to other systems?
What is the most common part of a Drupal site to be the hole for a ransomware compromise, ie. specific module, Drupal core, login function,  Apache server function?

How did the ransomware get in?

The website most likely got hacked.

  What is the most likely reason for a Drupal site to be infected with
  ransomware?

1) Well, doing exactly what that site owner did, putting off security updates which will leave you vulnerable.

2) Leaving the front door open: Allowing scripts, javascript/jQuery or PHP to be executed by regular users.

3) Not using Secure Login

  For sites that are available via both HTTP and HTTPS, Secure Login
  module ensures that the user login and other forms are submitted
  securely via HTTPS, thus preventing passwords and other private user
  data from being transmitted in the clear. Secure Login module locks
  down not just the user/login page but also any page containing the
  user login block, and any other forms that you configure to be
  secured.

Hacked!

  This module does not and will not prevent your site from being 'hacked'.

  This module scans the currently installed Drupal, contributed modules
  and themes, re-downloads them and determines if they have been
  changed. Changes are marked clearly and if the diff module is
  installed then Hacked! will allow you to see the exact lines that have
  changed.

Your Drupal site got hacked. Now what?


How to redirect url in index.php?title=plip to a specific url like /my-page? I develop a new drupal website to replace another website.
So, in order to not loose my Google SEO from the old website, I create URL rewriting rules.

Everything is ok except for old urls beginning with index.php, like index.php?title=plip

I would like to redirect like this :

RedirectPermanent /index?title=plip http://new.drupal/my-page

It is normal because of this, in Drupal .htaccess file :

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{HTTP_USER_AGENT} !MSIE
RewriteRule ^ index.php [L]

But how can I do to get my redirection from urls like index.php?title=plip ?

I tried with the flag S to create an If-Else-like rule but it doesn't work.

Is there any chance to make it possible ?

You should be able to make this work using the Rules module, as detailed below.
Looking at your path (= /index.php?title=plip) I would try to make the value (= plip) of the URL argument (= title) available as a new variable to the Rules module. To do so, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Conditional that looks at URL Im attempting to wrap my secondary links in an if statment that looks at the URL and only displayes them if URL is work/*.

The secondary links are only related to work but show on every page so i am trying to emove on any path that is not work/*. The secondary links are within my page.tpl

Ive been tryin with this but no joy.

 <?php  if ($the_url = explode('/', urldecode(request_url('work')))):?>

<?php if (!empty($secondary_links)){ print theme('links', $secondary_links, array('id' => 'secondary', 'class' => 'links sub-menu')); } ?>

<?php endif; ?>

Any help would be much appretiated.

Thank you

Try this:

$request_array = explode('/', request_uri());
if (in_array('work', array_values($request_array))) {
  //execute your custom code
}


Contact form - Custom fields are not sending content I've done a custom contact form with 2 more fields, but I can't get values of those 2 custom fields.

I modified contact.module in core to see what are coming from form submit, found my custom fields but they are empty. I just don't know why they are empty.

Value of contact_form in contact.module:

$contact_form = {"contact_form":[{"target_id":"feedback"}],"uuid":[{"value":"5470b680-99db-4d5a-8c00-ae043dce67e1"}],"langcode":[{"value":"pt-br"}],"name":[{"value":"Name"}],"mail":[{"value":"some@mail.com"}],"subject":[{"value":"Any"}],"message":[{"value":"Any message"}],"copy":[{"value":0}],"recipient":[],"field_customa":[],"field_customb":[]}
;

Any clues to make this contact form work?

Drupal 8 will handle custom fields on contact forms 'out-the-box', they will be rendered in the message body by contact module. If custom fields don't appear in message body, someone messed up.

In this particular case, attribute 'name' of 'input' html tags were modified, and $_POST came with a wrong schema. $_POST['field'] instead of $_POST['field'][0]['value'].

Here shows the hint:
"message":[{"value":"Any message"}] - Correct (field[0]['value'])
"field_customa":[] - Wrong (field[])


'hook_field_widget_form_alter' but for markup I have content type which has term reference as a field.
I want add some html attributes to each option in select on form (when adding new node of that content type).

'hook_field_widget_form_alter' is right place for custom code but not for HTML markup. How I can change display of this select?

Attributes on the option tags aren't themeable unfortunately, many of the standard form elements in Drupal are this way. You can theme the wrappers to your hearts content, but the elements themselves are quite locked down.

If it is absolutely necessary to do this you may need to find a way of doing it outside the form API.

You could use the #post_render on the FAPI options for it to do some manual rewriting of the output markup using regex and whatnot. Not very efficient but probably quicker than writing something from scratch!

The function that handles this is in the includes/form.inc file form_select_options. I really wouldn't condone editing it, but it is handy for reference.


Menu block makes parent menu item active when maximum levels not cover the linked node In Drupal 7, a menu block can specify maximum levels.
If the maximum levels is not enough to cover all menu items linked node, when in the
not-covered menu items linked node, could menu be active at their parent menu item?

For example,  a menu has 3 levels, and specify maximum levels = 2, when at level 3 menu
item linked node, could open its parent menu item in level 2?

Have a menu like this:
M1
 M11
  M111
  M112 - link node PageM112
 M12
  M121
M2

If maximum levels = unlimites
At PageM112 node page, the menu will be like this.
M1
 M11
  M111
  M112 - linking to PageM112
 M12
M2

If maximum levels = 2, going to PageM112 node page, the menu will closed, like this.
M1
M2
M3

In this situation, could the menu be active at its parent menu item, M11, with the menu
expanded like this?
M1
 M11 - active
 M12
M2

If I understand correctly you need the Menu Position module. Using this module you can keep Parent Menu item active at any level of it's sub items.

  This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.


why importer cannot map to custom field type I've created a custom field type and added a field with this field type to my content. When I add set any data on Node Edit page, the data will store into the database successfully. But if I try to set the data via feeds importer, in mapping, this field is missing. I don't know if I missed any hook function in my module, or is there any setting I have to do in my module.

Here, I list all hook functions I am using:

hook_field_info
hook_field_widget_info
hook_field_widget_form
hook_element_info
hook_theme
hook_content_is_empty

Does anyone have any idea about why I cannot find my field in mapping list? If you need more information, please leave me a message. Thank you!!!

You may also need to specify the field mapping details in:

hook_feeds_processor_targets_alter

  Alter mapping targets for entities. Use this hook to add additional target options to the mapping form of Node processors.

Example implementations: http://www.drupalcontrib.org/api/drupal/contributions%21feeds%21feeds.api.php/function/implementations/hook_feeds_processor_targets_alter/7

More info: http://www.drupalcontrib.org/api/drupal/contributions%21feeds%21feeds.api.php/group/mappingapi/7


How do I remove the default node path when using a path alias? When I add path aliases, how do I remove the system path (/node/[nid]) in Drupal 8, to avoid Google to index the page twice?

Simple answer: You don't have to. We pretty often are asked about disabling the generic URLs to avoid penalties from search engines.

This however is not necessary. Once using URL aliases, the meta tags for both versions of the node rightfully declare the node/[nid] paths as short URL, and the URL alias as canonical URL. So search engines will index the page using the URL aliases.

Penalties would arise only, if you provide the same content at various places and trying to disguise their connection.

If you still are afraid, you can e.g. make use of the rabbit_hole module.


How to get path of image from file id I have this output from my twig template dump:

/var/www/html/vendor/twig/twig/lib/Twig/Extension/Debug.php:56:
array (size=7)
  'id' => string 'views_block:about-block_1' (length=25)
  'label' => string '' (length=0)
  'provider' => string 'views' (length=5)
  'label_display' => string '0' (length=1)
  'views_label' => string '' (length=0)
  'items_per_page' => string '3' (length=1)
  'background' =>
    array (size=1)
      0 => string '136' (length=3)

So my file id (fid) is 136. I'd like to know a way to get this file's url without having to use a preprocess function.

Can this be done? Would I have to do a custom twig function to achieve this? If so where would I add the code to extend twig?

ex:

$twig = new Twig_Environment($loader);
$function = new Twig_SimpleFunction('function_name', function () {
    // ...
});
$twig->addFunction($function);

So I decided to create a module to extend twig and get the file url from its fid.

get_url_from_fid git project

Source of src/GetUrlFromFid.php

<?php
namespace Drupal\get_url_from_fid;

class GetUrlFromFid extends \Twig_Extension{

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName(){
    return 'get_url_from_fid';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions(){
    return array(
      new \Twig_SimpleFunction('get_url_from_fid',
        array($this, 'get_url_from_fid'),
        array('is_safe' => array('html'))
      )
    );
  }

  public function get_url_from_fid($fid){
    $file = \Drupal\file\Entity\File::load($fid);
    if(!is_null($file)){
      $uri = $file->getFileUri();
      return file_create_url($uri);
    }else{
      return false;
    }
  }
}


How to create a view that links an image from a field collection item to the field collections host node I have a custom content type "FH Portfolio" item that contains (among other fields) a Field Collection of "Geoimages". Each Geoimage contains (among other fields) one or more "Portfolio image" fields.

I'm trying to construct a view (block) that displays 3 'featured' FH Portfolio items, showing the first Portfolio Image. On hover, the title of the FH Portfolio item should be displayed. When the image is clicked, it should link to the FH Portfolio item, not the Geoimage that has provided the image.

I can get the images displayed correctly, with an Image Hover Effect (using Image Hover Effects module, which relies on a link being wrapped around an image to work)) that displays the title of the relevant FH Portfolio item (by using the token [host:node:title] ), but I can't make the image/title link to the FH Portfolio item; is there any way to do this? (I have Image linked to content).

I've tried rewriting the image field as a link going to [host:node:url] but that doesn't work.  (I've also tried including Content:Path as a field in the view (excluded from display) and rewriting the image field to display a link to [path].  That works, but I lose the image hover effect displaying the title.).

Edit the image field and link image to 'content'

Another method:

    1. Add the nid field in view.
    2. Edit the image field, Go to the rewrite result and check "Output this field as a link". and put node/[nid] token in it.


How to implement click event on dynamically generating ? I have a drop down select box. Through jquery on run time that drop then hides and the new drop down made which made from <ul> and <li> tags.

Now through firebug I notice that when the drop down is closed then there is one <li> and when I expand the drop down then in the firebug more <li> displayed.

So I want to implement the click event on these <li>.
I tried this code.

 $(document).ready(function() {
  alert('a');
  $('.fb li').each(function() {
      alert('li');
    $(this).click(function(event) {
           alert('hed');
        var fbpage = $(this).attr("rel");
        if(fbpage != 0) {
            window.open(''+fbpage+'', '_blank');
        }

    });
    });
    });

the alert('a') and alert('li') works but then that click event is not working.

Any idea about this? and if you does not understand my question then ask me I will explain it more.

Since you are running D6, you should look into the live() jQuery handler ( http://api.jquery.com/live/ ) that can be used to attach these click handlers to your dynamic elements.

More information on this can be found by googling or otherwise searching for

jquery click event on dynamically generated elements

You might also want to look into the Drupal.behaviors method of including jQuery and javascript instead of the $(document).ready() approach you've used.


Webform menu access control I'm using Drupal 7 with Webform and Content Access contrib modules.

I wrote a little snippet that displays all items for a given menu, and greys out the ones that the user doesn't have access to, while the accessible ones are links.

I get the access control information with

menu_link_load(menu_load_links(menu_my_menu)[mlid])[access]

...if that helps at all. It returns 1 if access should be granted, and NULL if not.

The problem I'm encountering is that, while this code works swimmingly for normal nodes, webforms seem to return a 1 for access even when the logged-in user does not have permission to submit that form. So the link shows up, and then it takes the user to a page that says "You do not have permission to view this form."

What function do I call to find out whether a webform of a certain path (or title or whatever I can find out from menu_link_load) should be visible to the user?

I think the easiest way to resolve this is to use Content Access and specify the View permission for a Webform, rather than Webform's "can submit" permission.  In other words, by using the Content Access module's View Permission instead of the Webform "can submit" permission, you can utilize the code you're currently using.  To do this you'll have to set a separate View permission for each Webform.

The problem originates from Webform's permissions conflict with Drupal core: Drupal's standard View permission may be true, but the Webform "You can submit this form" permission can be false, which gives a different Access Denied message from above.

I attempted to dig up an alternate solution, creating some custom code to derive the access for Webform menu items, but it really was looking horrendous.  Webform does not have a function that returns "You can submit this webform" access, and trying to efficiently determine if a menu item is a webform was looking pretty foul.


Convert a Flags Link into a Checkbox Is there a way to convert Flags links into check boxes within a view? I tried the Flag Form module, but it did not work (at least not in a view). I've reviewed the Flags Add Checkboxes as Display Type feature request. The discussion points to using CSS, JavaScript, or hacking the flags template file. Are there any other methods?

I'm not adverse to using JavaScript to do this, but I know little about it.

A comment from the Flag Add Checkboxes ad Display Type feature request offered a good foundation for using JavaScript. I read up on JQuery and changed the code slightly to work with D6. All credit goes to ngmaloney.

Drupal.behaviors.alter_flag_links = function (context){
    //Returns a checkbox dom object
    var cb_factory = function(class_attr, checked) {
      var checkbox = document.createElement("input");
      checkbox.type = "checkbox";
      checkbox.checked = checked;
      jQuery(checkbox).attr('class', class_attr);
      return checkbox;
    }
    //Convert each link to a form checkbox.
    jQuery('span.your-flag-value').each(function() {
      var flag_link = jQuery(this).children('a');
      if(flag_link.length == 0) {
        return;
      }
      flag_link.html(''); //Hide text
      var flag_classes = flag_link.attr('class');
      var checked = false;
      var class_attr = 'compare-cb';
      if(flag_classes.match(/unflag-action/)) {
        checked = true;
      }
      //Only Add form element if it doesn't exist
      if(jQuery(this).children('input').length == 0) {
        var elem = cb_factory(class_attr, checked);
        jQuery(this).prepend(elem);
      }
    });
    //Attach an event listener to each of the new checkboxes
    jQuery('input.compare-cb').each(function() {
      jQuery(this).click(function() {
        jQuery(this).parent().children('a').click();
      });
    });
};


Can we return 2 table themed arrays in function I have 2 arrays, but the 2 have different key values you can see in foreach for one it is src, where as for another it is source. I would like to show the both both tables on one hook. But this seems not working.

The issue is you're passing elements that a render array would use, such as the "#rows", "#sticky", etc, but Form API will ignore them, because anything prefixed with a "#" will be treated as a property of the form element.

Clive gives here (https://drupal.stackexchange.com/a/27269/28556) a very concise explanation and solution for that, which consists in creating your own theme function to render a particular element.

Additionally, I think you could, as well, use the existing theme('table', ...) function to render the table from that same function, but returning the results as direct markup instead.


Drush syntax error, unexpected T_FUNCTION in webform.module When I try to run drush right now I get this error:

-bash-4.1$ drush pm-list
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: syntax error, unexpected T_FUNCTION in
<site location>/sites/all/modules/webform/webform.module,
line 4654

Here is the function where the error occurs:

/**
 * Get a list of all available component definitions.
 */
function webform_components($include_disabled = FALSE, $reset = FALSE) {
  static $components, $enabled;

  if (!isset($components) || $reset) {
    $components = array();
    $disabled = array_flip(webform_variable_get('webform_disabled_components'));
    foreach (module_implements('webform_component_info') as $module) {
      $module_components = module_invoke($module, 'webform_component_info');
      foreach ($module_components as $type => $info) {
        $module_components[$type]['module'] = $module;
        $module_components[$type]['enabled'] = !array_key_exists($type, $disabled);
      }
      $components += $module_components;
    }
    drupal_alter('webform_component_info', $components);
    uasort($components, function($a, $b) {
      return strnatcasecmp($a['label'], $b['label']);
    });
    $enabled = array_diff_key($components, $disabled);
  }

  return $include_disabled ? $components : $enabled;
}

Line 4654 is the one that starts with "uasort" (near the bottom). I'm using

PHP 5.6.15
Drupal 7.41
Webform 7.x-4.12

Drush was working for the whole project (up till now) and webform was installed near the start of the project.

It's seems to be a problem with the anonymous function. I read some post that talk about a problem with eAccelerator and the PHP version. The recomendations are:

disabling eAccelerator and opcode caching
replacing eAccelerator with Zend's opcache
reverting to PHP 5.3

You can read more at:

The Webform issue about "Parse error: syntax error, unexpected T_FUNCTION"
http://php.net/manual/en/functions.anonymous.php#113422


Why can't I change textfield #default_value based on checkboxes' values after an AJAX response? I have been trying to learn Drupal forms with AJAX recently and from my current understanding of it I thought I should be able to do something like presented below (I wanted to store all selected values as a string in another hidden field to grab it later in my JS and do some stuff, but that does not matter here, what matters is what I do not get about AJAX).

So the idea is that selecting checkboxes will update the value in the input field with checkboxes' values.

Unfortunately, the #default_value on my textfield is not being set on my page, even though I can see it being set in my $form array when debugging with xdebug.

The form is used to filter some results with an AjaxResponse() ReplaceCommand.

Here is the simplified code, stripped from most unrelated things:

public function buildForm(array $form, FormStateInterface $formState)  {
  $values = $formState->getValues();
  $defaultCountry = implode(':', array_filter($values['countryId']));
  $form['countryId'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Country'),
    '#options' => [
      '1' => 'Aaa',
      '2' => 'Bbb',
      '3' => 'Ccc',
    ],
    '#ajax' => [
      'callback' => '::ajaxResponse',
      'event' => 'change',
      'wrapper' => 'some-wrapper-for-filters-form-and-results',
      'progress' => array(
        'type' => 'throbber',
        'message' => NULL,
      ),
    ],
  ];
  $form['defaultCountry'] = [
    '#type' => 'textfield',
    '#title' => $this->t('TEST'),
    '#default_value' => $defaultCountry,
  ];
  return $form;
}

public function ajaxResponse(array &$form, FormStateInterface $formState) {
  $result = 'some processing logic';
  $response = new AjaxResponse();
  $response
    ->addCommand(new ReplaceCommand('.filtered-offers > div', $result));
  return $response;
}

What do I miss here?

While I'm not sure why it doesn't work, the fix I've found in the past is to set the default value as #value in the AJAX callback. While this generally goes against the principle of #AJAX in Drupal (ie - changes should be made in the form definition), it works.


Using base_url() in image paths without using PHP? So normally I can do <img src="<?php base_url(); ?>/default/files/image.png" /> and that works just fine if I enable the php filter.

The trouble is that enabling the php filter disables all shortcodes. My drupal site is not installed in the root of the domain so  will not work.

Is it possible to have a relative path (this site will be moving once I'm finished) but have drupal know it's relative to the base url without using php? Maybe a setting?

in your .htaccess file, you could try something like:

RewriteEngine on

(in case it is not already turned on)

RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
RewriteRule ^$ subfolder [L]

(where in this case 'subfolder' represents the address of the installation)

This should create a system based, base url, rather than a php based url - so relative paths should work.


Suggest a page template for a specific view I have a view news how do you a suggest a particular theme file for it? For example page--news.tpl.php?

In case of Views 2, One of the option would be to name your template file "views-view--news.tpl.php".

There are  other useful options like "views-view--news--page.tpl.php" or  "views-view--news--block.tpl.php" depending on your display type.

You may find This tutorial useful .


How do I create a .tpl file for a panel pane? So, I want to add some HTML to surround the output of a Panel pane. I know the existing pane is rendered with:

panels-pane--entity-field-extra.tpl.php

If I edit this file, of course, every pane using it will show the changes.

If I create a new .tpl, say panels-pane--entity-field-top.tpl.php how do I apply it to a particular pane?

You can refer Documentation on Panels Pane template, which provides details on how to define a template for Panels Pane. If you want to add your own template name you can also do that by implementing template_preprocess_panels_pane in your theme or module file. Example for same is also available on documentation page.


Drupal 8 Menu always show as expanded I'd like to have a menu show as expanded regardless of whether it is checked or not in the UI (or always checked when a new menu item is created by a user)

I have been looking at hook_menu_links_discovered_alter

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook_menu_links_discovered_alter/8.1.x

  expanded: (optional) If set to TRUE, and if a menu link is provided
  for this menu item (as a result of other properties), then the menu
  link is always expanded, equivalent to its 'always expanded' checkbox
  being set in the UI.

How could I implement this?

If you are placing the menu in a block for display, check out the Menu Block module https://www.drupal.org/project/menu_block it has an option to expand all menu links.


domain with og access issue My site uses the Domain and OG modules.

I created the following content types: Group and  Group Post. I added OG visible field on Group, and OG content visible field on Group Post. Then, I created a group node, set the visibility as private. I created a group post node, and set the visibility as private.

I log out, and verified that anonymous users can see both.

I tried to build a new site with Drupal, and OG. When I follow the above steps, the result is right: Anonymous users can't see the two nodes.

I googled the issue, and found Visibility Access issue and Domain Access.

It seemed that the Domain and OG modules can't work together.

Does anyone have any solution?

https://drupal.org/project/domain_access_bridge

This module creates a working interplay between the Domain Access suite, one {access control} module (e.g. Organic Groups, Content Access, Taxonomy Access) and eventually the Workflow module.


How to validate temporary files with form API Problem

I have a custom form with three file fields. The files are selected, then on submit they're attached to an email and sent off with a call to hook_mail.

I'm pretty sure the files aren't saved to the server and I don't want them saved as the files might be sensitive information.

But I want the fields to support certain file extensions. How can I validate them?

So Far

There is a function: file_validate_extensions which can validate but it only works for Drupal file objects and since these are never uploaded I'm not sure that works.

I tried using file_save_upload, as when a file is selected in a form (and not immediately uploaded) it's information appears in $_FILES so I tried to load the temporary path given there however it doesn't work.

(The path is of the form: C:\XAMPP\tmp\phpEDC6.tmp)

function mymodule_form_submit($form, $form_state) {
    $coverincluded = file_save_upload($_FILES['files']['tmp_name']['cover_letter_included'],
       array(
          'file_validate_is_image' => array(), // Validates file is really an image.
          'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
       ));

     //unfortunately this dpm never shows, presumably because file_save_upload hasn't worked
      dpm($coverincluded);
 }

This isn't a particularly clever solution, but hopefully it's ok. As far as I could tell you can't validate temporary files, they have to be uploaded.

So I ended up uploading them to the private directory and then immediately deleting them. Because some of the data might be sensitive I don't want to store them and this form takes place on a secure page.

function mymodule_form($form, &$form_state) {

   $form['file1'] = array(
     '#type' => 'file',
     '#title' => t('File1'),
   );

   $form['file2'] = array(
     '#type' => 'file',
     '#title' => t('File2'),
   );

}

Now for the important bit.

function mymodule_form_submit ($form, &$form_state) {
    //check if any file was attached
    if($_FILES['files']['tmp_name']['file1'] != '') {
      //Save and validate the file to the private file area
      $file1_included = file_save_upload('file1_included',
                                     array(
                                        'file_validate_is_image' => array(), // Validates file is really an image.
                                        'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
                                      ), 'private://');
      //This is set-up for the email. Mimemail stores attachments in $params.
      $params['4'] =  array('uri'    => $file1_included->uri,
                          'filename' => $file1_included->filename,);
      //The file has been uploaded. So we'll set a variable which will be called later to delete it.
      $del_files['file1'] = $file1_included;

    }

   if($_FILES['files']['tmp_name']['file2'] != '') {
   //.... same as file 1...
   }

  //this will send an email. Note $params. We've put all our attachment information in
  //there.
  $message = drupal_mail('mymodule', 'notify', $email, language_default(), $params);

  //This function will delete all the files we've just uploaded. We check if
  //the variable has been set. And if it has then we call it and delete the relevant
  //files.

  if (isset($del_files)){
    _tellafriend_filedelete($del_files);
  }

}

This is the function we call to delete the files

function _mymodule_filedelete(&$del_files){
   //we know the variable exists, but now we have to check which files were uploaded.
   if(array_key_exists('file1' , $del_files)) {
    //and if they were uploaded. We delete them.
    file_delete($del_files['file1']);
  }
   if(array_key_exists('file2' , $del_files)) {
    file_delete($del_files['file2']);
  }
}


Can the confirmation URL be different based on different selections made using conditionals? Hello all of you super helpful people. :)
Drupal 8
Webform: Version: 8.x-5.19
I have created a webform which requires the person completing the form to select one of 4 options and whatever they select determines what fields they see or not.
One of the fields, when selected, needs to take the person to a different URL upon submission, but I am having a difficult time finding out if this is even possible to do...
EXAMPLE
Select:

Home (submit button takes you to the confirmation page)
Work (submit button takes you to the confirmation page)
Campaign (submit button would take you to a different URL (internal or external)

Does this make sense? Is this even possible to do?
Any assistance with this would be greatly appreciated!
Thank you!

As there is nothing out of the box that will support this
the good news it is quite straight forward in a custom module.
in this example
i have admin/structure/webform/manage/WEBFORMID/settings/confirmation
Confirmation type:
-> Page (redirects to new page and displays the confirmation message)
aka normal in your case for "Home" and "Work"
then you need a custom module to do ...
/**
 * Implements hook_form_alter().
 */
function MYODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // You will need your $form_id.
  // dump($form_id);
  if ($form_id == 'webform_submission_test1_add_form') {
    $form['actions']['submit']['#submit'][] = 'MYODULE_test_form_submit';
  }
}
/**
 * Implements hook_form_submit(). ish.
 */
function MYODULE_test_form_submit(&$form, FormStateInterface $form_state) {
  $form_values = $form_state->getValues();
  // this needs to be your element key.
  if (!empty($form_values['select_one'])) {
    if ($form_values['select_one'] === 'campaign') {
      // Redirect to some page
      $form_state->setRedirect('entity.node.canonical', [
        'node' => 7
      ]);
    }
  }
}


How to write big updation code using Batch API? I am writing a script to update all website registered user's Username & Email address. I have more then 5000+ users in my website which causes PHP execution time out error.

So I tried to implement Batch API but I am unable to implement it. I passed whole user list to Batch API and perform operations on it. But Batch API also shows the same PHP time out error.

Can someone help me to implement Batch API?

Here is my code:

function anonymize_data_menu() {
  $items = array();
  $items['admin/config/content/anonymize-user-data'] = array(
    'title' => 'Anonymize User Data',
    'description' => 'Click this link to anonymize user data',
    'type' => MENU_LOCAL_ACTION,
    'page callback' => '_anonymize_users_data',
    'access arguments' => array('administer user anonymize'),
    'file' => 'anonymize_data.user.inc',
  );
  return $items;
}

function _anonymize_users_data() {
  $users = entity_load('user');
  $chunks = array_chunk($users, 20);
  $count_user = count($chunks);

  foreach ($chunks as $chunk) {
     $operations[] =  array('user_anonymize_op', array($chunk));
      //user_anonymize_op($chunk);
     //krumo($chunk);
  }
  $batch = array(
    'operations' => $operations,
    'title' => t('Import batch'),
    'init_message' => t('Initializing'),
    'error_message' => t('An error occurred'),
    'finished' => 'user_anonymize_op_finished'
  );
  batch_set($batch);
  batch_process('admin/people');
}

function user_anonymize_op($users, &$context) {
  foreach ($users as $user) {
    # code...
    //krumo($user);
   $context['message'] = t('processing user @user', array('@user' => $user->name));
    //
      if($user->uid != 0 && $user->uid != 1) {
      $user->name = $i . '-' . $user->name;
      $user->pass = user_hash_password('blah');
      user_save($user);
    }
  }
}

function user_anonymize_op_finished($success, $results, $operations) {
  if ($success) {
    $message = count($results) . ' processed.';
  }
  drupal_set_message(t($message));
}

I am very confused about that how to process chunk of users.

Can someone help me it will be great.

The timeout is caused because you're trying to load all 5K+ users before you start the batch. Instead get the User IDs first and load when processing. Check an example below. Also have a look at Batch API Overview documentation page, before you continue:

function anonymize_data_menu() {
  $items = array();
  $items['admin/config/content/anonymize-user-data'] = array(
    'title' => 'Anonymize User Data',
    'description' => 'Click this link to anonymize user data',
    'type' => MENU_LOCAL_ACTION,
    'page callback' => '_anonymize_users_data',
    'access arguments' => array('administer user anonymize'),
    'file' => 'anonymize_data.user.inc',
  );
  return $items;
}

function _anonymize_users_data() {
  // Instead of loading all users at once,
  // first get there uid and then load chunk of user while processing.
  // $users = entity_load('user');
  $uids = db_select('users', 'u')
    ->condition('u.uid', 1, '>')
    ->fields('u', array('uid'))
    ->execute()->fetchAllKeyed(0, 0);

  $chunk_count = 20;
  // We've all rows here, split them in chunks.
  $chunks = array_chunk($uids, $chunk_count, TRUE);
  // Get all rows count.
  $num_operations = count($uids);

  $operations = array();
  foreach ($chunks as $chunk) {
    $operations[] =  array('user_anonymize_op', array(
      $chunk,
      array(
        'max' => $num_operations,
        'chunk' => $chunk_count,
      )
    ));
  }

  $batch = array(
    'operations' => $operations,
    'title' => t('Import batch'),
    'init_message' => t('Initializing'),
    'error_message' => t('An error occurred'),
    'finished' => 'user_anonymize_op_finished'
  );

  batch_set($batch);
  batch_process('admin/people');
}

function user_anonymize_op($rows, $batch_data, &$context) {
  // Define variables on start of batch operation.
  if (!isset($context['results']['progress'])) {
    $context['results']['progress'] = 0;
    $context['results']['chunk'] = $batch_data['chunk'];
    $context['results']['max'] = $batch_data['max'];
    $context['results']['failed'] = array();
  }

  // Do your processing here. START HERE.
  $names = [];
  $users = entity_load('user', $rows);
  foreach ($users as $account) {
    if (!empty($account->uid) && ($account->uid > 1)) {
      // What is $i here?
      $account->name = $i . '-' . $account->name;
      $account->pass = user_hash_password('blah');
      user_save($account);
      $names[] = $account->name;
    }
  }
  // Do your processing here. END HERE.

  // Update completion count.
  $context['results']['progress'] = $context['results']['progress'] + count($rows);

  $context['message'] = t('Processed @name user data.', array('@name' => implode(', ', $names)));

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['results']['progress'] != $context['results']['max']) {
    $context['finished'] = $context['results']['progress'] % $context['results']['max'];
  }
}

function user_anonymize_op_finished($success, $results, $operations) {
  if ($success) {
    $message = count($results) . ' processed.';
  }
  drupal_set_message(t($message));
}


Ajax HTTP Error Occured in Theming Tables I have two elements in my form: a select element and a div with an id of #myid_table_wrapper.

function myid_print_user_page_form()
{
    $form = array();

    $form['options'] = array(
        '#type' => 'select',
        '#options' => array(
            0 => t('All'),
            1 => t("Printed ID's"),
            2 => t("Unprinted ID's")
        ),
        '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_table_wrapper',
        ),
    );
    $form['myid_table_wrapper'] = array(
        '#type' => 'item',
        '#markup' => '

',
    );
    return $form;
}

Everytime the select element fires an onchange event it calls a callback function named myid_print_all_submitted_id_callback.

function myid_print_all_submitted_id_callback($form, $form_state)
{
    // Build the sortable table header.
    $header = array(
        'id_number' => array('data' => t('ID Number'), 'field' => 'id_number','sort' => 'asc'),
        'student' => array('data' => t('Student'), 'field' => 'student', 'sort' => 'asc')
   );

   //Get the node data.
   $query = db_select('student', 't1',array('target' => 'import'));
   $result = $query
       ->fields('t1', array('studid','lastname', 'firstname', 'middlename', 'extname'))
       ->condition('t1.id_status',2,'=')
       ->distinct()
       ->execute();
   //Build the rows.
   $rows = array();
   foreach($result as $record){
       $rows[$record->studid] = array(
           'id_number' => $record->studid,
           'student' => $record->firstname . ' ' . $record->middlename . ' ' . $record->lastname . ' ' . $record->extname,
       );
   }
   return theme('table', array('header' => $header, 'rows'=> $rows));
}

The code results to an error:

Whats wrong with my code? How will I debug this?

The correct way to do this is to populate the id table inside the form generation function (checking $form_state['values']). Then the callback should only return the form element.
This is an example of how I would do it:

function myid_print_user_page_form($form, $form_state)
{
    $form = array();

    $form['options'] = array(
        '#type' => 'select',
        '#options' => array(
            0 => t('All'),
            1 => t("Printed ID's"),
            2 => t("Unprinted ID's")
        ),
        '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_table_wrapper_div',
        ),
    );
    $table_html = '';

    // Check if option has been selected.
    if(!empty($form_state['values']['options'])){
      // Build the sortable table header.
      $header = array(
          'id_number' => array('data' => t('ID Number'), 'field' =>   'id_number','sort' => 'asc'),
          'student' => array('data' => t('Student'), 'field' => 'student', 'sort' => 'asc')
       );
       //Get the node data.
       $query = db_select('student', 't1',array('target' => 'import'));
       $result = $query
           ->fields('t1', array('studid','lastname', 'firstname', 'middlename', 'extname'))
           ->condition('t1.id_status',2,'=')
           ->distinct()
           ->execute();
       //Build the rows.
       $rows = array();
       foreach($result as $record){
           $rows[$record->studid] = array(
               'id_number' => $record->studid,
               'student' => $record->firstname . ' ' . $record->middlename . ' ' . $record->lastname . ' ' . $record->extname,
           );
       }
       $table_html = theme('table', array('header' => $header, 'rows'=> $rows));

    }

    $form['myid_table_wrapper'] = array(
        '#type' => 'item',
        '#markup' => $table_html,
        '#prefix' => '
',
        '#suffix' => '
',
    );
    return $form;
}

function myid_print_all_submitted_id_callback($form, $form_state)
{
    return $form['myid_table_wrapper'];
}

This is untested, but you get the idea.


views in D7 :: remove doubles in exposed filter list I have two content types, one (A) refering to the other (B). I also have two languages and I want to create a view where I show a list of all content type nodes of type A with an exposed filter, filtering the refering content type nodes of type B. this will show me all nodes of A that refer to B.
so my filters are

content type (A)
language (en)
refering node (exposed)

this works great but inside my exposed filter list of all nodes of type B every node is shown two times, representing every language translation.
I now want to only show the english nodes of type B in the exposed filter list.  how could I do that?
thnx!

ps: I tried to use the filter groups, but this did not work.

The Views exposed filters block is a Drupal form, one that can be modified via a hook_form_alter or hook_form_FORM_ID_alter implementation. Here is a simple sample implementation of the more generic hook_form_alter.

/**
 * Implements hook_form_alter.
 */
function foo_helper_form_alter(&$form, &$form_state, $form_id = NULL) {
  if($form['#id'] == 'views-exposed-form-content-page') {
    // Do something with mah filters...
  }
}

If you are in doubt of what #id to use, you can always just implement this hook, go to your Views page, and watch the output of the $form variable to figure out what is the correct id to use. If you are in D7, the ID you are looking for will most likely be prepended with views-exposed....