Set new theme setting to default on theme update

From what I can tell, themes do not process update hooks since they do not have a schema value tracked in the key_value table. So a hook_update_N is not possible in this case.

This means that you have a couple of options.

Option 1

If the theme is going to be updated in code, but not updated right away through the UI form, you will probably want run a drush command as part of the theme update.

drush config-set THEME.settings NEW_SETTING NEW_SETTING_VALUE'

Reference: https://drushcommands.com/drush-8x/config/config-set/

This will allow you to set it once and then any future updates/overrides can be handled as usual through the configuration system.

Option 2

If you are talking about a theme that is part of a distribution, and you don't have access to the system to run the drush command, then you could set a default value on the hook_form_system_theme_settings_alter function. This would not provide the value to the system when it loads the config, but it would provide a default to users when they update the theme and save the settings form.

If you did it that way, you would need to provide a fallback in your theme for if/when that value is not present to prevent unexpected behavior if the new setting value isn't yet set in the site's settings file.

Option 3

If you have access to the codebases for the affected systems, like in a site factory, then you could technically provide the new value in the exported configuration file itself and then it would be picked up upon config import.


How to flag a View's item (with AJAX) when hovering or clicking it?

The entire process may seem a little complicated at first, but it's easy once we break it down into smaller parts and understand how it all comes together.

Basically we have two parts which we need to address. Firstly the "backend" logic where we will be implementing hook_menu, allowing us to receive an AJAX request via a custom menu route and then flag our Message as seen. Then secondly the "frontend" logic where we'll be implementing a little bit of jQuery to trigger our AJAX calls (using the proper Drupal.behaviours way of course) :)

With this example I'm assuming you have created a Message entity and have added a boolen field to it. We'll use this to store our flag to indicate whether the Message has been "seen" or not.

Once you've done that, go ahead and create a simple custom module and implement hook_menu using the following example:

/**
* Implements hook_menu().
*/
function my_example_menu() {
  $items['my_example/message/seen/%'] = array(
  'page callback' => 'my_example_flag_message',
  'page arguments' => array(3),
  'access callback' => 'my_example_message_access',
  'access arguments' => array(3),
  'type' => MENU_CALLBACK,
  );
  return $items;
}

Now before we start writing the page callback function which will flag our message as seen, we need to make sure that we implement proper access rights. This ensures the user accessing our custom menu route actually "owns" the message, and isn't some malicious hacker trying to annoy us and mark all the messages on your system as "seen" as some kind of lame prank haha! See below:

/**
 *  Access callback to ensure user has the right to message entity
 */
function my_example_message_access($msg_id) {

  global $user;

  $access = TRUE;

  //if anonymous user then throw access denied
  if(!$user->uid) {
    return FALSE;
  }

  //load our message entity and check the uid
  $msg = entity_load('message', array($msg_id));

  if($msg[$msg_id]->uid != $user->uid) {
    return FALSE;
  }

  return $access;
}

You can test the access callback by visiting http://example.com/my_example/message/seen/[MESSAGE_ID] and trying out different message id's logged in as different users. If a message doesn't belong to you, Drupal should be giving you the old "Access Denied" message.

Now that we know our AJAX route is protected by Drupal access control, we can go ahead and write the page callback function which will flag our Message entity as "seen":

//page callback function
function my_example_flag_message($msg_id){

  $response = array('success' => FALSE);

  //first check that the message id argument is present
  if(!isset($msg_id) || $msg_id == 0){
    return drupal_json_output($response);
    drupal_exit();
  }

  //load our message entity
  $msg = entity_load('message', array($msg_id));

  //set the flag to TRUE
  $msg[$msg_id]->field_YOUR_FIELD_MACHINE_NAME[LANGUAGE_NONE][0]['value'] = 1;

  //save our message entity
  if(entity_save('message', $msg[$msg_id])){
    $response['success'] = TRUE;
  }else{
    $response['success'] = FALSE;
  }

  //return the status of our attempt at saving our entity back to the front end
  return drupal_json_output($response);
  drupal_exit();
}

Great so if you made it this far and didn't fall asleep reading that wall of text, then you should now have a working route which accepts a message id, and marks that message as "seen" (as long as it belongs to you). :)

Then our final piece of the puzzle is attaching a Drupal behaviour to each View row, enabled as to fire an AJAX call to our Drupal route and trigger our backend logic. I'm assuming you know some basic jQuery, but here's the example script you'll need to add to your page using the drupal_add_js() function or something similar. We'll call it my_example.js:

(function ($) {
  Drupal.behaviors.my_example = {
    attach: function(context, settings) {
      //you can adjust this jQuery selector to anything you like
      $('.view-row').click(function(e){
        //I'm assuming the message ID is in view row markup as a data attribe (eg: data-message-id="[MID]")
        var msgID = $(this).data('message-id');
        //trigger our jQuery AJAX call
        $.ajax({
          type: 'POST',
          url: '/my_example/message/seen/' + msgID,
          dataType: 'json',
          data: 'seen=1', //added some arb param here as an example
          beforeSend: function(){
            //if you want to do anything fancy before the AJAX call do it here
          },
          success: function(response){
            //if we successfully updated the message
            if(response.success == true){
              //do something fancy like display a message if you like
            }else{
              //if the update failed display an error message
            }
          },
          error: function(jqXHR, textStatus, errorThrown) {
            //if there was some kind of javascript / jquery error you can debug it here
          }
        });
      });
    }
  }
})(jQuery);

And hey presto, we now have some jQuery attaching our Drupal behaviour to each View row which when clicked, will fire off our AJAX trigger and then get Drupal to update your message.

This design pattern opened up a whole host of other ideas (think AngularJS and other exciting geeky tech) for my use of Drupal. I hope it helps you too :)

Obviously if there's anyone else out there with a better implementation please let me know!


Show all events that are active between two dates chosen from exposed date filter

If you have configured your view to display all events that has start date >= x and end date <= x then what you have done show do the job.

In order to make it easy for others to help you, I recommend that you give description of your content types date fields, update your question with export code of your view so that others look and spot mistakes if any.

In the meantime, I have created a content type called event, and give it one field called i.e. date (I have configured the date field to collect both start date and end date - only year/month/day). I then setup a view and setup two exposed filters on start_date and end_date of this content type with operators as greator than or equal to and less than or equal to, and they seem to work without any problem. Follow is the export code of my view

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Events';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['reset_button'] = TRUE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'eventsbydate' => 'eventsbydate',
);
/* Filter criterion: Content: date -  start date (field_date) */
$handler->display->display_options['filters']['field_date_value']['id'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value']['field'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['operator'] = '>=';
$handler->display->display_options['filters']['field_date_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_date_value']['expose']['operator_id'] = 'field_date_value_op';
$handler->display->display_options['filters']['field_date_value']['expose']['label'] = 'date (field_date)';
$handler->display->display_options['filters']['field_date_value']['expose']['operator'] = 'field_date_value_op';
$handler->display->display_options['filters']['field_date_value']['expose']['identifier'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['field_date_value']['group_info']['label'] = 'date (field_date)';
$handler->display->display_options['filters']['field_date_value']['group_info']['identifier'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['group_info']['remember'] = FALSE;
$handler->display->display_options['filters']['field_date_value']['group_info']['group_items'] = array(
  1 => array(),
  2 => array(),
  3 => array(),
);
/* Filter criterion: Content: date - end date (field_date:value2) */
$handler->display->display_options['filters']['field_date_value2']['id'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value2']['field'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['operator'] = '<=';
$handler->display->display_options['filters']['field_date_value2']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_date_value2']['expose']['operator_id'] = 'field_date_value2_op';
$handler->display->display_options['filters']['field_date_value2']['expose']['label'] = 'date - end date (field_date:value2)';
$handler->display->display_options['filters']['field_date_value2']['expose']['operator'] = 'field_date_value2_op';
$handler->display->display_options['filters']['field_date_value2']['expose']['identifier'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'events';

screenshot of the configuration page is as follow

If the above approach does not help you then have a look at this useful module https://www.drupal.org/project/views_between_dates_filter


How to prevent child element to move when parent dropdown?

In css you need to give your menu bar div an absolute position.

For Example: .menubar { position: absolute; } so that it overlays everything, so it won't affect anything else.

Then adjusted if needed

Example: .menubar { position: absolute; top: 0px; left: 20px; }

Also you will need to increase the yellow div from 50px to 70px

.yellow { margin-top: 70px; }


Administrative form to create new entities of a custom entity type

As far as I can see, the Entity Creation Kit module provides these create/edit/delete forms out-of-the-box. Although you should probably redefine your entities with help of that module.

Otherwise, you can perhaps take a look at the ECK module source code and use the relevant parts for your custom module.


Using HOOK_username_alter() to hide the real username

The $account argument in hook_username_alter() provides the user entity object with all its field values. You can use its field values for your $name substitution. For example:

function MyCustomModule_username_alter(&$name, $account){
  global $user;

  // This example presumes a field_first_name as a user first name field.
  // It will vary based on your field & language environment.
  // use Devel's dpm() to find your actual value for user entity.
  if (isset($account->field_first_name[LANGUAGE_NONE][0]['value'])
      && in_array('venue admin', $user->roles)) {
    $name = $account->field_first_name[LANGUAGE_NONE][0]['value'];
  }
}


Disable third-party modules before core update

The one and only way to solve your problem responsibly is the following.

Download all files to your local machine.
Where you have a web development setup. And Drush.
Download the database.
Setup the page on your local machine, import the database and re-do locally what you were currently trying to do on the live server.
Use your local Drush and whatever other tools you can get to check error messages, server logs, debug output etc.
Drop and re-import the local database and repeat every step until you have reproduced the problem often enough to know what went wrong in the first place.
Fix your live page.

And finally:

Never ever again update stuff untested on the live server. And have the database backed up let's say at least once a week. Good luck!


How can I override the fivestar title attribute without hacking the module?

The reason your javascript didn't work is simple. If you disable Javascript and load the page with the fivestar widget, it's just a simple <select> list. It's turned into a clickable star widget using Javascript as well. So your js was most probably being overridden by fivestar.

You can do this without hacking the module and without using javascript by creating another custom module, but there's a small issue explained at the end. Lets call the module myfivestar for example.

You would then need to implement hook_element_info_alter() to change the fivestar element's process callback to your own custom one:

function myfivestar_element_info_alter(&$type) {
  // Change the process callback of fivestar to myfivestar_expand
  if (isset($type ['fivestar']['#process'])) {
    $type ['fivestar']['#process'] = array('myfivestar_expand');
  }
}

Now you just need to copy the function fivestar_expand from the fivestar.module to your own module, rename it to myfivestar_expand, and change the line:

$options[$this_value] = t('Give @title @star/@count', array('@title' => $title, '@star' => $i, '@count' => $element['#stars']));

to:

$options[$this_value] = ''

which will effectively make the <select> list useless for visitors browsing with Javascript off as it removes the option labels which are then turned into the title attribute using fivestar's javascript.


How to capture git's output in drush make?

Ok, the short answer is: it is not possible. Not at the moment. Although the code in includes/exec.inc is prepared to output the captured stdout and stderr of the command, it will only do so, if DRUSH_DEBUG is set:

  exec($command . ' 2>&1', $output, $result);
  _drush_shell_exec_output_set($output);

  if (drush_get_context('DRUSH_DEBUG')) {
    foreach ($output as $line) {
      drush_print($line, 2);
    }
  }

The only way to set DRUSH_DEBUG is by giving the --debug flag on drush command-line (it can not be set from drushrc.php). Sadly, in a number of cases -- including git-invocations -- the top-level drush invokes a child drush to do the actual work. It is doing so without passing the --debug flag to it...

I filed a ticket with drush-maintainers and implemented a work-around. We replaced the real git executable with a shell-wrapper, which captures stderr of the real git (and some other info, like environment veriables) into a log-file, then feeds the captured stderr to its own descriptor 2 -- just in case the caller cares. Then, if the real git's exit-code is 0, the log is deleted, otherwise it is retained for investigation.


Default images also as user selected image functionality

Representative_image

  Allows you to define representative image or media fields for entities
  like nodes, taxonomy terms and the like. These can then be used in
  Open Graph meta tags (via tokens); or as fields in views. The media
  module is also supported. A default image can be defined for those
  entities without images.


Programmically populate select list with hook_form_alter

I'm not sure to understand what do you want but here is a sample of code I've that may answer to your question.

$form['remise'] = array(
    '#type' => 'select',
     '#options' => array(
        0 => t('Sur les catégories & les marques'),
        1 => t('Sur les catégories uniquement'),
        2 => t('Sur les marques uniquement'),
     ),
    '#title' => t('Remises'),
    '#required' => TRUE,
    '#default_value' => 0,
  );


Can we load core css files from custom theme with yml lib?

The first attempt to load the single file normalize.css is not correct. If you want to do it this way, you have to use the full path to this file.

But this is not the preferred way to do this. You don't know if in future the position of this file will change. Better use the library already defined in core, as you have done in the second attempt to load modernizr. This will work, if you put the key dependencies on the first level of the array, for example see the core library date:

drupal.date:
  version: VERSION
  js:
    misc/date.js: {}
  dependencies:
    - core/drupal
    - core/modernizr
    - core/jquery.once
    - core/jquery.ui.datepicker

If you look for normalize.css, this is defined in core:

normalize:
  remote: https://github.com/necolas/normalize.css
  version: "3.0.3"
  license:
    name: MIT
    url: https://github.com/necolas/normalize.css/blob/master/LICENSE.md
    gpl-compatible: true
  css:
    base:
      assets/vendor/normalize-css/normalize.css: { weight: -20 }

And you can use it as dependency in *.libraries.yml:

  dependencies:
    - core/normalize

Or as library in the theme.info.yml file:

libraries:
  - core/normalize

If you use a core library, you don't have to put it in your own library, you can choose the direct way to use it.


How can I get module configuration for testing

The tests do not care about the settings, which are saved in the database. They work with settings in config/import/mymodule.settings.yml

The file can look like this:

var1: 'Some text'
var2: 1
var3: http://example.org

More info: https://www.drupal.org/docs/8/creating-custom-modules/include-default-configuration-in-your-drupal-8-module


How to create grouped filters based on integer range?

You might try the Contextual Range Module: https://www.drupal.org/project/contextual_range_filter

According to the documentation, this allows you to make a contextual filter based on a range (as opposed to just a single field value).


Why would enabling a new module result in the majority of modules disabling?

It appears you're being affected by a known issue that has been resolved in Drupal 8 but still needs to be back ported to Drupal 7. The PHP extension Suhosin causes modules with parentheses in the package name to be disabled. You can edit your Suhosin configuration to remove parentheses from the array index blacklist or, if you're unable to do that in a pinch, you can edit the relevant module files to remove the parentheses from their package names.

More info in the core issue: https://www.drupal.org/node/2665152


How to change the value of a row in views

You could try using Views Conditional

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

  Views conditional allows you to output text based on the result of the
  condition.

As per the readme.txt

  How to use Views Conditional:

  Create a view. Add some fields under "FIELDS".
  Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
  Add and configure fields...
  Choose a field to run a condition against, and provide values accordingly.
  Save, views conditional handles the logic and returns as specified.


Managed to do this with Rules:

  Events: User has logged in.

  Condition: -

  Actions: Page redirect to user/[account:uid]/edit


Drupal 7 | Associate dynamic user to a content type

References module will enable you to do that.

It allows you to create fields and associate them with existing content/users on the site. It also features integration with Views so you can have more complex logic to filter out the available options.
The field can also be displayed as an autocomplete.


batch importing node data -- via database?

There are two routes you can take.

One uses the Migrate module usually in conjunction with Table Wizard.  This gives you a web front end for doing an import with field mapping, and other nicities.  EDIT: just saw that TW doesn't have a D7 version.

The other is a custom import script.  The script does the Drupal bootstrap process, queries the remote database, creates a $node and then does a node_save.  This is a little more complex, but not that hard.

I have been doing the later on new projects, and is easy to adapt to XML, CSV, or other data sources.


My hosting provider ask me to use xCache instead of the built in Drupal cache system

It makes perfect sense to use PHP opcode cache, you should be using one if not already using. I'd recommend APC for PHP version 5.4 and less.

xCache is somewhat similar in the way it handles caching like APC, but the mechanism is different. You have to do quick research which one suits your needs and hosting compatibility.

If you are using PHP 5.5+ then it comes with in-house OPcache. Personally I haven't tested but when the package is bundled with software core it certainly grabs attention. You should check the use case for you.

eAccelerator is also nice one, I used to use it few years ago, but, when I got to play with more RAM, APC is beast.

The later part of your question says about

  use xCache instead of built in Drupal cache system

which is completely false, xCache or any other opcode cache is not replacement of Drupal Cache, it should be used together. Opcode cache is for PHP, it doesn't have anything to do with Drupal.

As for the part of replacement concerns, you can use Memcached instead of Drupal cache that is stored in database.


How can I repeat parent table field only once for a group of child table fields?

The only way I can think of doing this without custom coding is by using the Views Field View where you create two different Views Displays, one with the contextual filter, save them both, then "embed" the contextual one into the other view.

This type of database query can be very performance intense, and caching is recommended. Or avoid it if you can.

In your case you can keep your original accounts view, but remove the student fields. Add another Display (Block) that is showing student name gender and age, and add a contextual filter for the account, save the view. Then in your original views display add the field for the student info.

You may need to adjust how the labels are shown, so you don't have them duplicate/in odd places because of the recursion.


Contextual information on custom Access Denied page

Supposing that the site is using clean URLs, I would rather use the following code:

function fn_custom_access_denied() {
  $path = drupal_get_normal_path(trim($_SERVER['REQUEST_URI'], '/'));

  if (($node = menu_get_object('node', 1, $path)) && ($node->type == 'event')) {
    drupal_set_message(t("%event is a private event.", array('%event' => $node->title));
  }

  return "";
}


Following some of the information found in Berdirs answer and comments I was able to arrive at a solution.

I formatted my header like so:

            $header = [
                'title'      => [
                    'data'      => t('title'),
                    'field'     => 'title',
                    'specifier' => 'title',
                ],
                'number'       => [
                    'data'      => t('Number'),
                    'field'     => 'field_number',
                    'specifier' => 'field_number',
                ],
                'time'       => [
                    'data'      => t('Time'),
                    'field'     => 'field_rank',
                    'specifier' => 'field_rank',
                ],
            ],

I then performed the EntityQuery like so

            $nids = \Drupal::entityQuery('node')
                ->tableSort($header)
                ->condition('type', 'my_content_type')
                ->condition('status', 1)
                ->pager($items_per_page)
                ->execute();

I formatted my rows like so

                $row = [
                    'data' => [
                        $node->title->value,
                        $node->field_number->value,
                        $node->field_rank->value,
                ];

After that generating the table was easy

            $render = [
                'table'           => [
                    '#prefix'        => '
Entries
',
                    '#theme'         => 'table',
                    '#attributes'    => [
                        'data-striping' => 0
                    ],
                    '#header' => $header,
                    '#rows'   => $rows,
                ],
            ];

The important parts I was missing is the proper format for $header. And using ->tableSort($header) instead of                 ->extend('Drupal\Core\Database\Query\TableSortExtender')
                ->orderByHeader($header) in my entityQuery


Best way to keep local and remote sites synchronized?

For executing drush commands on others server you should have access via SSH, and you only have access via FTP. Your best option I think is doing every day on production a backup and download it and then in your local machine: drush sql-cli < db.sql or mysql db < db.sql

Maybe you can use the module stage_file_proxy so you don't have to copy files


Altering ImageField Widget with FUpload enabled

I guess it is the line

$element['#type_name'] == 'property_gallery'

that makes your changes have/not have effect.

I would actually suggest writing a new widget alltogether, instead of altering the existing one(s). It isn't that difficult, but I don't know of any good tutorial for it online – there is a good chapter about it in the book "Drupal 7 Module Development" though, which helped me a lot.

If you find a good online tutorial, please post the link!


Recommended approach for setting up contact management?

Here are multiple options for implementing such contact form, as further details below.
Default contact form (D6 or D7)
This is the contact module that comes with Drupal 7 core (though disabled by default). Typically used by Drupal newbies, and commonly known to have quite a few limitations / issues that can be resolved using some of the contributed modules (mentioned below).
Webform (D6 or D7)
The Webform module is the traditional (and mature) solution used in quite a few (close to 500K) sites. Some details from its project page:

... for making forms and surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has an extensive API for expanding its features.

Note: It also has 2 related charting modules, i.e. Webform Chart and Webform Charts, both integrate very well with the Webform module to provide charts about data created via the Webform module.
Entityform (D7 or D8)
The Entityform module is a fairly new solution used in "only" about 18K sites, and only has an RC1 release so far. Some details from its project page:

... enables you to create front-end forms (fieldable entities), which contain fields that you define! These forms use the standard Drupal fields. This means that out of the box, you can use any standard Drupal node field! As of the time this article was written, there were over three hundred "field" modules. And since Entityforms are "Drupal entities", you will automatically be able to use future "field" modules!
The forms can be used to create custom surveys, petition, and personalized contact forms, and other customized form. (For those of you who have used Webforms, this module brings Webform's functionality into the "standard" Drupal field / entity world.)

Note: in D8 renamed to eForm (to avoid name confusion).
Contact forms in D8 core with the Contact Storage module (D8)
This is the contact module that comes with Drupal 8 core (enabled by default now).
Many more details about this can be found in the article about "Goodbye Webform? Contact Forms Are In the Drupal 8 Core", which explains why you will also need the Contact Storage module:

The one key feature that's missing with the Contact module is the ability to store messages sent through the forms. This is odd, because Drupal 8 deals with contact messages as entities. You can add comments to them, for example. You just can't see them!
To solve this problem, you'll need a contributed module called Contact Storage. The author says they hope to have this in core for Drupal 8.1 and that would make a lot of sense, filling this functionality gap.

Some details from the Contact Storage project page:

... will provide storage for Contact messages which are fully-fledged entities in Drupal 8.
This plus core contact module aim to provide functionality equivalent to the base-features of Webform or Entity Form.
The goal is to firm up this functionality in contrib with view to move into core in 8.1.x or later.


Why does "Read more" link not show up on view, but "Add new comment" does?

You have a mistake on your code. Instead of $variables['content']['links']['node'] you wrote $variables['content']['links']['comment'].

Corrected code:

function ap_hogeschool_theme_preprocess_node(&$variables){

  $variables['content']['links']['comment']['#links']['comment-comments'] = FALSE;

  if( $variables['type'] == 'wie_zijn_we_' && $variables['view_mode'] == 'teaser' ){

     $variables['content']['links']['node']['#links']['node-readmore']['title'] ='

';
     // Mistake was in this line:
     $variables['content']['links']['node']['#links']['node-readmore']['html'] = TRUE;
     $variables['content']['links']['comment']['#links']['comment-add']['title'] = '

';
     $variables['content']['links']['comment']['#links']['comment-add']['html'] = TRUE;

   }
  }


copy term reference from one to other field

You could do something like this:

$result = db_query("SELECT nid FROM {node} WHERE type = 'my_type'");
foreach($result as $row){
  $node = node_load($row->nid, NULL, TRUE); // reset cache
  // Assign one node reference field to another
  $node->field_termreference_2 = $node->field_termreference_1;
  node_save($node);
}

If you've got a lot of nodes, you may need to use the Batch API for that.

Alternatively, you may be able to copy the field tables to another field table at the database level with SQL ( backup first )

Something like:

INSERT INTO field_data_field_termreference_2 SELECT * FROM field_data_field_termreference_1;
INSERT INTO field_revision_field_termreference_2 SELECT * FROM field_revision_field_termreference_1;

and clear Drupal caches after that.


Programmatically added taxonomy terms not being indexed

You're correct. The core taxonomy module doesn't index or display entities other than nodes. taxonomy_build_node_index() is only for nodes.

It sounds like the solution you're looking for is Taxonomy Entity Index.

  The Taxonomy Entity Index module maintains a normalized index of all
  terms associated with a specific entity and revision. The core
  {taxonomy_index} table only maintains its data for published nodes.
  This module maintains its data for all entity types (regardless of
  published or not) and also indexed by revision.

It also supports views integration so you should be able to create a view of users who have been tagged with your taxonomy.


Getting a custom block image field URL in the block Twig template

#url at this stage is not processed yet. This happens later in the image templates.

To get the url in the block template you can access the uri field in the image file entity instead:

{{ file_url(content.field_parallax_image.0['#item'].entity.uri.value) }}

BTW you didn't find this property in the dump output, because it is a computed value to make it easier to handle entity references.


It looks like you are using an older version of Drupal core. Upgrade to one of the betas or the latest 8.0.x from Git and it should work fine.

In the latest versions the filenames have been changed, as reported in YAML files for menu links, contextual links, local tasks, and local actions have been renamed. 8.0.0-alpha14 is the first tagged release with the filename change.


I'm not sure if I understood your question correctly, but if you want to change the stock for a product you can simply call the uc_stock_set() function (where the product is in the $node variable, and the new stock is in the $stock variable)

$stock = 5;
uc_stock_set($node->model, $stock); // sets stock to 5

Or use uc_stock_adjust() to increase or decrease the stock by a certain amount

uc_stock_adjust($node->model, 1); // adds 1 to current stock, stock is now 6

I am assuming that you have

Installed ubercart
Activated the uc_stock module
Created a product, and set its SKU (model) to a certain value, say MODEL_1
Gone to the 'stock' tab on the edit node page of this product and activated the stock for MODEL_1

At this point we have a product, represented by a node. This product has one (or many) associated SKUs. Each SKU has an associated stock stored in the database by uc_stock.

Only once all of this is in place can we can go ahead and use the uc_stock_set and uc_stock_adjust functions.


Enable rest resource resource when module installs

The error was in the .yml file with the id: attribute. Dont need to include the module name with it:

id: custom
plugin_id: 'custom'
granularity: method
status: true
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - cookie


Google analytic module - demographic track does not work

You will have to enable Track DoubleClick data under the Search and Advertising tab in the GA module settings.  You should also make sure your privacy policy is up to date with the correct info found here.


Drush 6.6.0 Site-Install fails with 'No database to operate on.'

Your --db-url is not in the correct format.  Use this instead:

--db-url=mysql://USER@data.rds.awsdomain.com/dbname

Replace USER with the account used to access the database.  If this is the same user that you have specified with --db-su, then the --db-su option is not necessary.  Drush will not go the other way (fill in the "ordinary" user from the privileged user specified via --db-su), though.


How to show a Drupal Commerce coupon system on the cart page?

Basic rule of thumb using any module in Drupal is first read Documentation or Readme or Install files inside Drupal module.. That will tell you how the module works... Go through Project page for full details

For fixed amount discount use Commerce coupon fixed amount

For Example - Readme file explains how to create %off coupon

Example - Create a '10% off' coupon

1) Install modules

Install:
   - Commerce Coupon
   - Commerce Coupon UI
   - Commerce coupon percentage

2) Create a 'Percentage coupon' coupon

Go to: Home > Administration > Store > Coupons

Click 'Create Coupon'

Choose 'Create Percentage coupon'
   (if you have no other coupon types clicking 'Create Coupon' will redirect to
    the 'Create Percentage coupon' form)

Create a percentage coupon with the following:

Coupon Code: 10%OFF
Number of Uses: 1 (change as necessary)
Percentage Amount: 10
Active: Yes

Save

3) Enable the 'Coupons' area on one of your Commerce checkout panes

Go to: Home > Administration > Store > Configuration > Checkout settings

Move the 'Coupons' item into one of the checkout panes

Save

4) Test it!

Please do some basic research before posting questions like above .. Otherwise they will be put onhold :-)


I believe I have found something that does what I want: https://www.deeson.co.uk/labs/extending-entitydrupalwrapper

The basic idea is that, since drupal-core doesn't facilitate the extension of entity-classes, we use the entity-metadata-wrapper instead.

The above example would then be reformulated as such:

class MyNodeWrapper extends EntityDrupalWrapper{
    public function __construct($data) {
        parent::__construct('node', $data);
    }

    public function sayHi(){
        drupal_set_message("Hi!");
    }
}

function myNode_entity_load($entities, $type){
    if($type == 'node'){
        foreach ($entities as $entity) {
            $emw = new MyNodeWrapper($entity);
            $emw ->sayHi();
        }
    }
}

This appears to be a very reasonable approach. Only thing I dislike about it is that you can't use entity_metadata_wrapper to get the MyNodeWrapper-wrapper.


set the $cookie_domain variable in sites/default/settings.php

<?php
$cookie_domain = $_SERVER['SERVER_NAME'];
?>

Uncomment the $base_url variable and set the base URL of your website (without the trailing slash).

Another option if you have the Drupal Domain access module installed use

<?php
$base_domain = explode('.', $_SERVER['SERVER_NAME']);
unset($base_domain[0]);
$base_domain = '.' . implode($base_domain, '.');

$cookie_domain = $base_domain;
?>

Here is the reference to the answer


Is it possible to done search indexing locally, then upload it?

The suggestions in the comments are good, specially using solr.

But in your case you can index the whole data locally, and dump these three tables: search_dataset, search_index, search_total and then import it on the server.


I have found there is good reason why Drupal restricts html in titles. If you need a subtitle, it is best to create an additional field in the content type, then position it using the Display Suite module.


Display Text using flags on user profile?

I achieved 'Out of office' flag functionality using rules module.

Placed an out-of-office flag on user profile and set visibility rules (panels)   to show flag only if its user's own profile
Within flags used flagging form to capture user out-of-office message
Added an extra field 'out-of-office' within user's profile.
Created a rule on flagging-event to populate 'Out-office-field' with text from flagging form.
Created a rule to delete the text from 'out-of-office' field on unflagging.


How can I categorize nodes by countries?

You can achieve this by using views:

Create a new view that displays persons.
Under "Advanced" add a contextual filter for your country
As path use: "my_path/%"
All users for country "Belgium" Will be available on "my_path/BE"


Finding nodes that have not been indexed

The status of node indexing is based on the search_dataset. This table stores content keyword blobs and their associated sid, the primary key for the content's keyword (i.e. the nid). When compared/joined against the node table, it should let you see which nodes aren't index.

From what it sounds like, you've already spotted problem node(s) so it's just a matter of confirmation. Removing the node(s) from being indexed (e.g. hacking
NodeSearch::indexNode()) to confirm it's the problem, then finding out what content in the node is blocking indexer.


You can use Flag Module with drupal views to create your playlist. Flag module allows you to bookmark contents, comments etc. Then you can display the flagged content by adding flag:content relationship in your view.


Is there a way to limit how much storage users have to store their content?

With a support request and a little bit of work, Storage API could probably do this for you. In Storage API terms, I believe what you would do is create a "container" per user, and then use the sub-module "audit" to check how much space is being used. This number in turn could be used by the field widget you are using to limit uploads.


Pathauto menu token duplicated for a menu added in hook_node_insert

I finally moved the insertion of my menu in hook_node_presave() and then pathauto worked normally.


Moving, Removing, Disabling Administration on live server

The best approach would be to deny access to the administration pages for certain roles on your live site using standard Drupal permissions ( http://example.com/admin/people/permissions ).

The permission you're looking for is called "Use the administration pages and help".

Returning a 404 for all admin pages doesn't seem like the correct thing to do here, as the page has been found. A 403 is the correct semantic response for this.

If you're desperate, having the following code in a module on your live site only would do the trick:

function MYMODULE_init() {
  if (arg(0) == 'admin' && $GLOBALS['user']->uid != 1) {
    drupal_not_found();
  }
}

But I can't say I'd recommend it :)


Attaching more than one feeds url to a single content type

Instead of using the GUID field method that comes with Feeds, it is possible to use Feeds with the Field Validation module. See the discussion at patch at the bottom of this thread.

I haven't tried it, but Field Validation might let you set multiple unique fields as it provides validation options for every field in a content type.


Weekly Gym schedule / irregular recurring Events / D7

Try this:

Create content types gym1, gym2, gym3... > add suitable fields to them eg. Title and time(name the time field to field_gym1_calendar, reason for this -- see part five).
Create content: EXAMPLE: "content type: gym 3 --> Title: bodypump, Time: 10/10/2013 14:00-14:30".
You can also add a taxonomy "bodypump, zumba, etc..." and add a 'Term Reference'-field to your content type (This way admin doesn't have to type 'bodypump' or 'zumba' every time he's adding stuff to calendar, just select the right one from dropdown-box)
Install "Date Tools" and "Date"- modules
Go to Views > look for button "+ Add view from template" On top of the page.
Search for the NAME of the TIME field you added to CONTENT TYPE gym1.
Should look something like this: "A calendar view of the 'field_gym1_calendar' field in the 'node' base table."
Name this view to 'Gym 1 calendar'- for example.
If you have content in "gym1/......." It should be listed in "Preview" Below

Play around with "+ Add view from template" button, it creates a calendar view of any node type with -date / time- field in it (I think)

All this works in a commerce_kickstart install I'm currently f*cking with.. All the modules you need are listed in my comment... don't know. Have fun :)


Go to admin/structure/menu/manage/main-menu and edit the parents that have children that you wish to show, and click the tickbox 'show expanded'

Or alternatively install the module http://drupal.org/project/menu_expanded which brings back the tickbox on the menu 'list items' page ala drupal 6

Hope this helps


How do I clear the cache for a single node?

If you have the node object, use

use Drupal\Core\Cache\Cache;
...
Cache::invalidateTags($node->getCacheTags());

That's better than to assume the cache tag identifier will be 'node:' . $node->id() forever.


It's in

includes/theme.inc.

Docs are here.

Next time just put the name of the function in Google...the docs on Drupal.org will tell you what file any function is in.


How to print field type image in views-view-fields--xyz--block.tpl.php

Use field_view_field.

E.g.

$node = node_load($node_id);
print drupal_render(field_view_field('node', $node, 'field_your_field_name'));

Or if you don't want the label with the field then:

print drupal_render(field_view_field('node', $node, 'field_your_field_name', array('label' => 'hidden')))


is there a way to customize url alias by content type?

Yes. You can use the pathauto module.

http://dgo.to/pathauto


Berdir set me in the right direction with this question but the actual specifics of what I needed are buried in the replies to this question on rendering images from a node:

in  /themes/mytheme/page.html.twig add

{{ file_url(node.machine_name_of_field.entity.uri.value) }}

That renders just the image URL so I can place the image anywhere.


You can do this without uninstalling, but it takes some fiddling:

Move the module in filesystem
invoke drush ev "drupal_flush_all_caches();"
invoke drush cr

The crucial setting is the entry system.module.files in key_value database table. If you move the module(s), the try to run drush cr directly, it may fail because drush tries a full bootstrap and fails to locate the required files.

drush ev does an error-free bootstrap using drush_bootstrap_max(), and drupal_flush_all_caches rebuilds system.module.files config without trying (and failing) to load the moved files. Whereas drush cr does a full-site bootstrap, which causes drush to halt on any errors.


How do I specify a parent domain in a multi-site install?

It is called multi-site aliasing, hence the results. Drupal offers you to server multiple domains from the same folder in order to preserve the paths in the database. So you would use the same folder for example.com and sub3.com because you might want to disable one of them later on. Aliasing is meant on a file level here. What you need is a redirect.

A 301 redirect code can be issued by your webserver-software itself (e.g. Apache/nginx config or apache .htaccess) or by sending a header via the scripting software.

The "drupal-way" solution for you would of course be to use a module for sending that header. My recommendation would be multisite_redirect, because it would only need a one time setup for your case outlined above.


Drupal is very capable in this arena.

A few modules that come to mind are:

Voting API
Fivestar
Rate

With more detail I think you would get a better answer, but at a glance I believe you could accomplish this quite easily with readily available modules.

The tricky part I believe will be figuring out how to structure your site.

Will People/Service providers be stored as nodes or user accounts?

Will users need to register to rate? Can anonymous users rate? Both?

Can service providers register their own business/service or will you be adding a pre-selected list?

If you create a custom content type called "Service Provider" for example, you could apply the Rate module to this content type and have something up and running quite quickly.


User uploads media and community votes: How do I implement them?

Surely you need Views, which allows you to create a view of specific nodes; if the users of your site are allowed to votes on the content, you probably want to offer a list of the most voted notes, or the less voted nodes.

As per rating a node, there are many modules that can be used. Part of them requires the Voting API module, such as Fivestar, Rate.
Which one to use depends on how the users are allowed to vote. The Rate module allows the users to up-vote and down-vote. With Fivestar, they are allowed to give a vote from 1 to X (where X is normally 5); they are not allowed to down-vote, which means the rate cannot be a negative number.

The Flag module allows the users to flag a node for a specific reason; by default the module comes with the "Add to my bookmarks" flag that can be, in your case, changed to "Add to my followed." Thanks to the integration with Views, Flag creates a view listing all the nodes flagged with a particular flag; such view can be per user, and in this case each user has a view for the nodes they flagged, which is visible as tab in their user profile, or it is global, and in this case the view is not specific for a user but every user can add nodes to that list.


I want the date view filter on current date, not on current time

I have a view similar to what you're trying to achieve. You have to install the Date module (https://drupal.org/project/date) and through that module, you'll be able to set the granularity to 'Day' instead of minutes or seconds. Then, just put +0 day or now


How to show a description when a select box item has been selected

This isn't strictly theming, but the following works for me:

Put the following in a custom module:

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

  $items['termdescription/%'] = array(
    'title' => 'Term description callback',
    'page callback' => 'tax_desc_get_description',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function tax_desc_get_description($tid) {

  if (!is_numeric($tid)) {
    return drupal_json_output('Select a term');
  }

  $term = taxonomy_term_load($tid);

  $description = $term->description;

  return drupal_json_output($description);

}

This is simply a menu hook that calls a function.  You will be calling this menu link to get the description data for the taxonomy term.  The second function takes the term ID that will be passed in the ajax call, and gets the term object.  From that, it pulls the description set using the standard taxonomy term description.

Next, you'll need to add the following javascript and reference it in your module .info file:

(function($){
  Drupal.behaviors.taxdescGetDesc = {
    attach: function (context) {

      $(".page-node-add-article #edit-field-tags-und").after('
Select a term
');

      $(".page-node-add-article #edit-field-tags #edit-field-tags-und").click(function(){
        $.ajax({
          cache: false,
          type: 'POST',
          url: "/termdescription/" + $(this).val(),
          context: document.body,
          dataType: "json",
          success: function (json){
            $('#mycontainer').html(json)
          }
        })
      })
    }
  }
})(jQuery);

You'll probably want to change the ID's and classes that I've used, as I've just used a standard article type for this.

This Javascript will put a div with the ID of mycontainer below the select box (this can be styled/positioned with CSS so it matches your image).

when you click the select box, the term description will populate the div created earlier called mycontainer.

Just in case, your .info file will look like the following:

name = taxonomy description
description = taxonomy description from list

core = 7.x

scripts[] = tax_desc.js


usually if conventional uninstall wouldn't work i'd try clearing the module's entry from system table removing tables from the module installation (after backing up the data) clear the cache and reinstall.. hope it works for you ...cheers!!


// Define which node is the source, this node has his own id as translation nid (tnid)
$source_node = node_load($source_nid);
$source_node->tnid = $source_nid;
node_save($source_node);

$new_node_in_a_other_language = new stdClass();
$new_node_in_a_other_language->type = 'your_type';
node_object_prepare($new_node_in_a_other_language);
$new_node_in_a_other_language->title    = 'title fr';
$new_node_in_a_other_language->language = 'fr';
// define source tnid
$new_node_in_a_other_language->tnid = $source_nid;
node_save($new_node_in_a_other_language);


Drupal 7 image styles ignored by theme preprocess function

By taking over the display of that field you're actually bypassing all the field system would usually do to apply the custom display settings; it basically passes off the responsibility of creating the field HTML to you, and provides you with the raw values you'll need to build it up.

So if you want to output a style based image, you'll need to do it manually using theme_image_style():

$args = array('style_name' => 'thumbnail', 'path' => $item['#item']['uri'], 'alt' => 'Alt text');
$image = theme('image_style', $args);

// Append $image to your output...


Is allowing Full HTML (HTML filter on) input for all user roles safe?

Only trusted roles and users should have access to Full HTML. You can add some additional allowed tags to the Filtered HTML input format but don't add too many or you risk creating a vulnerability. (admin/settings/filters)


The 'rules' for the page.tpl.php template suggestions state you need to substitue each / in the page for 2 dashes, so your template file needs to be called:

  page--mymodule--list.tpl.php

Remember to the clear the cache again once you've made the change


How can I print usernames in order using entity_load function?

small change in your code will do it for you

$users = entity_load('user');//load all user in your site
$usersIds = array_keys($users); // get all uid of the user
foreach($usersIds as $usrId) {
    $user = user_load($usrId);
    $user_load_name = $user->name;//get the user name
    $user_load_name1[] = $user_load_name;// store all user name in array
 }
 natcasesort($user_load_name1);//For sorting array in ascending order INCASE SENCITIVE order
 $arr = array_reverse($user_load_name1, true);// For making it in descending

This code will only give the user name in Decending order if you want it in ascending order just remove array_reverse() line that will be enough.

hope it helps you :)


If you need to change the content of the variables passed to the theme function, then you can simply implement a preprocess function for that theme, which in Drupal 7 is invoked for every theme function, including the ones not using a template file.
In the case of theme_form_element() the preprocess function for your theme is MYTHEME_preprocess_form_element().

You could also avoid duplicating the code of theme_form_element(), and call it before, but in that case you should call it directly as theme_form_element(), not as theme('form_element') (which would cause an infinite loop).

The problem with theme_form_element() is that it doesn't use $element['#attributes']['class'] to set the attributes of the form element. It uses a local variable that is initialized with the following code, which passes its value to drupal_attributes().

  $attributes['class'] = array('form-item');
  if (!empty($element['#type'])) {
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  }
  if (!empty($element['#name'])) {
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";

To add a new class to the form element, you have two alternatives:

Copying the code from theme_form_element() to your theme function, and editing it
Call theme_form_element() from your theme function, and add a new class to the output returned from theme_form_element() using preg_replace().


This is what you need.

// Turn off page cache
drupal_page_is_cacheable(FALSE);
// Set memcache prefix to be different for each hostname.
$conf['memcache_key_prefix'] = $_SERVER['HTTP_HOST'];


View date filter using years as an offset

It turns out this was more of a PHP strtotime() question.  I just had to figure out the appropriate phrase to get the time frame I wanted, which is: "first day of january last year". I placed that phrase in the filter's offset value.


How to find out a node's comment status (open, closed) from node ID?

The following code should do the trick:

$node = node_load($argument); // load the node object based on the nid
if($node->comment == COMMENT_NODE_CLOSED) {
  // comments are closed - hide the view
}

There are 3 constants that define the different comment states:

COMMENT_NODE_HIDDEN
COMMENT_NODE_CLOSED
COMMENT_NODE_OPEN

For more information see the Node object reference.


How can I place brackets around a field in a view?

Simply use the rewrite field option: use the 'country' token and place brackets around it.

Special thanks to @Mołot!


How do I get multiple references from the autocomplete?

The comma is used to separate multiple references, but looking at the code in Name::valueForm() I would say the form element needs to use a property more.

  $form['value'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => $this->t('Usernames'),
    '#description' => $this->t('Enter a comma separated list of user names.'),
    '#target_type' => 'user',
    '#tags' => TRUE,
    '#default_value' => $default_value,
    '#process_default_value' => $this->isExposed(),
  );

Settings #tags to TRUE makes the the form element accept multiple values.

The format of the values assigned to the form element is evident in EntityAutocomplete::validateEntityAutocomplete() (its validation handler), which uses this code.

  $input_values = $element['#tags'] ? Tags::explode($element['#value']) : array($element['#value']);

  foreach ($input_values as $input) {
    $match = static::extractEntityIdFromAutocompleteInput($input);
    if ($match === NULL) {
      // Try to get a match from the input string when the user didn't use
      // the autocomplete but filled in a value manually.
      $match = static::matchEntityByTitle($handler, $input, $element, $form_state, !$autocreate);
    }

    if ($match !== NULL) {
      $value[] = array(
        'target_id' => $match,
      );
    }
    elseif ($autocreate) {
      /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface $handler */
      // Auto-create item. See an example of how this is handled in
      // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::presave().
      $value[] = array(
        'entity' => $handler->createNewEntity($element['#target_type'], $element['#autocreate']['bundle'], $input, $element['#autocreate']['uid']),
      );
    }

The form element value is an array of item whose target_id key is an object of the requested entity.

(From that code, it is also clear that #tags makes the form element accepts multiple references separated by commas.)

As for the using reference that aren't found, you can decide what the autocomplete does by setting #validate_reference: If you set it to TRUE, and #autocreate is not set to TRUE, the autocomplete will accept only existing references.


Avoid access to profiles (user/%user/view)

There are four problems with the code you reported:

The code is changing the menu type, when it should not do so.
The code is changing values that it should not touch, if the purpose is to only change who can access the user profiles.
user_edit_access() and user_access() expect the argument they receive to be a user object, not a string. It is wrong to set "access arguments" to array('access administration pages'), as you are doing.
Even if you would set "access arguments" to array(1), user_edit_access() allows the users to see their own user profile; if you want to avoid to show to the users their own user profile, then that function is not the function I would use as access callback.
As said by jhedstrom, it is not necessary to use code in this case, when it is enough to don't give the permission to access user profiles to those roles you don't want to be able to see any user profile. The answer I am going to give takes the assumption you don't want the users to see any user profile, including their own; in this case, removing the permission to access user profiles doesn't help, as Drupal still allows the users to see their own user profile.

function mymenu_menu_alter(&$items) {
  $items['user/%user/view']['access callback'] = FALSE;
}

function mymenu_user_view_access($account) {
  return $account && $account->uid && user_access('administer users');
}


I do not as yet have significant experience with internationalisation in drupal.

Having said that, if you would like greater control over your search indexes I would definitely look at using search api instead of the default drupal search.

As well as allowing you to pick which fields are indexed, it also abstracts your search index so that you can take advantage of Apache solr etc. In your case, at least to start, I would suggest you stick to the simple database backend for search api.

The more flexible approach of search api brings additional functionality via other modules. For your use case I would look at Search API Entity Translation, which

  generates separate search index items for all/selected available
  languages for each translatable entity

It looks like this relies on entity translation rather than internationalisation, so make sure you survey any potential implications for translation of your content first.


In Drupal 8, there is a [module-name].module file inside your module. You can use "Hook attachments alter".

Code to alter your meta tags -

// For adding description in meta tag .

function hook_page_attachments_alter(array &$attachments) {
   $attachments['#attached']['html_head'][] = array(
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'description',
            'content' => 'Any thing in meta description',
          ),
        ),
        'description',
      );

// For adding title in meta tag.

$attachments['#attached']['html_head'][] = array(
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'title',
            'content' => 'Any thing in meta title you want',
          ),
        ),
        'title',
      );

// For adding noindex in meta tag-robots .

$attachments['#attached']['html_head'][] = array(
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'rel' => 'robots',
            'href' => 'noindex',
          ),
        ),
        'noindex',
      );

You can add more meta tags for different pages and can validate them too.


How to implement different landing pages for different countries?

First thing is, how are you identifying your user's country?

You could use JS and the geolocation API
Or you could use the IP of the user and use a database

Id depends on how accurate you need this.
Once you translate the information to an actual country. Then you can decide what to show.

Something to keep in mind is the penalty for this. Instead of showing a different page per country, you might consider showing the same page and maybe via some JS modify an element once you have the location.


How to configure multisites for the console?

a mapping must be done in sites/sites.php for

   drupal multisite:debug

to display the list

sites.php

 /**
 * Multi-site directory aliasing:
 *
 * Edit the lines below to define directory aliases. Remove the leading hash
 * signs to enable.
 */
$sites = array (
    'my_domain_name.fr'=>'my_folder_name_in_sites?'
);

i am not sure for it to be correctly configured

my_folder_name_in_sites?

must be

my_folder_name

or

sites/my_folder_name


The best way to change this would be by editing each record in your database using a tool such as PHPmyAdmin. Once you have migrated to the new website, and enabled the Statistics module you will see the column added in your database table.

Hope it all goes well.

Chandeep


Alter appearance of content types in teaser view through code?

The best example of this I can think of is the Read More module which adds a "read more" link to the end of the body teaser (in teaser mode obviously).

The idea is to use the node view hooks and teaser build mode to target what and when you want to edit.

For Drupal 7 you can look at the read_more module source for an example.
For Drupal 6 you can look at the ed_readmore module source for an example.


Field Entity Autocomplete filter the published nodes

The entity reference appears on the registration form, and the applicant is able to view and choose unpublished nodes from the list.

An anonymous user can see nodes of this type, but obviously they are not meant to see unpublished nodes of this type. On the rest of the site, they cannot see these unpublished node (only the autocomplete ignores this.)


How can I remove a theme that is no longer in core?

You can create a theme calling it test_stable. Then, you clear the cache with drush cr and uninstall the theme with drush theme:uninstall test_stable. It will solve your problem.
You don't need to create the whole theme; the test_stable.info.yml file is sufficient for Drupal to recognize the theme as present.
As the test_stable theme has been removed from Drupal after Drupal 8.7.x, and that file isn't present in latest versions, before proceeding with what I suggested, I would run drush updbst and check for pending updates.


PAReview.sh error, Expected "switch (...) {\n"; found "switch(...) {\n"

Put simple switch, why put curly braces.

    function _MYTHEME_content_grid($columns = 1) {

      $class = FALSE;
      switch($columns) {

        // No sidebars, just content.
        case 1:
          $class = 'grid-100';
          break;
        case 2:
          //something
          break;

       // etc...
     }
   }


How to show the number og members views members views

It's look the same, please follow instructions from image:

Full image: http://i.stack.imgur.com/45olm.jpg


Show taxonomy term's image field on node page

You can achieve this in a different way, using Display Suite module you can simply render taxonomy terms in a desired view mode.


Does a third-party module need to implement hook_help()?

Modules should implement hook_help() even for just giving a short description of the purpose of the module (an overview help page). The standard structure of that page is described in Help text standards / Help page. hook_help() is the hook used from the core Help module.
In Drupal 8.8.x, a new experimental core module has been added: the Help Topics module. Its purpose is allowing modules to write their help pages as Twig template files with an embedded YAML header, for example like ban.banning_ips.html.twig.
---
label: 'Banning IP addresses'
related:
  - user.overview
---
{% set ban = render_var(url('ban.admin_page')) %}

{% trans %}Goal{% endtrans %}

{% trans %}Ban visitors from one or more IP addresses from accessing and viewing your site.{% endtrans %}

{% trans %}Steps{% endtrans %}

{% trans %}In the Manage administrative menu, navigate to Configuration &gt; People &gt; IP address bans{% endtrans %}

{% trans %}Enter an IP address and click Add.{% endtrans %}

{% trans %}You should see the IP address you entered listed under Banned IP addresses. Repeat the above steps to ban additional IP addresses.{% endtrans %}

Since the module is experimental, third-party modules should not depend on that and use those files for their help text, especially because the module is going to be merged with the Help module. The plan is also to deprecate hook_help().
Third-party modules should:

Drupal 7
Implement hook_help() even to show a short overview page

Drupal 8
Implement hook_help() even to show a short overview page; consider writing integration with the Tour module to add additional contextual help to any page in the shape of a tour, which can have multiple steps, each one describing part of a page (such as different form elements in an administrative form)

Drupal 9 (or 10, depending from when the Help Topics module will be merged into the Help module)
Write topics pages even to show a short overview page; consider writing integration with the Tour module to add additional contextual help


It turns out that image_path_flush() is being fired in Drupal\file_entity\Entity\FileEntity->postSave() even when the image is not actually updated. You can see the issue and proposed resolution outlined here: https://www.drupal.org/project/file_entity/issues/2816761


How to positioning a field before another specific field with hook_form_alter()

Set the weight property of your required lower than other.

$form['field_latitude']['#weight'] = 0;
$form['input_latitude']['#weight'] = -10;

or
function provintegra_form_alter(&$form, &$form_state, $form_id) {

$form['input_latitude'] = array(
  '#type' => 'textfield',
  '#title' => t('Search address'),
  '#default_value' => '',
  '#prefix' => '
Mappa qui
',
  '#weight' => -10,
);

}


Nesting views with a node reference field

You can solve it with Viewfield.

  View arguments are supplied through tokens.

So, what you should do:

Add new type of your view (new Block, for example) and add contextual filter by node reference field.
You can modify display format etc.
Create for your tasks new field "View Reference" and set your new display type of view. Check «Always use default value».
Set [node:nid] in Arguments input.

Tested on D7.


How do I fix the missing top 1/2 inch of the content box?

The body class in the custom-media.css is defining margin-top: 90px for the fixed header, you will need to increase this to match the size of your header.

You may need to include media queries to account for reactive menu changes.

It probably works when you are logged in because either the admin toolbar is modifying the margin or there is a rule specifically for being logged in that assumes the toolbar but you don't have it enabled.


Is it possible to use a sort of constant or a custom token in the rewrite section of a views field?

If I'm understanding the question properly, you can either use a hidden field on a node to create a node specific value which you can rewrite as a link if desired, or create a Global:Custom Text where you can include whatever static or variable data you desire, so long as the fields containing the information are present (visible or not).


Views table doesn't set fields next to each other

I made the excel import input all the fields.
And make a node for every row in the xls file, then i made a extra field with the product name in the xls file so every node could reconize on what tabel they had to add the rows.

bit messy with a lot of tables but the out put works.


How should jcarousel be installed and configured?

From looking at the code you need to put the jcarousel library here:

/libraries/jcarousel/lib/jquery.jcarousel.min.js

This means install the module as usual and then put the library like given above in the folder libraries

But it seems that there is truly a flaw in setup instructions: The module page states like this:

  Download and extract the jCarousel library to libraries folder of
  drupal root. The source code can be found here:

  https://github.com/jsor/jcarousel/releases

  the folder name you create for this will need to be "jcarousel". the
  full path should be: libraries/jcarousel

  and when you are done, the following path will need to be available:
  sites/all/libraries/jcarousel/dist

This is a mixup of D7 and D8 as TO already stated and in addition if you do it like so, the path given in views_slideshow_jcarousel.libraries.yml will not be available.

I created an issue to maybe get this fixed: https://www.drupal.org/project/views_slideshow_jcarousel/issues/3084864


If you have a web server installed on your local network, and you type the IP address in the URL (e.g. IPaddress:port/nameofproject), you should get your Drupal site.
The fact that when you just type the IP, and the port you get the default server page means that your router settings are already working.


Executing a Rule on a user(s) selected from a list

It sounds to me like you need to fetch the user as an entity in Rules, if you have multiple users use a loop. After this you should be able to apply the relevant action. Here is a stab at the Rule (note, this is untested but should point you in the right direction):

Event
- (Whatever trigger/s you want here)

Condition
- Entity is of type: Node
- Entity has field: (pick the user reference field here)

Action
- Loop(for multiple users)
- (Final action you want to take place. Add the new variable here)

Hope that makes sense. See how you go with this and let me know.


Update 1: As pointed out by the OP, Jeff Burnz doesn't only sell his time as a consultant, but actually has a site, AdaptiveThemes.com, where he sells his "adaptive"-themes, but those are D7 only.

Unfortunately I'm not aware of any company advertising such themes yet.
One of the first I would except to see this from is http://fusiondrupalthemes.com/, but nothing there yet.

If you are looking for something more unique, I believe the Drupal 8 Design Initiative owner, Jeff Burnz, sells his time to make themes, and is the author of a number of responsive themes already. Sky, Corolla and the base theme Adaptive theme, which you may want to look into, given the lack of an actual answer to your question.


What to do when you can't upgrade modules?

Major upgrades of modules should not be a problem if the module is still supported. Just do drush up moduleshortname in the CLI (or replace the old code in the module directory with the new if you don't have drush). Updating a module is integrated in Drupal. If you do this manually (drush will do it automatically) just make sure you run Update on your site after updating the module (Update is linked to on Reports->Status Report page if you need to run it). Update should take of all incremental updates of the module, its schema, and the data in the schema, automatically. Unless there are a bug in the code to update the module, there should be no data loss.

Modules that are no longer supported, especially if they're unsupported because they have security vulnerabilities the maintainer did not fix, are a problem.

The first thing to do is to review the unsupported module and the features it brings to your site.  Is this features your site cannot live without?  If the answer is "no", just disable and uninstall it.

If the unsupported module provides functionality you need, try to find some supported replacement for each unsupported module.  If you find a replacement, you need to migrate all data from the old unsupported module to the new one.  If you're not a developer, you may need to hire a consultant to help you with migration.

If you don't find a replacement, and you are a developer, you may consider fixing the insecure module.  If you follow the process for dealing with unsupported projects, and work with the security team, you should be able to fix the problem. The security team is a helpful bunch and may provide some guidance.

As a last resort, you may hire a consultant to fix an insecure module you absolutely need, forking the result as a custom module for your site.

As already described by Darvanen, you need to do all this on a development server first and only repeat the procedure on your production server when you're sure the update did not damage anything. And make a backup before you start, just in case.


Webform: states dropdown vs textbox plain text in case of other country autoswitch?

addressfield module does that perfectly.

What I don't like about it is that it will also show "address 1&2" fields. You can hide those with css.
When you output the field it will show the complete address. You can also hide the parts you don't need with css.


How to prepare directories in private file system?

Ok, I solved it by passing proper flag (for UI):

file_prepare_directory($dir, FILE_CREATE_DIRECTORY);

For using drush command still don't know and failing.


View for selecting an image associated with a node's child node?

Haven't figured out how to make Views return what I want but it seems this works, where I would pass the query the lesson node. But I really want to understand how to make Views produce the desired result!

SELECT *
FROM file f
INNER JOIN tab t on t.field_tab_fid = f.fid
INNER JOIN lesson l ON l.entity_id = t.entity_id
WHERE l.field_lesson_target_id = 672

http://sqlfiddle.com/#!9/dbf63/4


How to allow user to use one exposed filter and select between two views

Usually views with exposed filters use get params fx

example.com/view1?filter_a=search
example.com/view2?filter_b=search

If you create your own form then build the URL bases on input and search type it should work just fine. I don't think it will be possible to do a view selection with exposed filters.


On a multilingual website using i18n, should I set the built-in Drupal English or my custom English as the default source language for strings?

I18N is a beast of a module. I will try to answer this but have no I18N setup on hand, so this is from memory.

As you have probably realised, depending on how things are configured the default language is normally used as fallback when translations are not available. So, keeping this in mind, you would use your U.S English to translate/modify the entries you want, and set it as default. Source language would be set to the original English.

It used to be one would need to export and re-import translations but that is not the case anymore.

There is a warning to heed, ripped from http://drupal.org/node/1279668 (good reference on your topic btw):

  In contrast to Drupal's standard localization system, which always
  translates from English, strings will be translated from the source
  language. By default the source language is the site's default
  language, so changing the default language could break these
  translations. You can set which language is used as the source
  language via Administration > Configuration > Regional and language >
  Multilingual settings > Strings.

As this message states clearly things may break along the way, backing up your data is very important while you are tweaking this.

Another great link for I18N information that has cleared many things up for my multilingual projects: http://hojtsy.hu/multilingual-drupal7

PS:  Much better and simplified I18N support is upcoming in D8, *YEAH! *

Good-luck!


How to hide a form field in hook_node_view()

You can't. hook_node_view() exists only to

  Act on a node that is being assembled before rendering.

It can't be used to alter the node's edit form.

You need to use hook_form_alter() or hook_form_FORM_ID_alter(), to alter form elements e.g.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' && $some_other_condition) {
    $form['some_element']['#access'] = FALSE;
  }
}


How to create text base field without format?

Text (plain, long) field type is string_long.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Plugin%21Field%21FieldType%21StringLongItem.php/class/StringLongItem/8.2.x


Query pager not showing for administrator

Looks like I found the answer. It appears easier (and more efficient) to use the db_select instead, at least for the number of fields I am sorting on. As suspected it was the pager colliding with another pager on the page, although I am not sure what pager this could be. The pager seems to working fine for all users now that I added '->element(0)' to the db_select. Here is some code:

function build_area_table() {
  $header = array(
    'area_name' => array(
      'data' => 'Area',
      'field' => 'n.title',
      'sort' => 'asc',
    ),
    'level_range' => array(
      'data' => 'Level range',
      'field' => 'flr.field_area_level_range_value',
      'sort' => 'asc',
    ),
  );

  $query = db_select('node', 'n')
            ->extend('PagerDefault')->element(0) # fix displaying pager for all users
            ->extend('TableSort');
  $query->join('field_data_field_area_level_range', 'flr', 'n.nid = flr.entity_id');
  $result = $query
    ->fields('n', array('nid', 'title'))
    ->fields('flr', array('field_area_level_range_value'))
    ->condition('type', 'area')
    ->limit(2)
    ->orderByHeader($header)
    ->execute();

  # build the table
  $td = array();
  foreach ($result as $area) {
    $td[] = array(
      'area_name' => array(
        'data' => l($area->title, 'node/'. $area->nid),
        'class' => array('area-name'),
        ),
        'level_range' => array(
          'data' => format_area_level_range($area->field_area_level_range_value),
          'class' => array('level-range'),
        ),
    );
  }

  $areaTable = array(
    'area-pager' => array(
      '#markup' => theme('pager')
    ),
    'area-table' => array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $td,
      '#empty' => 'No areas to display.',
    ),
  );

  return $areaTable;
}

I could probably achieve the same using EFQ, although I can't find an EFQ version of '->element()'. I tried specifying the element via theme like so:

theme('pager', array('element' => 0))

but there would need to be some kind of check based on the user role, as 0 works for administrators but not for other roles and vice versa. Hopefully this can save someone else some time as well!


Where to write public, common, utility functions in Drupal?

As many API modules do, you can place your global helper functions within a dedicated module. (I'll be using MYHELPERMODULE in the following example.)

You then should follow the naming conventions:

function MYHELPERMODULE_startswith($needle, $haystack) {
  // do your magic
}

You can call this function from within all other modules, as long as your helper module is active. To assure it's active, add your helper module as dependency to the .info file of the module that is using the helper function:

dependencies[] = MYHELPERMODULE


Language switcher does not display the correct link to the default language path

I think this happens because the term itself have no multilanguage path. From my experience the only way to have mulitlanguage path to a term is to create them by hand with an URL-Alias or by installing the [Pathauto i18n Taxonomy][1] Module. This helped me a lot


It is because you run Drupal in local; if you uploaded your site to a valid domain or set a virtual host, you get rid of it.

You can set your virtual Host following How to Add Virtual Directory Alias on Apache Xampp. You could also use Acquia Desktop dev2 which handles virtual hosts by itself.


The title mouse-over is translatable. I needed to enable the content type-> edit -> publishing options -> multilingual settings and it works.


Create a node Programmatically having Composed Field

Consider with this example
you created a field as contact with two subfields as mobile(textfield) and home(textfield).

so while creating the node pro grammatically you just have to assign the array of your input to the field,something like below

$contact = array("mobile"=>"1234565","home"=>"789");
$node->field_contact[$node->language][0]['composed'] = $contact;

I have not shared the node_save() as you have mentioned you are able to make it.


It needs to be:

views-view-field--[field-machine-name].html.twig

If you look in Manage Fields, your field machine name is probably field_this_is_field.

Therefore, in your case:

views-view-field--field-this-is-field.html

Note that this is will override for all views that have this field, if you want to only target a specific view use:

views-view-field--[view-machine-name]--[field-machine-name].html.twig


Strict HTML strips CSS classes in a custom block

Default custom blocks in Drupal 8 use the Basic HTML text format. Using either Basic HTML or Restricted HTML will remove any class attributes.

You need to set your format to Full HTML to prevent Drupal from stripping out these attributes.


Views output realname field as a contextual link

Setting the contextual filter to transform spaces to dashes will not make the Realname field in the database contain dashes, so the filter fails. In your url you look for one-two, in the database this is One Two they are not the same and it doesn't work (one-two ≠ One Two).

First make sure pathauto is installed and enabled. It will provide your users with a pretty url. This will make sure every user has a unique path.
If you replace spaces and dashes in the URL as you do now, the contextual filter for these users One Two, One-Two, One'Two will all become one-two even if they are if fact different users. So your results will be mixed up. Pathauto will make sure they become unique; one-two, one-two2 and so on.

Do not rely on simple pattern matching, but use the uid from the instead. Luckily we can hide this entirely from the url by using a View's contextual filter.

Update

It seems I have missed a module requirement; Sub-pathauto (Sub-path URL Aliases).

  The Drupal Path module matches only full URLs when creating
  SEO-friendly aliases. This module extends that behavior by also
  matching known sub-paths and replacing them with their respective
  alias.

  For example, if user/1 is aliased to users/admin, this module rewrites
  the link to the user contact page user/1/contact to use the aliased
  URL users/admin/contact instead.

The is required to properly obtain the UID from the url.

Then create your view as follows:

Use must use the unaliased path for the path. So if your user is at /users/url-safe-realname and your gallery at /users/url-safe-realname/gallery, you enter /user/%/gallery (omit the s in users pathauto adds if using default settings).

For the contextual filter, in the WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED section, check Specify validation criteria, choose user and numeric UIDs.

The result will be a page that has the url-safe realname in the path and shows only content created by the user:


How to get image with image style path to a twig template

It can be done with the help of two additional modules.

Twig Field Value - to get the path to the image and
Twig Tweak - to get the image style version of an image.

Then in your Twig template you would use something like this to get the image style path:

{{ content.field_image.entity.uri.value | image_style('medium') }}

where field_image is the name of the image field.

If you use something like the Media module then your images come from a referenced entity. In that case you could use

{{ file_url(content.field_referenced_entity | field_target_entity.field_image.entity.uri.value | image_style('medium')) }}

and field_referenced_entity would be the media/entity reference field and field_image the name of the image field on the referenced entity. Notice that in the second case the whole path is wrapped in file_url().


Your hook seems to be named as if it was a mobilize one, where it should be named by your module's. something like "my_module_init".


If you want to use mod_rewrite, here's what to put in .htaccess:

RewriteEngine on
RewriteRule ^en/(.*)$ /$1

Btw. this has little to do with Drupal, it is either an Apache thing or a DB thing (depending on how you decide to solve it).


How can i create two register forms for different users?

Use the Profile2 Registration Path module. It can help you in creating as many registering forms as you need. I have used this one.

  This module enables administrators to set unique registration paths per Profile2 profile type.

  Overview

  The Problem

  By default, the Profile 2 module permits you to add fields from chosen profile types to the default user registration form. Unfortunately, there is only one user registration form. Thus, every user will be presented with these fields during registration. If you have two profile types targeted at two different audiences, you cannot have two separate registration forms.

Profile 2 use this module to get different set of fields. While editing the profile you have created, you can check this one.

Unique registration path
Enable unique registration path
Settings
URL path http://ram.site.dev/customer/register


Why are my webform conditionals not always working?

As our native language is Belgian Dutch and we use a comma for decimal separator, I added a simple replacement for comma to dot in webform_calculations.js. This resulted initially in a javascript error for empty fields, and meanwhile the code was reproduced in Drupal's default files. Since only one webform has calculated fields only that form was affected when logged on as user. After correction a new file was generated and strange enough only administrator login used it, so all worked fine, while the user logon kept using the faulty file, even after all cache cleaning (Drupal and browser) and rebuilding.Replaced all files with correct code..
Problem solved.


For Drupal 7, there is Authcache module. In Drupal 8, you could use Dynamic Page Cache from core.

You could also use some JavaScript. If you have random data to display, you could display them all, hidden by default and use javascript to display one of them each time. Or you could use AJAX, request a URL that will return your new block content, on each page refresh. Disable cache for specific blocks has more information that can help you.

If you have multiple dynamic blocks in your website, my suggestion is to use a module, as it will take you less time to implement it. Writing JavaScript for each dynamic block will take you more time, to implement it and maintain it.


Views grouping rows case-sensitive, I need to ignore case

In Drupal 8, this can be done pretty effortless thanks to Twig.
Just override the output of the grouping field with its value plus Twig's built-in uppercase filter (|upper or |capitalize), see screenshot:


You will need jQuery to make this work but it shouldn't be too complicated. Basically the exposed filter acts as the degraded (non-javascript) version as well as giving you all the possible category options.

$('.views-exposed-form .views-submit-button input').hide();
$('.views-exposed-form select').change(function(event) {
  // Clear previous highlights
  $('.highlight').removeClass('highlight');

  // Get the selected category
  var selectedCategory = $(this).find('option:selected').text();

  // Use the category name to find items on the page
  $('.views-field-term-node-tid .field-content a:contains(' + selectedCategory + ')').parents('.views-row').addClass('highlight');
});

I made this example with a view with fields and the "Content: All taxonomy terms (All taxonomy terms)" field limited by taxonomy. If you use a different method of creating the view you will want to change .views-field-term-node-tid .field-content and probably also the .parents('.views-row') which is what gets highlighted.

You'll also probably want an additional selector in front of all the .views-exposed-form selectors in case you add more exposed forms to you sight such as $('.my-view .views-exposed-form')...

I also made this to trigger on the select change, but you could do it when clicking the Apply button (which you would obviously not want to hide then).

If you exposed filter is a multiple select you can add an each() to the end of $(this).find('option:selected') and loop through getting the text and setting the highlight.


Getting site-offline message when trying to drupal_bootstrap from command line

An easy way of writing CLI code for Drupal is implementing your own drush (http://drupal.org/project/drush) commands. Drush itself commes wirh handy example code.


$form['my_element'] = array(
    '#type' => 'textfield',
    '#attributes' => array(
        ' type' => 'number', // insert space before attribute name :)
    ),
    '#title' => 'My number',
    '#required' => true,
    '#maxlength' => 3
);


Turning a query string into an array after using parse_url

You need to use an associative array, e.g.

$pieces['query'] = array('q' => 'hello');

The arguments for l() are in no way related to, or compatible with, the return from parse_url(). To avoid confusion it'd be better to build up a separate options array to pass as the 3rd argument to l().


Drupal 6 : views Exposed Form : rename the label of a field : please how?

ok I came to this :
this looks like it does the job. maybe this could be rewieved by a DOCUMENTED drupal hacker.

function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  // only alter the jobs search exposed filter form
  if ($vars['form']['#id'] == 'views-exposed-form-MYFORMID') {

    // change the text of an exposed field label (BEF checkboxes here)
    $vars['form'][FIELDNAMEasinurl]['#options'][0] = 'a different label in search pages' ;
    $vars['form'][FIELDNAMEasinurl]['#options'][1] = 'than in edit forms' ;
    // this particular field has a common layout not the case here :
    // this will work but not with the BEF checkboxes layout I want
    //$vars['widgets'][FIELDNAMEinternal]->widget = drupal_render($vars['form']['partage']);

    // or the field was rendered by better exposed filters (here cheboxes)
    // search into better_exposed_filters.theme the function call you need (theme_select_as..)
    $vars['widgets'][FIELDNAMEinternal]->widget = theme_select_as_checkboxes_fieldset($vars['form']['partage']);

    // Change the text on the submit button
    // [...]

  }


How to add an image property to an entity?

You need to create an integer property that references the fid column in the file_managed table.

For inspiration, check out the user_account_form() function (the picture element) and associated validate/submit handlers. They show the exact methodology you need to use.


I'm not sure how you're counting, but hook_nodeapi() has 4 arguments, as you said, while taxonomy_nodeapi() has only 3. How they are named is totally irrelevant, only the amount and order counts. PHP doesn't have named arguments, you could also name them in your hook like this: yourmodule_nodeapi($wathever, $you, $want = 0) and it would work. There is however no reason to do it, it only has the potential of confusing someone. :)

The only important part is here is that the third and fourth argument are optional and must have a default value, because they are not passed for every $op.

About &$node, that's not so nice, but not a problem. The & can be left out, which means that $node is not by reference (in PHP4, that is) but it seems that taxonomy_nodeapi() doesn't need that. The other way round would be a problem in PHP 5.3 (adding a & here when PHP doesn't expect one).


Maybe, is this the appropriate Drupal way or is there a more elegant built in solution I am unaware of?

Yes, that's an appropriate "Drupal" way.

The other way is to make it global, and add it to the database settings array in settings.php.

But you're essentially setting the same thing whichever way you do it. If you were to use your method, and then remove that option from the connection afterwards, it could arguably be considered more secure, since you're limiting the time and scope that LOCAL INFILE can be used in.


How do I remove JOIN in hook_views_query_alter()?

you can add field B as a relationship and use as a reference term in your View UI


override date module function for label strings changes

Now I use an Omega sub theme, mytheme. I added to a CSS file, mytheme-alpha-default.css, some styles such as the following:

label {display:none;}
div.some:before {content:"To Date: "; display:block; margin-left: 2.0em;}


Once you had something under that alias, alias is treated as "used" and blocked from reuse.

Search http://example.com/admin/config/search/path (or similar page in 6, if address was changed) and look there for aliases you want. Remove them. Remove aliases with -0. Re-save your node / term / anything. That should do it.


Entity Translation: Translate breadcrumb

You need to add that string(those are not getting translated) into backend, using translate interface- http://example.com/admin/config/regional/translate/translate


How to render Entity Reference fields in the current language

You can use the following procedure for translated fields

Add language in your THEMENAME.theme

function dru8_preprocess_node(&$vars) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['lang'] = $language;
}

And in your node.html.twig to get translated fields

{% if node.field_stories.entity.hastranslation(lang) %}

{{ node.field_stories.entity.translation(lang).title.value }}

{% else %}

No translation

{% endif %}

Thus in your case you will need

{% for location in node.field_locations %}

      {{ location.entity.translation(lang).title.value }}
       {{ location.entity.translation(lang).field_sub_title.value }}

 {% endfor %}


How do I remove comments from an existing webform?

No need to do either; you can edit any existing webform and toggle the Comment settings menu to Hidden on each published form.