Wrong text being shown in a template file When I add text in Hebrew inside html.tpl.php, it shows me strange characters instead of the ones I am expecting.

How can I fix this?

You need to set the encoding of new files to utf-8 in your text-editor. The image below is on Notepad++. There should be a similar setting in your text editor.

To test if you got it right, create an HTML/PHP file with the Hebrew text outside of Drupal first.

For Notepad, Save As and select UTF-8 as the Encoding.

Also, make sure you have the following line in the <head> tag of your HTML:

<meta charset="utf-8">


How to create an autocomplete textbox in register page - Drupal 6 Consider I am doing a registration form with the following fields.

1. Name

2. Email

3. City

Here the city should be auto complete.

I created the city field with the help of content profile module in order to add more fields in future.

Now how can i make the "City" text box auto complete.

How can i store the records in the table ?

Thanks in advance...

There's a full example for Drupal 6 here: [Textfield that uses autocomplete][1]. The code will probably be useful to people on this site as well so I'll post i here:

The following is based on a module with the name: 'cities'

In your form function:

$form['city'] = array(
  '#type' => 'textfield',
  '#title' => 'City',
  '#maxlength' => 128,
  '#autocomplete_path' => 'cities/autocomplete',
);

In your module file:

function cities_menu(){
  // path with autocomplete function for cities
  $items['cities/autocomplete'] = array(
    'title' => 'Autocomplete for cities',
    'page callback' => '_cities_autocomplete',
    'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
    'type' => MENU_CALLBACK
  );
  return $items;
}

Also in your module file:

function _cities_autocomplete($string) {
  $matches = array();
  //search table `cities` for cities that begin with the letters the user enters in the form
  $result = db_query_range("SELECT city FROM {cities} WHERE LOWER(city) LIKE LOWER('%s%')", $string, 0, 10);
  // add matches to $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->city] = check_plain($data->city);
  }
 print drupal_to_js($matches);

}


Views to display recent content with user pictures I want to create a view displaying the recent content posted by users along with their respective pictures. I am able to Create the view displaying recent content but how to display the respective user picture who created the content along side the content.

Add a relation ship of the type content:author and use that relationship to add the user profile image.

Hope that helps.

EDIT : A description as per the comment

1) From RELATIONSHIPS(This would be in the advanced section on the right side) click on add. it will bring up a list of fields that you can add.

2) Add the Content: Author relation ship.

3) Now When you try to add the a field additional fields would be displayed related to the user you can select  User: Picture. The relationship author should be select.


Populate a select box with a vocabulary I have a select box that I want to populate with a particular taxonomy programmatically. If i was was to use a taxonomy vocabulary how would i populate a particular select box in my form. My form is generated using the from api and not using content types. If for example I was to have a vocabulary called countries. I have a select box which currently is configured like this

 $form['status']['currentstatus'] = array (
 '#values' => array(t('red'), ('green'))

 );

$form['status']['currentStatusList'] = array (
    '#title' => 'current status',
    '#type' => 'select',
    '#options' => $form['status']['currentstatus']['#values']
);

Instead of just adding the values I would like to pass a vocabulary.

I have manged to get the vocabulary data
but a zero is placed before the terms.

the code I figured out for the box is the same as yours. I even pass the id for the vocabulary. I will have a play with it thanks for your help

You should be able to use the taxonomy_get_tree function to get all the children of the term, and then just run a foreach() on that.

Example:

function mymodule_blah($vocabulary) {
  $terms = taxonomy_get_tree($vocabulary);

  foreach ($terms as $data) {
    $output[$data->tid] = $data->name;
  }

  return $output;
}

This should return an array keyed by Term ID, although you could put whatever you want where it says $data['tid'] to put a different key in.

Example output:

[1] => ['My First Term']
[2] => ['My Second Term']
...
[15] => ['My Fifteenth Term']

Then pass this to your '#options' on your select box.

EDIT:

Forgot to mention that the helper function will need the vocabulary ID passed to it - should have added in the clarification just for completeness' sake.

EDIT 2 (full implementation):

function mymodule_myform($form) {
//The rest of your form stuff is in here
$form['status']['currentStatusList'] = array (
    '#title' => 'current status',
    '#type' => 'select',
    '#options' => mymodule_selectbox_contents(PUT THE NUMERIC VOCABULARY ID HERE)    ,
);
//The rest of your form stuff is in here
}

function mymodule_selectbox_contents($vid) {
  $terms = taxonomy_get_tree($vid);

  foreach ($terms as $data) {
    $output[$data->tid] = $data->name;
  }

  return $output;
}


How to add an specific action button in views? Is there any way to add a specific action button in view module for an entity I've created programmatically.

More specifically, I want to make a search of my entity in view, and having beside each result of the entity an action button .  Currently,  we can configure 'delete/edit' button. I want to add a specific one.

PS: I'm using Drupal 8 and i created my module an entity with drupal console.

Here is the solution I found for my problem:
Let say that my entity is named Entity.
I created a new operation in my controller implementing my business logic ,  say we'll call it operation_name.
Then, in my EntityListBuilder.php , I surcharged the operation getDefaultOperations, specifying the name of my operation, the url and title :

 public function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);
    $operations['operation_name'] = array(
        'title' => $this->t('operation_title'),
        'weight' => 30,
        'url' => new Url('url',array(
          'medecin' => $entity->id(),
          )
        )
      );
      return  $operations;
    }

Back to my view configuration: In adding fields section I will add "Action link" , we will notice that the operation "operation_name" was add to the others (edit and delete).


How to include node title in teaser I am using Display Suit module to enhance the apache solr search results page. I use the Teaser view mode, but I don't get the node title in the teaser, because the node Title field is not available in the Content type display setting under teaser settings.

Is there any alternative way to add the node title as part of teaser view?

Even when Display Suite is enabled, you need to set a layout for it to be enabled for that particular content type. If you just want one column you can select the "One Column" and it will add all the fields available with Display Suite.

It should look something like this:


How to show language switcher only on home page In my multilanguage site i am using Language switcher (User interface text) and I have it located in block called "Help". This block is shown in the middle of the site, where I want it. But I want it to be displayed only on homepage. I tried to hide by the restriction of a content type. But I wasn't successful.

Set block visibility to only show on <front>


Create a taxonomy view that links to different photos I'm creating a website for a business who sells and installs rail fencing for their clients.

For the fence, there are three different categories of interest:

fence type (2 rail, 3 rail, etc)
fence application (barrier, dog fence, horse fence, etc)
fence material (pressure treated, pine, etc)

I'm trying to create a method of giving the site visitor to choose how they want to look at the pictures.

Each time a fence is installed and photos are taken, I want the business to be able to sign in, create a node called "Photos," Add a title, cover image, body, group of images, and then tag the node using the 3 categories above (on three separate taxonomy lines).

From there, the site would automatically arrange the added photos into the pre-configured view based on its categories.

http://fence.ckasdf.net is the site.

The menu item marked "Photos" shows a view that separates each slideshow by "job" or node called Photos.  This works as expected.

The menu item marked "View: Fence Application" is a view of taxonomy and shows the various applications.  Clicking on each link shows the various nodes (jobs) that have been tagged with that particular application, and clicking on a node shows the picture slideshow.

Instead, after a taxonomy term is clicked, I want it to load a page showing a slideshow that includes all the photos relevant to that taxonomy term.

Here I am adding the screenshot for the configuration section for this module which you will find in your vocabulary manage display.

Screenshot


Where did date-time "add [custom] format" go in Drupal 7? In D6 this was located in,
Site Configuration >> date & time >> formats >> add format
Where is this in D7?

I found this Drupal.SE question: Date value to different date format explaining the code to create a custom format, but it doesn't say in which file to make the change.

Configuration -> Regional & Language -> Date and time -> Formats -> Add format.

You end up at /admin/config/regional/date-time/formats/add.


Help with JQuery Toggle Div, Start in Hidden State Alright, this has been driving me insane for all too long. I'm trying to toggle a div, but start it in a hidden state. Suggestions on how to modify the following?

// Drupal 7 js code
(function ($) {
Drupal.behaviors.togg = {
attach: function (context, settings) {
$('a#togg-link:not(.togg-processed)', context).addClass('togg-
processed').each(function() {
$(this).click(function() {
$("div#togg").toggle(400);
return false;
});
});
}
};
})(jQuery);

Try this - In your loop, where you are iterating over each element to attach a click event handler, add this line:

$(this).hide();

That should hide each element. But don't add it to your click event handler. You can also initially hide the element using CSS if you want. Either method should work.

Please consider properly formatting code samples you post so that the community can read and understand it easier.

Good Luck!


Get content of selected option after user select any option from select field I have created a content type, This content type form having a select box.

I need to develop a functionality like once the user select any option from select field the following textbox should having options like auto-complete data to respected selected option.

I can not create taxonomy and dependency because the database is very large. unable to add all data to taxonomy.

I want to do it by using ajax on change option. How can I achieve this?.

Can anyone suggest the easiest method?

I have done same with User Roles and Users. Check below code if you can find it helpful.

function custom_menu(){
    $items = array();
    $items['custom'] = array(
        'title' => 'custom',
        'description' => 'Custom',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('custom_form'),
        'access callback' => TRUE,
    );

    // " % " is the RID coming from '#autocomplete_path'.
    $items['autocomplete/%'] = array(
        'page callback' => 'autocomplete_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );
    return $items;
}

function custom_form($form, &$form_state){
    $options = array();
    $roles = user_roles($membersonly = TRUE); // Getting list of Roles.

    // Removed "Authenticated" role from the list.
    // That is not listed in "users_roles" Table.
    array_shift($roles);

    foreach ($roles as $key => $value) {
        $rid = user_role_load_by_name($value);
        // Give RID to each role as their key in array.
        $options[$rid->rid] = $value;
    }

    // Defining $role as selected value of Select list.
    $role = !empty($form_state['values']['roles']) ? $form_state['values']['roles'] : '';

    $form['roles'] = array(
        '#type' => 'select',
        '#title' => 'Role',
        '#options' => $options,
        '#ajax' => array(
            'wrapper' => 'auto-wrapper',
            'callback' => 'select_callback',
        ),
    );

    $form['auto'] = array(
        '#type' => 'textfield',
        '#title' => 'Users',
        '#autocomplete_path' => 'autocomplete/' . $role, // Pass RID to path.
        '#prefix' => '
',
        '#suffix' => '
',
    );

    return $form;
}

function select_callback($form, &$form_state){
    return $form['auto'];
}

function autocomplete_callback($role, $string = "") {
  $matches = array();
  if ($string) {
    $query = db_select('users', 'u');

    if(is_numeric($role) && $role != ''){
        $query->join('users_roles', 'ur', 'ur.uid = u.uid');
    }

    $query->fields('u', array('name', 'uid'));

    if(is_numeric($role) && $role != ''){
        $query->condition('ur.rid', $role)
            ->fields('ur', array('rid'));
    }

    $query->condition('name', db_like($string) . '%', 'LIKE')
      ->range(0, 10);

    $result = $query->execute();

    foreach ($result as $user) {
      $matches[$user->name] = check_plain($user->name);
    }
  }

  drupal_json_output($matches);
}


How to solve Bootstrap Theme settings override problem? I'm using the Bootstrap base theme and a sub-theme (cdn) in one of my websites.
Normally everything was fine. Then I installed a fresh Drupal into another server and installed the themes I was using before. The problem appears there, I couldn't change any theme settings of Bootstrap themes via Drupal interface. For example I tick the Fluid container and save but it doesn't change, the box goes back to being unchecked.

The new server configurations may be different from old one.
Does anybody know what Bootstrap need for theme settings?

I solved this problem by disabling the ModSecurity on cPanel.

  ModSecurity is an Apache module that applies a set of rules to the activities of software run on Apache. It is used by some hosting environments to assure security, but some rules can interfere with the normal operation of Drupal.


Disable the Comment module Is there a way to disable the core Comment module in Drupal 8? The module is enabled by default, but I prefer not to use Drupal comment system and would like to not have it clutter up the GUI for site builders.

I do understand that disabling a module in Drupal 8 is the same as removing it -- perhaps that's why most core modules can't be disabled.

In Drupal 8, you cannot anymore disable modules. You can only uninstall a module, but in the case of the Comment module, you first need to remove any Comments field. In fact, on /admin/modules/uninstall you will see the following message:

  The following reason prevents Comment from being uninstalled:

  The Comments field type is used in the following field: node.comment

By default, the Comments field is added to every content type.

Once you remove that field from every content type, you will be able to uninstall the Comment module from a Drupal 8 site, if there isn't any module that depends from the Comment module. Otherwise, you first need to uninstall first those modules.

As for updating Drupal, updating Drupal doesn't install the core modules you previously uninstalled, not even the ones the profiles you used to install Drupal would install.


Add trailing slash to URLs when generating Sitemap with Simple XML sitemap I am trying to generate Sitemap for my site using Simple XML Sitemap module. I have checked the Documentation for Extending the module features. Since I am newbie to Drupal 8, I am in confusion how to get this achieved. tried some hooks but failed it may be my lack of understanding regarding drupal8 module development. Can anyone help me to get this done. What are the namespaces I should add to my custom module.

Currently my URLs are generated like www.mysite.com/country/india but I want it to be like www.mysite.com/country/india/ since I use trailing slash with URLs.

I've used htaccess to add trailing slash to URLs with 301 redirect.

You can use hook_simple_sitemap_links_alter() to change the links generated before the sitemap is saved.

function example_simple_sitemap_links_alter(&$links) {
  global $base_url;
  foreach ($links as $key => $link) {
    if ($links[$key]['url'] != $base_url . '/') { // Excluding base url
      $links[$key]['url'] = $link['url'] . '/'; // Here Trailing slash will be added
    }
  }
}

Before using the hook:

After using the hook:


Multiple Indexes with Apache Solr Is it possible to use multiple indexes with Apache Solr? We want to use different indexes depending on the environment id.

Setup multiple solr core's and then use settings.php to define for each environment as poster above said.

If you are using ApacheSolr its like:

$conf['apachesolr_environments']['my_env_id']['url'] = 'http://localhost:8983';

Just make sure your settings.php is not moved from server to server, if it is then use environment variable in apache:

SetEnv ENVIRONMENT development
SetEnv ENVIRONMENT staging
SetEnv ENVIRONMENT production

And use something like this in settings.php

<?php
switch ($_SERVER['ENVIRONMENT']) {
  case 'development':
    $conf['apachesolr_environments']['my_env_id']['url'] = 'http://localhost:8983';
    break;
  case 'production':
    $conf['apachesolr_environments']['my_env_id']['url'] = 'http://www.domain.com:8983';
    break;
}
?>


How to alter combined filter value programatically? When taxonomy terms are combined, the values searched are term id instead of term name. So I tried to alter the query using views_query_alter. But it seems the values are coming from object.

function MYMODULE_views_query_alter(&$view, &$query) {
 if ($view->name == 'my_view') {
   if (is_object($query->where[1]['conditions'][0]['field'])) {
     foreach ($query->where[1]['conditions'][0]['field']->conditions() as $key => $value) {
        if (is_numeric($key)) {
          $possible_terms[] = $value['value'][':views_combine'];
        }
      }
     // here i was planning to load the term id from the partial
     // term search key from combined filter
     // once the term is identified, i would like to update the query.
   }
 }
}

The problem is $query->where[1]['conditions'][0]['field']->conditions() is a function and I don't know how to substitute value to it.

The example on the hook_views_query_alter page should get you started. Whet they do here is changing the node title into the node id, by redefining the $condition variable.

function hook_views_query_alter(&$view, &$query) {
  // (Example assuming a view with an exposed filter on node title.)
  // If the input for the title filter is a positive integer, filter against
  // node ID instead of node title.
  if ($view->name == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {]

// Run through all conditions and pass them by reference.
// (Altering the value here will change it for all things later on.)

      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on title, chang the
        // condition to filter on node ID.

//If there is a condition on the title field

        if ($condition['field'] == 'node.title') {

// Overwrite the condition

          $condition = array(
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          );
        }
      }
    }
  }
}

You should be able to copy quite a lot of this function, tweak the initial if statement a bit so it does not filter on title, and substitute your own values.

I have not used a combined filter, but the Views API converts into similar to this. If you add some debug code to find out what the initial array is, you should be able to substitute that.


Debug PHP code with XDebug and VS Code For development I use a local Drupal 7 installation on Xampp under Windows 10. I use Visual Studio Code as IDE and want to debug my PHP code with it. I tried to set that up but can not quite get it working. This is my configuration:

Xampp installation path: c:\xampp
PHP: c:\xampp\php (version PHP 7.3.17 64bit)
Drupal files: c:\xampp\htdocs

php.ini additions:
[XDebug]
zend_extension = "c:\xampp\php\ext\php_xdebug-2.9.6-7.3-vc15-x86_64.dll"
xdebug.remote_autostart = 1
xdebug.profiler_append = 0
xdebug.profiler_enable = 0
xdebug.profiler_enable_trigger = 1
xdebug.profiler_output_dir = "c:\xampp\tmp"
xdebug.remote_enable = 1
xdebug.remote_handler = "dbgp"
xdebug.remote_host = "127.0.0.1"
xdebug.remote_log = "c:\xampp\tmp\xdebug.txt"
xdebug.remote_port = 9000
xdebug.trace_output_dir = "c:\xampp\tmp"
xdebug.remote_cookie_expire_time = 36000

VS Code launch config:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "runtimeExecutable": "c:\\xampp\\php\\php.exe",
            "pathMappings": {
              "c:\\xampp\\htdocs": "${workspaceFolder}"
            },
            "xdebugSettings": {
              "show_hidden": 1
            }
          }
    ]
}

I downloaded the correct xdebug DLL and put it in:
c:\xampp\php\ext\php_xdebug-2.9.6-7.3-vc15-x86_64.dll
In my Chrome browser I installed the "XDebug Helper" extension.
In VS Code I installed the XDebug extension and set a few breakpoints in my code.

Then I open my Drupal site in Chrome and hit debug in the XDebug Browser extension.
The breakouts don't get deactivated as "unbound" but the debugger does not stop at any of them either.
What am I missing?

In my VS Code launch config I had to change the pathMappings from this:
"c:\\xampp\\htdocs": "${workspaceFolder}"

into that:
"c:\\xampp\\htdocs\\sites\\all": "${workspaceFolder}"


Custom template file to use themes html/page.tpl I have a custom module (using Drupal 7) that adds a page using hook_menu(). Its callback just prints the value returned from theme('mytheme_hook').

If the content of my template file is simply 'hello world' I get only a white screen with the text output.

Is it possible for this page to extend the theme's html.tpl (and even page.tpl) with 'hello world' inserted in the 'content section' of the page?

This looks like a similar thing I am trying to achieve, but it doesn't offer a solution.

If you want your content to be inserted in the content section of the page you just need to return it (as HTML, or render array) from your page callback function. Then you can override the template of any (html/page/node) level for this page by standard theme hook suggestion and customize it.


How can I create a patch for a contrib module or core which is not in version control? Because we use a devOps system that installs packages on the server via Composer, my core drupal installation and contrib modules are not in version control (Git).

I used to patch modules as follows:

Commit everything, so my branch is up-to-date.
Make my changes to the module (= write the fixes in the module).
Inside my code editor go to Code -> Create patch and follow the steps there (because of Git, my editor knows what has changed).
My patch gets saved where I prefer to do it.

Since we started working with keeping modules and core out of Git I do not have a clue on how to create my patches anymore.

Curious about the solutions you might have!

So, you would have to download the module seperately, like:

git clone --branch 8.1.x http://git.drupal.org/project/colorbox.git

Then, you make the change and run the following:

git diff 8.1.x > colorbox-css-issue.patch

This creates a patch for this module. Now you can place the patch in a patches folder and add it to your composer.json file.
Helpful source: https://www.drupal.org/node/707484


Hide a field based on checkbox I want to hide the price for specific products in a product display. I have added a checkbox to the product display type and when it is checked I want to hide the price.

I have figured out that I can hide the field with hide($build['product:commerce_price']) in hook_node_view_alter but the problem is I don't know how to get the value of the checkbox. var_dump($build["field_hide_price"]) outputs null;

The conditional field module will do this for you. In this module when certain fields are selected, get value, ... other operations (hiding,removing,make it required,...) may happen


Node theming through Views or tpl.php files - which one is better for performance? As an example, let's take a node with 5 fields and two blocks between those fields. E. g. you want an article do be displayed like this:

First field

Second field

Block with related nodes

Third field

Fourth field

Block with ads

Fifth field

In D7, such display is quite simple to create with Views - you use contextual filters to output fields and just put two blocks between them.

Another option is to use node.tpl.php and create the same template.

Which of these two (Views with context. filters and tpl.php files) is better performance-wise, especially when it comes to MySql performance?

The two are essentially doing the same work and are going to degrade over load very similarly from my experience. If you look at how views works and builds its content, contextual filters is just aiding the discovery by passing in all the data the view needs. This has to be done one way or another. After that, the view builds the same regardless.

However, tpl files are greatly useful for code management. If you are really worried about performance, then you need to look into memcached and/or Varnish - both are open source and can be implemented easily on most *nix servers.


Which module will allow a user to grant another user permissions for editing content of content type I have a content type of 'project' and I want the creator of this content type to be able to allocate other users to be 'admins' on this project, so they have extended rights to edit the project details, archive the project, approve users attached to that project.
Is there a module that sounds like it can achieve some of this stuff?
thanks

If those are existing permissions on your site already and you just want to control delegation, it sounds like you might want the Roleassign module.

  RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.

  RoleAssign introduces a new permission called Assign roles. Users with this permission are able to assign selected roles to still other users. Only users with the Administer permissions permission may select which roles are available for assignment through this module.

If that is not sufficient for your needs, a combination of Roleassign and Workbench Access would likely serve your needs.

  Workbench Access creates editorial access controls based on hierarchies. It is an extensible system that supports structures created by other Drupal modules.

  When creating and editing content, users will be asked to place the content in an editorial section. Other users within that section or its parents will be able to edit the content. A user may be granted editorial rights to a section specific to his account or by his assigned role on the site.

A combination of these two modules would likely be more than adequate for your purposes.


View of Taxonomy with titles above the terms Does anyone know if I have a view of a Taxonomy Vocabulary - How do I get titles above all the term results?  Here is my page:
http://64.34.70.141/~henryl/bloom-size
I'd like to have titles like this website:
http://demo.commerceguys.com/ck/collection/drink
But I can't figure out how they've added the titles - I've tried to look through the view selections of the site but I can't get mine to match.
Can anyone help?
Thanks!

You have an unformatted list view of node teasers. Just click Format settings on view edit page, and turn on Force using fields. After that this result will be shown as teaser, but you can add fields.

Add your taxonomy term field to the Fields, and you can use it in Format settings Grouping field Nr.1. If the teaser doesn't contains this field, you have to add a relationship to the proper taxonomy term too.


How to set language for user register page / form per subdomain For a custom module, I need to change the language of the registration form based on the subdomain the user is currently active on.

I tried changing the global $language variable in hook_form_user_register_form_alter, but that does not work ($language variable is also not set at that point). I also tried setting the language in the $user object, but also no dice (probably because it is an anonymous user).

Finally I took a look at the language negotiation api, but setting up negotiation providers seems overkill for this (and haven't it studied enough to get a grasp on how to use it).

I just need to render the registration page in a different (but already available) language on /user/register, based on the subdomain. What would be the best way to achieve this.

I'm using Drupal 7.

Maybe you can use the Domain Locale module. It allows you to change the available and default languages per domain.


Is it safe to delete default image/file styles? For consistency and usability purposes, we want to set up a default set of image styles which are clearly understood by our editors. This probably means getting rid of default style names like "medium", "large" etc.

The question is, is this likely to break other third party/contrib code that relies on the Styles module? Might we need to patch these (possibly too much of a headache) or just configure them to use the new styles?

Note: styles seem to be defined and displayed to editors purely by their (sometimes auto-capitalised) machine names, so we can't set a friendly name that differs from this.

Also: Is it even possible to remove existing styles? I can only seem to find ways/hooks to add them.

You shouldn't remove the default styles (as mentionned), but you can alter them using hook_image_styles_alter

You can remove the options from selected forms using hook_form_alter (as mentionned).

I tried to find a generic approach and happily found this page.

This is how I applied the info:

function mymodule_form_alter(&$form, &$form_state, $form_id) {

  recursiveRemoval($form, 'thumbnail');
  recursiveRemoval($form, 'medium');
  recursiveRemoval($form, 'large');
  recursiveRemoval($form, 'square_thumbnail');

}

function recursiveRemoval(&$array, $val) {

  if (is_array($array)) {

    foreach($array as $key => &$arrayElement) {

      if(is_array($arrayElement)) {

        recursiveRemoval($arrayElement, $val);

      } else {

        if($arrayElement === $val) {

          unset($array[$key]);

        }

      }
    }
  }

}

N.B.: Use at your own discretion.


How to execute custom code on user signup I need to do a REST request every time a new user signs up.

The REST request returns some data that I need to store for the Drupal user account, and be able to present as content somewhere.

What is the best/cleanest way to do that?

You can do it in a simple custom module, be sure to first understand Drupal hooks system as this is the base for (almost) everything Drupal.

In your module, you can implement hook_user_presave() to be called before a user account is saved. It will be called for both creation and update, so you will need to guard your code with a condition to detect new user. After the REST call, there is several option to store the returned data. The easiest one is the use the data attribute of the user account. It is a simple PHP array that will be serialized in a database columns. It is not very good performande wise and not very flexible (you can query the stored data) but it is easy.

function MODULE_user_presave(&$edit, $account, $category) {
  // Accoding to user_save's documentation, this is a new user if
  // $account->is_new is set to TRUE or if $account->uid is not set
  if ($category == 'account' && (!empty($account->is_new) || !isset($account->uid)))) {
    $edit['data']['MODULE'] = MODULE_get_data_from_rest($account);
  }
}


Is using nodes for a notification system a performance concern? I am building a user activity notification system whereby each new notification message is created as a new node which is displayed by Views. To prevent an infinite number of nodes being created there is a system in place to delete notification nodes once they have reached a certain age.

This still begs the question however of whether using nodes in this way is a good idea for future performance. If a single user gets 20 notifications in a day, that is 20 nodes; now if there are potentially several hundred to a thousand users that is a lot of nodes in a short period of time. The main reason I use nodes is because they are easy to access and manipulate using Rules and also are very flexible when used with Views.

Therefore is it worth considering an alternative to nodes and if so what? The Messaging module comes to mind, but since each new Message is a new entity I'm not quite sure whether in terms of performance this would be any different to using nodes. Is there a module that offers the same flexibility of nodes but also has better performance?

I would go with Messaging. Dedicated Entity (if implement properly) is always faster than Node. I participated in the big D7 project and we were happy with Message API. By using a custom entity you can switch to custom storage, like: https://www.drupal.org/project/mongo_entity

This can be helpful for D8:

https://drupalwatchdog.com/blog/2015/3/entity-storage-drupal-8-way


Caching for every user In my website, users will be redirected to a "frontpage" page where they will be able to see the latest news, their special announcements, their own materials, etc. Now I have to use DB to retrieve all those information.
I also want to use caching for this purpose so the data on their frontpage refresh every 3 hours let's say instead of each visit.

I am using the following function to achieve this:

function mymodule_cache($reset = FALSE) {
  static $my_data;
  global $user;
  if (!isset($my_data) || $reset) {
    if (!$reset && ($cache = cache_get('user_data:' . $user->uid)) && !empty($cache->data)) {
      $my_data = unserialize($cache->data);
    }
    else {
      $my_data = ... (This is where I do all the DB queries, etc.);
      cache_set('user_data:' . $user->uid, serialize($my_data), 'cache', time() + 10800);
    }
  }
  return $my_data;

}

now this works great, but my question is how if I have tons of users, let's say 10,000 users, would it be efficient to still using this caching method since we are filling up the table rows with data?

Or if not, what is the best solution?

Thanks
Luca

In general, yes, you can do this. There is no limitation on the number of cache entries that can be stored. However, if using the default database cache backend, it can fill up your database and when additionally using the default cache bin, it can slow down other cache lookups. So, I would recommend:

Use a custom cache bin instead of the generic cache table. Especially important if you don't follow the second point. Because the cache bin 'cache' usually holds information that is requested on almost every request.
Use a different cache backend, e.g. Memcache. That avoids that your database gets big due to these cache entries and makes cache lookups faster. See https://drupal.stackexchange.com/questions/12307/where-is-the-best-place-for-cache-bins-drupal-7

Two additional tipps:

Monitor the number reads/writes of that cache to see if the cache actually helps. If, say, 50% of the cache entries are only written and never read, you might want to consider to avoid caching this information.
Especially when using a cache backend like Memcache (which has a smaller overhead for cache calls), it might be helpful to split the data up into several separate cache entries. There a number of benefits for this:

You can cache certain information longer than others (maybe there only is a new announcement every few days but multiple new comments/whatever per hour
Some of the data might not even be user specific but only specific for the roles a user has or even global. So for example, all anouncements could be read from a single cache entry.
You can use cache_clear_all() to clear specific caches on defined events. For example, clear all news caches if a new news is published. By doing this, all users will be able to see the news immediatly. If this is working well, you can increase the cache expiration time.


can hook page alter also do all the things that hook form alter can do..? Since the page alter hook also has information about individual form fields is it correct to say that hook page alter can do everything that hook form alter can do

Not, for sure hook_page_alter can't do everything that hook_form_alter (or other form alter hooks) can do.

Form alter functions allow to alter the form itself, its structure, values and valid values, submit and validate handlers, etc. This is because they are fired early in the Form API workflow. When Form API ends its work there's a render array that Drupal can render as HTML code.

After all form alter hooks are done (and any other code that generates the page content) comes hook_page_alter, but the form is done. Any alterations you make will be unkown for the Form API layer, most of the times resulting in strange validation errors form Form API (for example the 'Illegal Choice has been detected').

What you see in the hook_page_alter is not a form but the render array of a form: Here you can't modify submit or validate handlers, options of a select wiidget or add new elements in a multiple element field.

From hook_page_alter:

  If you are making changes to entities such as forms, menus, or user
  profiles, use those objects' native alter hooks instead
  (hook_form_alter(), for example).


"No query was run" when Contextual Filter is added. Was working before I have a bunch of nodes with terms in a certain vocabulary. The vocabulary consists of doctors' specialties, like "Gynecology / Obstetrics". Terms in this vocabulary have a few extra fields:

Singular noun form ("Gynecologist / Obstetrician")
Plural noun form ("Gynecologists / Obstetricians")
URL string ("obgyn")

I have a view that displays all the nodes associated with the term. The view's path is "doctors/specialties/%", and it has a Contextual Filter for the URL String field of the taxonomy term, via a taxonomy Relationship. So when you go to /doctors/specialties/obgyn, you get a page with a heading "Gynecologists / Obstetricians" and then all the content with that term.

This view previously worked perfectly, but at some point something changed, and now it returns 404. The preview in the Views UI just says "No query was run". When I delete the Contextual Filter, it shows all the normal SQL, but when I re-add it, it goes back to "No query was run".

Here's a dump of the view. Can anyone tell me what I'm doing wrong?

I had already flushed caches and reloaded the page twice (yes, I'm positive, and yes, I swear) when I originally asked this question, but at some point my view magically started working again. So I guess I should have just flushed caches and reloaded the page harder.


Can a product support recurring and not recurring payment at the same time? So if for some product variant I check option "Allow subscriptions" all product variants of that products can be bought only in recurring way? Is that true?

I mean, I can not have one product and one set of variations that can be purchased "normal" way (by paying whole price during checkout process) and other set of variations support subscriptions and recurring payment? Is that right?

If I want to support both ways of paying (recurring and "normal") for one product I actually have to create 2 separate products? Correct?

Asking because when I edit product variation fields "Subsription type" and "Billing schedule" are both mandatory.

If you take a look at this page, you can see that what comes out of the box is that you create a seperate product variation for the recurring products and then create seperate products.

Instructions from the docs:

  Download and install the Commerce Recurring Framework and Advanced queue Drupal modules.

  Create a variation for the recurring products
  Go to admin/commerce/config/product-variation-types

  Add a product variation type with the “Allow subscriptions” trait
  Create a product type for recurring products

  Go to admin/commerce/config/product-types
  Add a product type that uses the previously-created product variation

  Create one or more billing schedules. The billing schedules will become options when configuring your product.

  Go to admin/commerce/config/billing-schedules
  Create a new billing schedule with the desired options

  Fixed (specific day of month) or rolling (from creation date)
  Dunning options to remind users for expiring credit cards

  Create a product

  Use the previously-created product type, with the recurring variation
  Use the desired billing schedule

A possible solution would be to create a custom block that switches between the two products on the product page.

If you want to fetch data from the recurring product on the normal product, you might want to create a reference field to the recurring product on the normal product.


How to implement a nomination process for nodes? I want to implement a nomination process. Users should be able to

Nominate existing Nodes of type 'course'.
Nominate new content that should later be of type 'course'.

All nominations should be listed somewhere.

What's the best way to do this?

For 1. I thought about using the Flag module and then just make a view where all nodes with nomination flag are listed.

For 2. I'm not sure, maybe I use webforms and the admin has to transfer it into a node of type 'course'. But how do I get a list of new AND existing nominated content?

How about using modules Node_convert, and Flag (which is obviously a must have for what you're looking for)? About Node convert (from it's project page):

  adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

I'm using Node_convert already for long time, works great. It allows for implementing a lifecycle (or workflow?) to start from a node that is only just something like an idea (or suggestion, question, issue, abstract, etc). Those ideas that get the highest votings, are the ones that seem to make sense to handle with highest priority. Compare it to a 'Question' with a lot of votes, but with hardly any (or no) answers.

When the node's content evolves (read: the more effort/details added to it), I convert its content type to finished products like (eg) a recipe, a redbook (already from my Drupal 6 days a few years ago).

By combining it with some type of access module (related to either taxonomy or content type) I can make it more restrictive to give access to it. E.g. public to start from, then "authenticated", and in the end only for roles such as "subscribers", "students", etc.

Maybe you also want to consider Fivestar and/or Voting API (I have the impression that "Voting" is a kind of synomym of what you mean with "Nominate").

And of course: use Views as you are considering already. To continue my samples above: using some basics Views reports, you can easily massage it all in a todo list also.


How can I attach the same library with Javascript multiple times on the same page with different settings? I have a custom field formatter that attaches a library that includes a javascript file. It uses drupalSettings to pass some values to the script.
The first time the field formatter appears on a page, it works as expected. However, subsequent appearances of the formatter behave as if they have no script attached.
A simplified example:
(function ($, Drupal, drupalSettings) {
  $(document).ready(function () {
    var selector = drupalSettings.gallery.id + ' .foo';
    alert(selector);
  });
})(jQuery, Drupal, drupalSettings);

If the field formatter appears three times on a page, I would expect to get three alerts with three (slightly) different strings. Instead, I only get one, with the ID I expect for the first string.
It seems like the easy way to deal with this is to use inline scripts, but I know that's strongly discouraged. Is there a right way to do this?
Edit: updating the code to use drupalBehaviors, I now have:
(function ($) {
  Drupal.behaviors.galleryBehavior = {
    attach: function (context, settings) {
      $.each(settings.gallery.id, function(index, item) {
        alert(item);
      });
    }
  };
})(jQuery);

I'm now getting multiple alerts instead of one, but they still all contain the same string. Dumping the contents of settings.gallery shows that only one ID has been inserted into the array, which suggests to me that subsequent instances of the formatter aren't adding attachments? The PHP code looks like so:
$id = $items[0]->getEntity()->uuid() . '__' . $this->fieldDefinition->getName();
ksm($id); // just to make sure I'm actually generating the expected number of unique IDs
$elements['#attached']['drupalSettings']['gallery']['id'][] = $id;

This appears to be the right way to populate an attached drupalSettings array, based on one somewhat similar question I was able to find this morning, but clearly I'm missing something.

Thanks to responses from 4k4, the following works:
$id = $items[0]->getEntity()->uuid() . '__' . $this->fieldDefinition->getName();
$settings = [
  'id' => '#' . $id,
  'setting1' => 'foo',
  'setting2' => 'bar',
];
$elements['#attached']['drupalSettings']['gallery'][$id] = $settings;

And then in the javascript:
(function ($) {
  Drupal.behaviors.galleryBehavior = {
    attach: function (context, settings) {
      $.each(settings.gallery, function(key, item) {
        var main_selector = item.id + ' .gallery-main';
        alert(main_selector);
      });
    }
  };
})(jQuery);


How add tab menu item with external link to article node content I want to add an extra tab menu item to article node type.

I mean a new menu item beside view, edit and other tabs only in article node.

but this tab menu item has external link to another site and it's target is _blank (to open destination in new window)

what is your solution for my issue?

Create custom module  Replace mymdulename with your module name.
implement hook menu to add "Menu local task" which let your menu
item to show along with view, edit ..
page call back to add the
redirect rule, in below example I am redirecting to google.com, you
can add a check according to node and add redirection rule.
access callback ensures this menu tabs gets attached to nodes for article
content type.

  /**  * Implements hook_menu().  */

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

  $items['node/%node/movies'] = array(
    'title' => 'Movies',
    'page callback' => 'mymodulename_redirect',
    'page arguments' => array('node', 1),
    'access callback' => 'mymodulename_content_type_check',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );

  return $items;
}

/**
* Access callback
*/
function mymodulename_content_type_check($node) {
  if ($node->type != 'article') {
    return FALSE;
  }
  return TRUE;
}

function mymodulename_redirect($node) {
  dpm($node);
  $url = "http://www.google.com";
  drupal_goto($url, array('external' => TRUE));
}

Update

to open the external link in new tab use jquery to add '_blank' attribute
in your custom

jQuery('.tabs a').attr("target","_blank");

Remember to pick unique classes instead of ".tab" to avoid having this behaviour to all tabs.


How to hide the right and left regions from a customized login page? I'm working on Drupal 7, and trying to create one customized login page. I don't want to display the right and left regions in this page; I want a login page with only header, footer and content, where the content would be the "Username" and "Password" fields.

How can I do it?

Go to the Blocks admin page, admin/structure/block.

Find the regions you don't want to show. E.G., 'Sidebar A,' 'Sidebar B.'

'Configure' the blocks which appear in those regions. They will all have a 'Pages' tab at the bottom, and this is where you can configure which pages contain or exclude those blocks. You'd check 'All pages except those listed' and then put the path to your custom page.

HTH.


How can I switch language links to master links on a translated page? On my website currently only one content type gets translated and is therefore available in multiple languages. On this content type/page all the links (logo, menu, footer, etc.) refer to their language version of the current language.

E.g.: I'm currently on the french version of the page. The URL looks like this: "/fr/translated-node.html". Now all the links in the menu or footer look like this: "/fr/some-page.html".

But it shouldn't be like this. All the links on this page should always look like this: "/some-page.html". So without the language code at the beginning.

How can I achieve that programmatically?

Go to admin/config/regional/language/detection/url and then you must delete the path prefix for the language, you don't need code to do this.

And save the config.


Drupal 8 css and images relative to root I have the challenge that I want my site to be cache-able by and external varnish cache provider.

Most of my page gets cached nicely, but elements like the ico file, images and css are written with the full url in code and hence doesn't use the cached version.

www.domain.com points to internal.domain.com

When I go to www.domain.com the urls for the images looks like this

http://internal.domain.com/sites/default/files/styles/hero_full/public/hero/image.jpg?itok=WiCUbqbj

What I wanted was that it just wrote a url relative to the root of the site.

/sites/default/files/styles/hero_full/public/hero/image.jpg?itok=WiCUbqbj

The issue is the same with files included from the THEME.libraries.yml file.

Core actually did exactly that change just a few days ago, it will be like that in 8.0.3.

That said, your set up looks problematic to me, that's not going to be the only thing that somehow relies on the domain name. Usually the same domain is used?


LIghtbox2 hide header and footer regions I had created a lightbox which contains the node title and body content. But it shows the Admin bar of drupal , Header and Footer regions. I want to remove these from the lightbox and showing only the content of node on lightbox.

I am using Lightbox2 module for  this.

Not answering directly but proposing an alternative solution here:

If possible, switch to Colorbox, extend it with Colorbox Node and use it to easily display your nodes without header and footer like this:

My Example


How do I create dynamic routes where the changing part is at the beginning of the path? I need to create custom module routes like the following.

/ireland-dummy-page (IE)
/uk-dummy-page (UK)
/dummy-page (global)

How can I write the route paths for this scenario? Do I want to write separate ones or is there any way to make this dynamic?
my.calculator:
  path: "/{con}-dummy-page"
  defaults:
    _controller: '\Drupal\calculator\Controller\CalculatorController::CalculatorPage'
    _title: "Dummy test page"
  requirements:
    _permission: "access content"
  options:
    no_cache: "TRUE"

In your edit, {con} is a route parameter? This is not possible in Drupal, you can't start with a route parameter and /{con}/ has to fill an entire route segment.
Before you can match a route for such a path you have to do some path processing. See Do new routes require a static first portion?


How Do You Make a 'Rules Link' Work in a Custom Content Pane? I'm struggling to get a Rules Link set in a Custom Content Pane to trigger a Rules Link and work. I've done many tests and using the URL path provided by the Rules Link Edit page, (ie domain/content/post-new-content) all I get is a 404 despite my many trials and viewing/reading of info docs online.

Put simply, I want a link set on a Custom Content Pane to show a link which the user clicks, this will then trigger a Rules set to check: a) the user has valid auth/role; B) and then redirect to a Post page; if not authorised then redirect to a 'Subscription' page. Through my testing, a 'standard' link to an Add Content page works fine, so I presume it is something within the Rules/Rules Link  framework I working within the D7.2x

Can someone please provide some generalism how this (assumed simple flow) should work. HELP!

To render a Rules link programmatically use the following:

<?php
    print render(rules_link_render('RULES_LINK_NAME', $node->nid));
?>


Improving the "preview" of a node I know how to override the preview of a node being edited, but for some reason in the "trimmed" portion it displays a node's title and in the "full" version only the body. I'd like to be able to display the node's title in the "full" version also.

The theme method I'm overriding is theme_node_preview($variables).

I'm actually removing the "trimmed" portion completely, since it's not relevant to my content types. The method looks something like:

function theme_node_preview($variables) {
  $node = $variables['node'];

  $output = '
';

  $preview_trimmed_version = FALSE;

  $elements = node_view($node, 'full');
  $full = drupal_render($elements);

  $output .= $full;
  $output .= "
\n";

  return $output;
}

You could also try Page Preview, which shows a simulated full-page preview of a node:

  This module re-implements the Preview area of the node edit form as an
  IFRAME that renders and displays the full page view of your edited
  content as the anonymous user would see it, including elements such as
  blocks that display as a reaction to the page context.


Theme Organic Group Entity Reference on user profile On my site, users join groups via an Entity Reference field using the "Check boxes/radio buttons" widget.

The widget default is to display only the group Title. Like so (where the list bullet is a checkbox):

Group1Name
Group2Name
Group3Name

The group content type has an additional field called "description" that I'd like to include on this display. Like so:

Group1Name: Group1Description
Group2Name: Group2Description
Group3Name: Group3Description

Is there a way to theme either the checkbox widget or something in Organic Groups to display this additional field?

You need to create an entity reference view and use it for your og_groups_ref field. In Views where you click Add, you will see entity reference view next to block, page etc.

Create the view to show the groups and the add fields for title and description. Place description above title and exclude it from display.

Rewrite the title in field settings to something like [title] -[description]. The replacement patterns are in the view field settings.

Go back to your groups audience field settings (main settings, not widget) and choose entity reference view instead of organic groups or simple. Use the view you created.


How to include book traversal links on a custom twig template page I use the Book module to create books with chapters.
When I use the default twig template node.html.twig to display a book chapter, a section titled "Book traversal links" is included, with links to the previous chapter, the next chapter, and to the book. The debugger says these links come from the book-navigation.html.twig template.
Instead of the default template, I'm using a custom twig template node--chapter.html.twig to display chapters.

QUESTION:

How can I get the same book traversal links onto my custom page?

NOTES:

I checked for a block containing the book traversal links that I could just insert in my twig template, but I don't see one.
I have checked the $variables array in the twig template to see if maybe a list of the chapter's siblings is already there, but don't see one.
I'm already using HOOK_preprocess_node(&$variables) to find the book parent book's id, so I can use it to find the chapter's siblings, if that's the way to go.

Alas, there is no block for this; the book navigation links are hacked on to the node view in core.

From core/modules/book/book.module:

/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $book_node = Node::load($node->book['bid']);
      if (!$book_node->access()) {
        return;
      }
      $build['book_navigation'] = [
        '#theme' => 'book_navigation',
        '#book_link' => $node->book,
        '#weight' => 100,
        // The book navigation is a listing of Node entities, so associate its
        // list cache tag for correct invalidation.
        '#cache' => [
          'tags' => $node->getEntityType()->getListCacheTags(),
        ],
      ];
    }
  }
}

The good news is that this should work with custom templates as long as you are using the full view mode.

I have a custom node template and I still get the navigation links on my books at the bottom of the content.  (Unfortunately, whether I want them there or not-- as per the above code, they are forcibly added and there is no UI to control them.)


CSS class for view display not being applied I have a view set up with a block display. Its style is set to HTML list, which it does with no problem. But it doesn't seem to be applying the CSS class listed in the setup. What do I need to do to get this to apply?

Edited to add: Drupal 6, Views2

I said IF its D7 bc I could not find what version. I was reading it on my phone. But here's your Drupal 6 answer:

But here's the template suggestions for D6:
http://drupal.org/node/1089642

You can download devel module to get template suggestions as well.

-OR-

Download this module to add css classes to specific blocks:

http://drupal.org/project/block_class


How do I preserve GIF animation with the image field and image styles? Currently, when I upload animated GIFs to image fields, image styles breaks the animation as part of the crop/resize sequence.

I'd love to be able to preserve animation while also taking advantage of image styles. Is there a way to achieve this?

It is possible, there already is some discussion:

Pure PHP with imageMagick - https://stackoverflow.com/questions/718491/resize-animated-gif-file-without-destroying-animation
Drupal discussion - https://drupal.org/node/1115658
Issue for ImageMagick module with patch - https://drupal.org/node/1802534 - several users claim that it is working.


How to theme multiple entities on the same page? I am trying to write a module that displays several entities in one page, but I don't see how I should theme them.

I've found (an mostly followed) this: https://drupal.org/node/1238606.

But the point where I get stuck is the return value of the page callback. The link above suggests:

function my_entity_page_view($entity, $view_mode='full') {
  $entity_type = $entity->entityType();
  $entity_id = entity_id($entity_type, $entity);

  $entity->content = array();
  $entity->title = filter_xss($entity->title);

  field_attach_prepare_view($entity_type, array($entity_id => $entity), $view_mode);
  entity_prepare_view($entity_type, array($entity_id => $entity));
  $entity->content += field_attach_view($entity_type, $entity, $view_mode);

  $entity->content += array(
    '#theme'     => $entity_type,
    '#element'   => $entity,
    '#view_mode' => $view_mode,
    '#language'  => LANGUAGE_NONE,
  );
  return $entity->content;
}

I however try to load several entities at once and have no fields, so I tried this:

$entities = // Array of entities keyed by id;

entity_prepare_view('entity_type', $entities);

$return = array(
  '#theme'     => 'entity_type',
  '#element'   => $entities,
  '#view_mode' => 'full',
  '#language'  => LANGUAGE_NONE,
);

return $return;

Since entity_prepare_view() accepts an array of entities, I'd suppose there should be a way to theme several entities at once as well. Or am I wrong?

After a bit more fiddling, this worked for me. I've tried a similar approach earlier, but I guess there was something wrong. I've commented out the field functions, but these are the places in case you need them.

$entities = // Array of entities keyed by id;

// Prepare all entities at once. Attach fields if desired.
//field_attach_prepare_view('entity_type', $entities, 'full');
entity_prepare_view('entity_type', $entities);

// Expose all entities individual to hook_theme.
foreach($entities as $key => $entity) {
  $entity->content = array();
  //$entity->content += field_attach_view('entity_type', $entity, 'full');
  $entity->content += array(
    '#theme'     => 'entity_type',
    '#element'   => $entity,
    '#view_mode' => 'full',
    '#language'  => LANGUAGE_NONE,
  );
  $entities[$key] = $entity->content;
}

return $entities;


How do I add updated timestamp to a file url to ensure people download the latest version? I'd like to add the last updated timestamp to the uploaded file name e.g. my.pdf?ver=123413414

The file is uploaded on a regular basis and I'd like people to access the latest version.

I can't see a module/formatter to do this.

I can write
- javascript to add the timestamp to the end but the file would never be cached.
- write a file formatter that adds the last updated timestamp to the end of the download link.
- write something that calls "theme_file_link"

what is the best approach?

Thanks

The best approach would be to actually rename the file both on the file system and the database and incorporate the upload time in file name.

Appending time after the question mark in URL would have purely informative purpose. And if that's what you want then create a custom module and place the following code in it:

function my_custom_module_node_view_alter(&$build) {
  if (isset($build['field_file'])) {
    $time = gmdate("Y-m-d:H:i", $build['field_file'][0]['#file']->timestamp);
    $build['field_file'][0]['#file']->filename = $build['field_file'][0]['#file']->filename.'?'.$time;
  }
}

If you have multiple files per node then use the following code instead:

function my_custom_module_node_view_alter(&$build) {
 if (isset($build['field_file'])) {
    foreach ($build['field_file'] as $key => $file) {
      if (is_numeric($key)) {
        $time = gmdate("Y-m-d:H:i", $file['#file']->timestamp);
        $build['field_file'][$key]['#file']->filename = $build['field_file'][$key]['#file']->filename.'?'.$time;
      }
    }
  }
}


Create a list and count of users per role Using Drupal 7 I would like to display:

A) a list of recent users per role (Limit to 10).

and

B) a total count of users per role.

I have looked for a module to do this but can't find anything. I also tried a few things in views but had no luck. This is what I tried in views:

  enable aggregation for you view, and then set the group by for you field (Content:nid for example) to Count.

Didn't give me the results I was looking for.

If there is a module that can do this that would be perfect otherwise i'm hoping to use views... lastly I guess it could be posible with PHP.

I'm going to assume Part A is the easy part, but just to be thorough:

Create a new view based on the Users table
Add the User: Name field (if it isn't already there)
Limit the results to 10
Sort by descending

As for Part B, let's begin by dissecting why Aggregation will not work right out of the box with Views 3.

The only reasonable base table that we could use to count user roles is the Users table, right? After all, Views gives us a User: Roles field right away. So, we turn on Aggregation on two copies of the User: Roles field (the first to group the results, and the second to COUNT the results). However, if you take a look at the SQL, the query is:

SELECT users.uid AS uid, COUNT(users_roles.rid) AS users_roles_rid
FROM {users} users
LEFT JOIN {users_roles} users_roles ON users.uid = users_roles.uid
GROUP BY uid

So, the query will:

SELECT a uid and then COUNT the roles that particular uid possesses
Perform a LEFT JOIN by comparing two uids from the users table and the users_roles table (not very helpful)

It turns out that the COUNT does its job correctly by counting up the roles each user has... but it is not what we need. Since we chose User as the base table, the COUNT is only counting the number of roles. What we actually need is to COUNT how many users belong to each role. The users_roles table will provide us the necessary information.

Here is the SQL we're after:

SELECT role.name, COUNT(users_roles.uid) AS users_per_role
FROM users_roles AS users_roles
INNER JOIN role AS role ON role.rid = users_roles.rid
GROUP BY role.name

The above query will give you a list of all of the roles in your site along with a count. Since users_roles is not an available base table out of the box, we cannot construct this query via Views without some PHP customization.

There are a few options to get the required results:

Use the Views API to describe users_roles to Views. This requires a bit of PHP heavy lifting. Check out this answer for more information. The Data module may be of use as well.
Cheat and run the above query through db_query and stick the results in $view->attachment_after.

Here is an example of the latter, using hook_views_pre_render in a custom module (be sure to clear caches first to get this hook to work):

function mymodule_views_pre_render(&$view) {
  switch($view->name) {
    case 'my-view-name':
      $results = db_query('
        SELECT role.name, COUNT(users_roles.uid) AS users_per_role
        FROM users_roles AS users_roles
        INNER JOIN role AS role ON role.rid = users_roles.rid
        GROUP BY role.name
      ')->fetchAll();

      foreach($results as $result) {
        $rows[] = array($result->name, $result->users_per_role);
      }

      $view->attachment_after = theme('table',
        array(
          'header' => array('Role', 'Number of Users'),
          'rows' => $rows,
        )
      );
      break;
  }
}

Lastly, keep in mind that a user may have multiple roles. So, it would be incorrect to sum up all of the "Users Per Role" values and say that the result is your total number of users.


Varnish cache not region aware We have a Drupal 7 site whose content is split into geographic regions. The concept is that page view blocks and filters will display region specific content based on the users IP address or selection of their country, the page URL is the same throughout.
The issue we now have is that Drupal cache and Varnish cache are not regionally aware in that the cache is built up by the first visit upon start and clearing of cache so the wrong content gets displayed to a user who wishes to view content for his region, because someone before him opened the same page from another region. Any ideas?

Possible solution of separating your caches, by regions, in Varnish is to use GeoIP VMOD: https://github.com/lampeh/libvmod-geoip

Simple example:

put country code to hash

sub vcl_hash {
        hash_data(req.url);

        if (req.http.host) {
                hash_data(req.http.host);
        }
        else {
                hash_data(server.ip);
        }

        # separate caches by countries
        hash_data(geoip.client_country_code());

        return (hash);
}

Now caches for different countries will be different.
Of course, you still need to take care about page generation in Drupal, it should provide different content for different regions too.


hook_form_form_id_alter doesn't save data by default I use hook_form_form_id_alter() to edit the user_form. I'm creating some checkboxes and textfields. Thats working fine. I also can output the values, when clicking the submit button.

But it doesn't save the values by default.

How do I save my values?

hook_form_form_id_alter only alters the form object for presentation / behavioral changes on existing forms. It doesn't alter processing or storage for existing forms.

For that you'll need to add a custom submission handler, or use the Form UI to create new custom user fields if you don't need custom processing/storage needs.


Do Fields Slow Down Drupal Whenever I'm trying to edit or create a content type, it always takes quite a while to load the page. Is it because I have too many existing fields and Node Autotitle is pulling all of them and slow Drupal down?

If you have Tokens module enabled and also if you have a lot of fields, then it'll take a lot of time for the token ui to load up. This was the problem in my site. It took me a long time to figure this out. If there is a performance hit, only when you try to edit or create a content type then it might be caused by the tokens module. It's worth checking it out.


how can i change new password/confirm password by using services module in drupal I am using services module to consume users account details.

Enabled user in admin->services->resources.

URL: https://drupal.com/service/user/23

method : post

request body:
{
"current_pass":"xyz"
"email":"xyz@gmail.com"
}

I have updated these two values are successfully,
but how can I change new password and confirm password values.

How to take these values in request body and I have tried like this(new_pass) but failed to update.

Please help me.

https://drupal.com/servics/user/9

where 9 is User ID

Method : PUT

Pass 'X-CSRF-Token' paramerter with user token value in header.

Example Call :

{"uid":"9","current_pass":"guessusername1","pass":"guessusername1xxx","pass1":"guessusername1xxx"}


Is there a way to let every user can choose (e.g. on registration) whether their field is private or public? I have an address field for every user on my website. Now, not everyone is happy with having his address visible to other users. I'm currently using field_permissions to control the visibility of the single fields. Is it possible to let the user decide which visibility he chooses (without code)?

If you want to do this without writing any custom code, you could use Panels.

Create a boolean field, Show my address publicly, and add it to the user profile.

Then override the user profile display with Panels.  Add all of the fields that you want to display, including the address field.  Then, add a Visibility rule to the address field and set the condition to be Show my address publicly == TRUE.

This is a bit complicated to set up if toggling the display of the address is all you want to do, but Panels offers a lot of flexibility (without writing code) that could be used for other things, too.


Taxonomy Term Block View Show Nodes For All Terms in Node? Hello i achived this once but for some reason i am having a problem with it this time.

Using D6 and Views 3. I have a block view for random videos.

Taxonomy Term ID from URL
Load default argument from node page,
Validator: taxonomy term
Argument Type - Term id's by , or +

Iv checked and unchecked both-

Allow multiple terms per argument

and

Allow multiple arguments to work together

without much success. The desired output would be on a node tagged with 'science' and 'spirituality' the block view would show nodes that are either tagged 'science' or 'spirituality'. At the moment i seem to be getting no results or only nodes tagged with both 'science + spirituality'.

Does anyone know the correct settings for me to show nodes with any of the node's tags?

Thanks

I am not sure for d6, but in d7 you can do it like this(i believe it can be done same way in d6)

In Contextual filters(your Arguments) you need to add Nid like you did, after add new argument has taxonomy term ID and in WHEN THE FILTER VALUE IS NOT AVAILABLE -> provide default value chose not content from URL but PHP code and do this:

You need to load node and get your taxonomy terms from field.

 $node = node_load(arg(1));
  if($node) {
  $field = field_get_items('node', $node, 'field_YOURFIELDNAME');
  if($field) {
      foreach($node->field_YOURFIELDNAME[LANGUAGE_NONE] as $term) { $terms[] =  $term['tid'];          }
    return implode('+',$terms);
  }
}
  else { return; }

it will return tids of selected taxonomy terms. But its a d7 way with Views 3.


Save user selection after search in views I am facing a problem with views. Is it possible somehow to save the user selection when a user is doing a search?

To get it clearer, I'm having a list of users. Let's say, I am searching for customer A via filters, then select the found customer, change my filter to find customer B and select him to. But every search, resets my selection. I'm looking for a possibility to save the selection and have A and B selected in the end.

Go to your views >> Exposed filter settings and check Remember the last selection checkbox

If you want to go further then try the Views Saved Searches module

This module allows you to save your current configuration of exposed filters for later use. This can be especially useful for Views with a lot of exposed filters.
Whenever a View is changed, all saved searches for that View are deleted, to prevent corruption. If the user has JavaScript enabled, the saving and deleting process happens through AHAH, and the new section is displayed below the exposed filters section. When JavaScript is disabled, the new section is displayed above the exposed filters section.


menu-mini panels: removing anchor tag from menu item I've used the menu-minipanel module to set-up some mega menus. The main menu items are set (using the module UI) to show a minipanel with my various menu blocks/nodes.

However I don't want the 1st level menu items themselves to point anywhere, and since I've used the Menu Minipanel option to allow for a click to reveal the minipanel I was forced to use the Special Menu Items module to generate a "#" as an href.

However the problem I'm having now is that when the user clicks on the menu items to open the megamenu, the '#' href takes them to the top of the page.

Can anyone suggest any options here?

Here's the site I'm working on presently as reference.

You can use some jquery here, by capturing click event of this menu item, and returning false.

$("<selector>").click(function(){
   return false;
});

Or try this

$("<selector>").click(function(e){
   e.preventDefault();
});


How do I programmatically find the core version? How do I programmatically find the Drupal core version running a site?

I found this example in MetatagNodeTranslationTest.

To find the drupal version in your code,

\Drupal::VERSION

will return it.

If you need to compare

if (floatval(\Drupal::VERSION) <= 8.3) {
  // do some stuff.
}


Retrospective fix to hook_update_n() in current release I need to make a correction to a hook_update_N() function in the .install file which is causing SQL constraint errors when some users upgrade to the new release version. The original worked fine providing they ran update.php manually right after upgrading. But some users started using the site before running update.php and then when the did run it they get SQL errors. Also some automated upgrade scripts get the error. In both cases the required update is not performed.

Backgorund details are in issue https://www.drupal.org/node/2706119

The correction is done and ready, but I do not necessarily want to make another release, as it was only three months ago for the last release. 18k users have upgraded but 34k have not yet, so it would be good if the fixed update_n() function could somehow be added into the current release. Is that possible? Can git tag the new commit into current version and then I re-release it again?

You can reset the status of the hook_update_n from below query
update system set schema_version=0 where name='modulename(hook)';

Then you can run update.php so this hook_update_n() will work again with your latest changes.

Also you can see this link for schema_version values system_schema() why we have to set schema_version '0' instead of '-1'.

you can use following drush module for roll back the update version in the system table. Called "uroll" for update rollback.

https://github.com/danshumaker/drush-uroll

Usage: drush uroll --module=mycustommodule --version=5

This combined with a database backup reload script allows you to rinse and repeat when writing update functions


Listing first name, last name at Users listing page I have installed and configured User Profile module, which allows me to add fields like First Name, Last Name for users.

As of now, when I go to users list at /admin/user/user I see username column. How can I can add these extra fields in the column?

I suggest using Administration views module which will replace all administration overviews, e.g. the list of users, with actual views. You will then be able to add any field you have attached to user profiles to your overview as well. This will work for both Drupal 6 and 7.


Only show result when the author has a relation with the current user You might already suspected it, I'm talking about groups. I've a content type what represents groups, the node/group is referred in a field (field_group) on the user entity. With this relation I want to define "permissions" in views.

For example the blog I build now displays content of all groups, no matter what group you are in, the view will always display all blog nodes. Now I want only to display the nodes what have an author with a field_group value equal to the currently logged in user its field_group value.

How should I do this in views? Some people mentioned to use contextual filters, I tried some common options but it didn't resulted like expected...

Please, let me know if you know a working setup.

Thanks ~ F.

Found out how it should be done if you can refer to an author.

My setup:

add relation ship Content : Author as "author"
add relation ship User: Group (field_group) - Appears in: user:user. with the relation to "author".
add contextual filter User: Group (field_group) - Appears in: user:user. with at "When the filter value is NOT available" -> "Provide default value" -> "PHP Code" the following code:
global $user;
$data = user_load($user->uid, TRUE);
return $data->field_group['und'][0]['nid'];


Which module supports select or other option for Term reference type? Is there any module to support select or other option for Term reference type?

I tried with the Select (or other) module but its not working in Term reference type

There is a sandbox module available that adds this functionality:
https://drupal.org/sandbox/cameronbprince/1895832

Also there is an issue in the issue queue to incorporate this into the module itself: https://drupal.org/node/1716764

Alternatively, the hierarchical_select module also provides the option to let users add new terms to vocabularies on the node edit form.


open node-reference links title in popup I want in my node view pages, node reference links open in popup window or lightbox window.
Does anyone have a solution?

You can use a theme_preprocess() function to add attributes to that link, or you can create a custom field template that adds classes or specifies a target.

For a new window/tab, you'd add target="_blank" or if you want to use an overlay you would add classes as specified in the module that provides that functionality, such as Lightbox or Colorbox.


How to get latitude and longitude from user with Form API I want to create a database-driven website with Drupal 6 to gather some information from users that is related to the location; I want to create a form (and I don't want to use Webforms, or CCK) to get some data from users, and to get coordinates by creating a point on a map (by Openlayers or Gmap API), and then saving those data in a database table. I also want to integrate it with Views module so i can make a query from data.

I'm quite happy with the Geolocation Field module for Drupal 7. It allows you to put a field on any entity (user or node or whatever) that uses a map. It also has an html5 module to collect the information. Great stuff, actively maintained.


Let the site administrator edit content at page I'm using views (outputing fields) to display the content of a page and that's working fine for the end user (the visitors). I have 2 questions about the administration for this page.

Is it possible to let the administrators edit the content type(s) within the view from the page that´s being displayed? Like the way you do when you edit articles (click edit in the right corner)? Views can do that when you list content but not fields? See my screenshot where i try to explain it.

2.Is it possible to organize the content (and the different content types) in a structured an hierachial order that's meaningful for the site administrators? For example I would love to first list the page on level 1 and then display the different content types below the page on level 2. See my second screenshot where I try to explain this.

It is not clear what you want to edit - content types (page, article, blog etc.) or nodes? If you want to edit particular nodes in a view which outputs fields, core Contextual filters module have views implementation so you can choose Global: Contextual links as a field. You can even configure which links to display as contextual links.
Check out Views Bulk Operations and Administration Views as they allow you to alter the admin interface using views.


Error when creating custom form I am trying to create a custom form in drupal 8. for that I created my custom module called hello , and i've put inside the hello.routing.yml file the folllowing route:
hello.my_special_form:
  path: '/my-form'
  defaults:
    _title: 'My new form'
    _form: '\Drupal\hello\Form\Test.php'
  requirements:
    _permission: 'access content'

Inside Test.php ,
I have only written :
<?php
/**
 * @file
 * Contains \Drupal\hello\Form\Test.
 */
   namespace Drupal\hello\Form;
   use Drupal\Core\Form\FormBase;
   use Drupal\Core\Form\FormStateInterface;
   class Test extends FormBase {

}

I have no errors in my recent log messages, but when I clear cache , the website crashes.I have no idea why specially that I have not written anything yet.
Debugging: If I comment all the Test.php file, the clear cache works fine ! In addition to that, If I only comment the class Test extends FormBase line , the clear cache works as well. so the problem is in the class declaration. Any idea why?

FormBase is abstract; it implements FormInterface, but doesn't contain methods for:

getFormId
buildForm
submitForm

You need to provide those in your class or PHP will reject it.
...
class Test extends FormBase {

  public function getFormId() {
    return 'foo';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    // Build form then
    return $form;
  }

  public function submitForm(array $form, FormStateInterface $form_state) {
    // Perform submission tasks
  }

}


Commerce doesn't handle Sagepay Form Integration return So I'm using SagePay Form Integration on my site, but it has ceased to function correctly.

So on the Payment Stage of Checkout it says 'Use the button below to proceed to the payment server.'. Now I successfully complete a payment on the Sage Pay Testing Server and it comes back to the site URL checkout/order_id/payment/return attached with some GET vars.

The issue is that when it returns, checkout just displays 'Use the button below to proceed to the payment server.' again. The status of the order hasn't been updated and the user isn't ushered to the complete stage. Any idea why this is?

After further inspection it also seems that under Store > Orders it isn't logging the payment as it had previous. The order just remains at the payment stage in 'Shopping Carts'
tab of Admin > Store > Orders.

I'm having this exact same issue with all of the following versions:

7.x-1.0-beta2
7.x-1.0-beta1
7.x-1.x-dev

Your help would be greatly appreciated!

Turns out that Firebug Lite script in html.tpl.php was causing the issue:

<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>

Swiftly removed.


How to get only field value in View template How can I access/print the raw value of a date field? (or any field for that matter). I am working in a View template and I typically use $fields['field_myfield']->content. But that gives me the HTML not just the value.

My template.php file:

 function mytheme_preprocess_views_view_fields(&$variables)
{
    $view = $variables['view'];
    if($view->name == "news_main_list")
    {
          $variables['news_date'] = $variables['fields']['field_news_date_text']->content;
          $variables['news_type'] = $variables['fields']['field_news_type']->content;
          $variables['theme_hook_suggestions'][]='views_view_fields__news_main_list__block_1';
     }
 }

My views-view-fields--news-main-list--block-1.tpl.php file:

  <?php if (!empty($field->separator)): ?>
<?php print $field->separator; ?>

  <?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>

<?php print $fields['title']->content; ?>

    <?php print $news_date; ?> | <?php print $news_type; ?>
    <?php if ($news_type == "event") : ?>
        <?php print 'hello'; ?>
    <?php endif; ?>

  <?php print $field->wrapper_suffix; ?>

You must specify which one of Views template files you are working on, If it is views-view-fields.tpl.php then $fields variable is availabe but if it is not views-view-fields.tpl.php then $view object is available. use kpr($variable) to get the $variable available properties.

You can also use hook_preprocess_views_view_fields(&$var) to set the values of fields in $var array then retrieve them in fields template file

UPDATE:

First define the following function in your template.php file

    function THEME_preprocess_views_view_fields(&$variables)
    {
        $view = $variables['view'];
        if($view->name == "THE_VIEW_NAME")
        {
              $variables['my_field'] =strip_tags( $variables['fields']['field_myfield']->content);
              $variables['title'] =strip_tags( $variables['fields']['title']->content);
              $variables['theme_hook_suggestions'][]='views_view_fields__SOMETHING';
         }
     }

By this function the $my_field and $title variables are available in the views-view-fields--SOMETHING.tpl.php file. You have to create views-view-fields--SOMETHING.tpl.php file in your theme directory and use above variables in it. views-view-fields--SOMETHING.tpl.php file is created to theme every output (record or row of columns) of your View. Make sure you are using - instead of _ when creating views-view-fields--SOMETHING.tpl.php file.

$view variable is a variable that contains every detail of the current View. you can use kpr($view) to see its results.


PHP Parse error: syntax error, unexpected T_FUNCTION in redhen_activity.module on line 608 After migrating from dev to prod on Bluehost when I run update.php I get a 500 error and I get the below error in error in error_log.

  PHP Parse error: syntax error, unexpected T_FUNCTION in
  redhen_activity.module on line 608

This is D7 with the latest update to the Open Outreach Distribution. The odd thing is that my dev site (running as a subdomain) works just fine.

I think you're using PHP 5.2 or earlier, which doesn't support closures. You can find out which version of PHP you're using  phpinfo().

Lindly upgrade to PHP 5.3+, or use create_function, or write a static function and pass it as a callback.


How to use the uc_csv module for getting reports I am using the ubercart module for purchasing products. I want to export the order records/history as csv file and view it in spreadsheet. So I searched and got the uc_csv module. I have installed the module for Drupal 7. When I click the csv export link from store administration option it shows:

  "THERE ARE CURRENTLY NO CONFIGURED EXPORT REPORTS".

How can I configure this option? Please suggest some ideas.

you can create export reports by clicking the "CSV Export" menu item located under "Store administration" in the Drupal administrative menu system.

You can create any number of reports to export certain criteria. More granular criteria can be programmed later if there is demand for such a feature. Please provide feedback if this is the case.


How to check if filefield has a value or not by Rules I have a cck file field "pic" users can attach up to 3 images to. I would like to set a Rule with the condition depending on whether user has uploaded at least one image or not.

I set the condition "Saved content's field 'field_pic' has value" + "negate"  But no matter the field has a value or not (a file has been attached or not) the debug says "Condition "Updated content's field 'field_pic' has value" evaluated to FALSE."

I also tried this code below but again always the condition is FALSE.

return array(
  0 => array('fid' => 0, ),
);

How can I set the condition to check if the cck file field has at least one file or not?

I believe that "has value" needs to return TRUE or FALSE. You need to do the assessment yourself, because the value that it should have might not necessarily be a one or a zero (I would use this rule if I wanted to evaluate if a field has the value of 5, say: If yes, return true.)

You can either put in a value in the text input (5) which it will match for you and return true/false, or you can use PHP to evaluate it and return true or false yourself.


Pass a webform value to a node via Rules? I have a rule that is successfully creating a node of a content type when a webform is submitted. How do I pass a value from the webform into the created node via rules? (This is a Drupal 7 site.)

Create Hidden inputs in webform.
Assign to this hidden inputs values (prepopulated in url, tokens, webform rules or programmatically).
Assign these inputs to content fields using Rules.


Automatic alias overriding manual alias on each edit Does anyone have an issue with Automatic alias, where the setting keeps turning back to auto on each edit of a node?

What we would like to achieve is

a) some node paths should be generated automatically from the title and remain automatically managed

b) for other paths we want to override the alias

The problem is only with b, where after any edit to the node the alias behavior reverts back to a.

How to get desired behavior?

Go to admin/build/path/pathauto on your site, open the 'General settings' fieldset and select 'Do nothing. Leave the old alias intact.' as update action. That should be all.


How can I get hold of the Composer object? I'm trying to get the file location of something in an installed package.
https://stackoverflow.com/questions/15714809/get-filesystem-path-of-installed-composer-package says I can get that from the Composer object.
But in Drupal, how do I get the Composer object?

Usually, I'm doing this using ReflectionClass.
Take this example: to load the cacert file which comes inside one of composer packages:

First, locate any class in that package using ReflectionClass.
Secondly, get the package path using dirname bypassing the file name.

Code example:
// Load certificate file.
$reflection = new \ReflectionClass(\GSRequest::class);
$packagePath = dirname($reflection->getFileName());
$gsRequest::setCAFile(realpath($packagePath . '/cacert.pem'));


How do I make the exposed filter values available as tokens for text areas How do I display (or render in twig) the search term, entered in the search field. When you enter a search term and click on the search button, you will go to the search results page (view).

In the header of that view I want to display something like:

  Your search of [mysearcherm] has x number of results.

I build the search field with a views exposed form and Search API.

Update:
In the textarea of the views header I want to insert the search term as replacement token, but it's not available?

You can show the relevant search term in Text area when you add it to the Header option in Views.

When you tick the Use replacement tokens from the first row option you will see the Replacement patterns tokens available, and below that global replacement tokens.

You can use something like:

<div class="messages messages--status">Your search of {{ name }} has [view:total-rows] result(s). </div>

Although you'll probably want to take care of plurals more intelligently and also use a twig conditional to not show anything if the Exposed form isn't used.


How to use _user_mail_notify with a defined language as the title say, I would like to know how to use _user_mail_notify with a specified language.

According to the documentation the third parameter should be the one that override user_preferred_language() but when I specify it the language used is always the one returned by language_default().

My code is pretty simple:

_user_mail_notify($op, $account, $mail_lang);

Where:

$op is 'register_admin_created' as the account is created programmatically.
$account is the return value of user_save
$mail_lang is an object selected from the array returned by language_list('enabled') (as I understood it should be).

I don't know if I'm using it wrong or there is a bug in the function, anyone used it with a custom language and can help me understand?

Thanks you.

I finally understood and overcome the issue, in order to send emails in a different (enabled) language multilingual features must be enabled for the emails.

To enable the multilingual features there are just few steps:

The module "User mail translation" has to be enabled
From the Variable configuration (admin/config/regional/i18n/variable) you have to select the tab "User emails" and then check the email types you want available in a different language
From the account setting page (admin/config/people/accounts) then you select the language (in the very first box of the page) and add the translation for the related email templates (just scroll down)

After this 3 steps you will be able to send emails in all the enabled (and translated) languages in your site.


how to overwrite the search box? <div class="fr_search">
  <form action="/"  accept-charset="UTF-8" method="post" id="search-theme-form">
    <input  name="search_theme_form" id="edit-search-theme-form-1" size="15" value="" class="form-text" />
    <!-- … -->
  </form>
 </div>

The above code is generated by the Drupal Search module. I want to add this code to the form.

<select class="search_l" onchange="selectSearch(select)">
  <option value="0">whole site search</option>
  <option value="1">google search</option>
</select>

How do I do this?

I would rather implement hook_form_FORM_ID_alter() to alter the form returned by search_box(). If mymodule.module is the name of your module, then you should add the function mymodule_form_search_box_alter(&$form, &$form_state). You need also to replace the form submission handler with your own.

function mymodule_form_search_box_alter(&$form, &$form_state) {
  $form['submit']['#weight'] = 10;

  $form['search_type'] = array(
    '#type' => 'radios',
    '#options' => array(t('Whole site search'), t('Google search')),
    '#default_value' => 1,
    '#weight' => 5,
  );

  // Replace the search.module handler with your own.
  if (in_array('search_box_form_submit', $form['#submit'])) {
    $key = array_search('search_box_form_submit', $form['#submit']);
    unset($form['#submit'][$key]);
  }
  array_unshift($form['#submit'], 'mymodule_search_box_submit');
}

You could also show the form field containing the text to search inline with the radios you add.
The code I reported replaces the form submission handler with mymodule_search_box_submit() that must be implemented from your own module. This is the code executed from the submission handler implemented by search.module; I report it as reference.

function search_box_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_REQUEST['destination'])) {
    unset($_REQUEST['destination']);
  }
  if (isset($_REQUEST['edit']['destination'])) {
    unset($_REQUEST['edit']['destination']);
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/node/' . trim($form_state['values'][$form_id]);
}

As reference, I report here the code of the search.module function that builds the search box form.

function search_box(&$form_state, $form_id) {
  $form[$form_id] = array(
    '#title' => t('Search this site'),
    '#type' => 'textfield',
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );
  $form['#submit'][] = 'search_box_form_submit';

  return $form;
}


node_save() casing 500 Internal Server Error - 48s when using with AJAX global $user;
$node = node_load($_POST['expire_offer']);
$node->field_status['und'][0]['value']=0;
$node->field_expire_date['und'][0]['value']=time();
$node->revision = TRUE;
$node->uid = $user->uid;
$node->log = 'This offer expired from rate manager expire ' . date('m-j-Y');

node_save($node);

When I remove node_save($node); it loads properly.

Sorry, I don't have enough reputation points to comment so I should post this as an answer.
Obviously your 500 error comes from the script. The node_save($node); does not cause your error, it's just the trigger.
If you want to follow the best coding practices, you should use try and catch blocks to catch your errors before you try to modify your database.
If the "dblog" module is activated you could follow the error stack to debug your script or else you could comment out all of the lines that are assigning new values to your variables and start re-executing your script by uncommenting one line at the time utill the error is reproduced.
I hope that this helps a bit. We have all been there. Cheers.