I've had pretty good results previously with SmartIP, and now there is Rules integration which can react to which country the user is in.

So you should be able to set a Rule similar to the following psuedo-rule:

  EVENT:

  Page is going to be viewed

  CONDITION:

  Page is: Front page
  IP Address is in country: whatever country you want

  ACTIONS:

  Go to page: YOUR COUNTRY SPECIFIC LANDING PAGE

I know you said you were new to Drupal, so you can find some really useful Rules tutorials at NodeOne: Learn the Rules Framework.

EDIT

I've just twigged you said you want it to the province level rather than country (sorry, that was glaringly obvious - my fault), so you might be looking at some custom code.

Last time I used it, I used SmartIP to get the latitude and longitude of the user, and then the Location API for the nitty gritty.

You should be able to combine this with hook_init() and drupal_goto() to redirect the user to the relevant page.


drupal moving from local host to live server - error

When creating database exports, the tables are usually locked to ensure that there are no attempts to access or change data within the tables while they are being exported and imported. Those locks will usually be released at the end of the import process. That obviously did not happen for your database.

Most likely your database import in phpmyadmin timed out and did not complete the import process. Check the tables available in phpmyadmin and see if there are the same number of tables as on your local server. If the data appears to be properly intact on the production server, then you will need to manually unlock the tables.


I build a workaround. I created a custom path in drupal that redirect to the external image url like /image/{img-id} . If anyone find an answer on the main question please post.


Please visit to the permission page- /admin/people/permissions page and scroll down to check menu permissions for administrator and allow the checkbox to create and edit menus, check the checkbox for Administrator menus and menu items. It is checked by default, but in your case you can verify it.
Also I have seen your localhost link has a missing foldername, should be like this-
localhost/foldername/admin/structure/menu/item/8/edit?destination=/admin/structure/menu/manage/account


How to get my custom 404/403 pages to work with Bootstrap?

You're using $vars instead of $variables (per conversation in IRC).


How to create a view of hierarchical taxonomy terms and their nodes?

You can do it using the grouping fields feature inside Views.

Create Views listing your nodes (titles), add a Field showing terms they're tagged with (sub-term).

Then add a Relationship for that same Field (the Taxonomy term reference Field). Add another Relationship to introduce Parent term, use the first Relationship here.

Now add another Term name Field and set it to use the second Relationship, this way the Field will show the first level Taxonomy hierarchy for a node.

Now edit your Format settings and set the Grouping field Nr.1 to use the Parent Field, and set the Grouping field Nr.2 the usual (sub-term) Field.

If you need further control of the output you can overwrite to change HTML, and use CSS to emphasize the hierarchy visually.


In my opinion, the most elegant solution would be to leave the original values and to define how you operate with them (adding, substracting, etc.) at the Aggregator Plus level, but I am not familiar with that module, and I don't know how easy it would be to extend it.

If you want to modify the value of these fields before saving the node, there are at least two possibilities I can think of:

Using Rules (it involves creating some custom PHP code). The following example (using increment instead of changing the sign) can give you a hint: https://www.drupal.org/node/1389074
Creating a custom module and implementing hook_node_presave(), in order to modify the fields before they are written to the database.

Hope that helps,


How to ignore the first argument in view contextual filters?

There is a specific contextual filter called "Global: Null" that you can employ to ignore a path part and leave the query unchanged. You will have to reorder the filters so that Null is in the right position (in your case, the first, since you want to ignore the first % of the path). See the screenshot:


According to the docs I found here commerce_product_load_by_sku($sku) will return a $product object and one of the properties is product_id.

$product = commerce_product_load_by_sku($sku);
drupal_set_message($product->product_id);

The product object looks something like this:

[product_id] => 5
[sku] => EX151
[type] => class
[language] => und
[title] => Example Product
[uid] => 1
[status] => 1
[created] => 1316634672
[changed] => 1316639451
[data] =>
[commerce_price] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [amount] => 12500
                        [currency_code] => USD
                        [data] => Array
                            (
                                [components] => Array
                                    (
                                    )

                            )

                    )

            )

    )


Remove nodes individually from Solr Search index

That's exactly what I wrote the module for. There's a release now and I moved the module to Apache Solr Node Exclude because I botched the project creation the first time.


How to delete Duplicate Nodes based on title?

You can achieve that by Remove Duplicates module

This module helps the administrator to easily remove duplicate nodes according to one of the node fields.
Features
The duplicate nodes found are permanently removed. It can be very useful with Drupal Feeds module (Feeds).


This sounds like the necessary JS file is not being loaded.  Check Firebug or Developer Tools, etc to see if collapse.js is being added to the <head> of the page.  The file can be found at YOUR_DRUPAL_ROOT/misc/collapse.js


How to convert string count into number?

Drupal doesn't provide any conversion of value in "Math Expression" field. So we need to fix it in another way, for example following these steps:

Add two new columns "string count" and  "field_number" same as previously added, excluding

When add fields tick "Exclude from display" checkbox
Select "Plain Text" to "Formatter" dropdown

After it, edit "Math-Expression" field, in "Expression" textarea write your mathematical expression with that newly added fields, e.g. [string_count_1] - [field_number_1]


That will work, but here is how I would do it (in D7). You can set up the ajax callback server side like this:

$response = array('value' => $condition);
drupal_json_output($response);
drupal_exit();

Then your value will be available as data.value in your success callback:

$.ajax({
  url:example.com/some/path
  success:function(data) {
    alert(data.value);
  }
});


Wrapping content in anchor tags with CKEditor

I found a solution. As @Clive said CKEDITOR.dtd.a.h2 = 1; and CKEDITOR.dtd.a.h3 = 1; is the solution.
These need to be declared in a my_module.module file:
function my_module_editor_js_settings_alter(array &$settings) {

  foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
    if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
        $settings['editor']['formats'][$text_format_id]['editorSettings']['customConfig'] =
        base_path() . drupal_get_path('module', 'my_module') . '/ckeditor_config.js';
}
  }
}

And then we create a file ckeditor_config.js:
CKEDITOR.dtd['a']['h2'] = 1;
CKEDITOR.dtd['a']['h3'] = 1;

Doing this we can wrap h2 and h3 elements with an anchor tag and CKEditor is not going to modify it.


how to have a another page.tpl.php file in drupal with different regions and blocks?

If your path to the register page is www.example.com/register-now then you only need to name the page template file appropriately and Drupal should do the rest, you shouldn't need to add anything to template.php.

From what you've written, the name of the page template file is wrong. It needs to be renamed to: page--register-now.tpl.php (notice the underscores turned to dashes).

After you rename the file (usually after adding any additional template files), make sure to clear all caches from admin/config/development/performance.

EDIT: If your page is a node, you can't use the Alias path in the template file, it actually has to be the internal path to the node, e.g. page--node--123.tpl.php where 123 is your node's ID.

  The rest are based on the internal path of the current page. Do not confuse the internal path to path aliases which are not accounted for.

See here


Using REST to create user with CAS username

Answering with the workaround I used. It is far from ideal, but works. It relies on having access to the DB of the client site. This uses D7 rules with the php-filter module. It would be much more elegant in it's own custom module.

The site sending the POST request uses sql to update the authname table on the site receiving the POST request. The created user then has a cas-username.

Below is the code for the rule action - creates the POST request, then alters the DB.

// Generate random password
$bytes = random_bytes(10);
$pass = bin2hex($bytes);

// data for user fields
$data = array(
  'name' => array(
    'value' => '[account:name]'
    ),
 'mail' => array(
   'value' => '[account:mail]'
 ),
 'status' => array(
   'value' => 1
  ),
 'pass' => array(
   'value' => $pass
    )
  );

// POST code
$data_string = json_encode($data);

// POST with cURL
$url = 'https://example.com/restendpoint';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$response = curl_exec($ch);

// Get UID from response
$newuser = json_decode($response, true);
$newuseruid = $newuser['uid'][0]['value'];

// DB update
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO authmap (uid, provider, authname, data)
VALUES ($newuseruid, 'cas', '[account:name]', 'N;')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

curl_close($ch);


You should be able to create a page--user--reset.tpl.php template in your theme directory alongside any other page reset templates and just include the content region inside there.  More information about template and theme hook suggestions can be found here (or at least after drupal.org comes back from its upgrade :) but the basic idea is to override the internal path of user/reset/../.. and Drupal is smart enough to ignore the rest of the path and just use the template given the base here.


Here is code tested to work on a minimal install with nodeblock. It's well commented but to recap: get the node displayed in the block, get the term, use one the term's field as css class.

// change mytheme to your theme's name
function mytheme_preprocess_block(&$vars) {
  // don't do anything if it's not a nodeblock block
  if (empty($vars["elements"]["#node"]) || !is_object($vars["elements"]["#node"])) {
    return;
  }

  // get the node object, already loaded
  $node = $vars["elements"]["#node"];

  // get the linked term's id (change field_term to yours)
  $tid = $node->field_term[LANGUAGE_NONE][0]['tid'];

  // load the term fully to get access to its fields
  $term = taxonomy_term_load($tid);

  // turn one of the term's field into a css class (change name to any field)
  $css_class = drupal_clean_css_identifier($term->name);

  // add the css class to the list of classes for this block
  $vars["classes_array"][] = $css_class;
}


How do I update a Drupal distribution to a newer version?

With drush for commons 7.x you can do:

drush up drupal -y
drush dl commons -y
drush updatedb -y


What do you set in the "column" field for adding a minimum words validation via the Field Validation module?

This may help you out....

Field > Appropriate column value

Normal field > "value"
Taxonomy field > "tid"
Date field > "value" and "value2"
Node reference field > "nid"
User reference field > "uid"
Link field > "url","title","attributes"


Typically Nodes are content. Permissions in a webapp are typically not content. Content is a piece of factual text, an image, an uploaded pdf.

It sounds like you want to look at the Organic Groups module.


Use Disable Message Module. and set permission for user roles you want.

  Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.


Global Combine fields filter (Views) does not include Referenced Entities (Content Type)

This is not possible with Global Combine fields filter at the moment, see also the feature request for the Entity reference module.

This is possible though with the Views filters populate module. You can use any field of a referenced entity or field collection of which you setup the relation with in your view.

Howto :

Like the instructions on the module's page describe, first step is to
add the fields you want to search on in an OR combination of filters.
With Drupal6 that would have been by using the 'Views Or' module; with
Drupal7 this is just a filter group with internal operator set to
'Or'. These individual filters should  not be exposed.
Then these filters can be exposed as one input by adding the module's provided filter called 'Populate filters', found on the 'Global' section. Expose it and check the filters you added in the Or group.


There is two simple way to do it I think :

Use Vocabulary module which gives you the taxonomy/vid page.
Or Use views to create your page. Create a taxonomy type view and add Taxonomy vocabulary: Vocabulary ID or Taxonomy vocabulary: Machine Name as argument.
If you want to display the nodes related to vocabulary then I think you need to use Views Field View with 2nd option.


Is it possible to add multiple fields within a single component?

For one of my projects I spend almost whole week trying to find similar functionality it turns out that you cannot render the input of two fields as one entry from webform result due to the fact that webform creates separate database entry for every field. I solve my problem by just creating multiple fields value_1 value_2 and so on and when exporting result concatenate them in Excell (stupid I know :-) and does not work for your case) . There is module Webform Add More but it only use the same aproach but hides the extra fields and shows them when needed. If you are willing to switch from webform you can try EntityForms this way you can use regular Drupal fields to get entered values and embedding Entityforms on Nodes using Entity Reference


Create a field to type in name of body class

Johan, if the only thing out of sync between your live and local environments are the node nids, you can do this with css like so:

/* this will target both and will work on both environments if the other nid
   does not exist in the other environment */

.node-page-1521,
.node-page-1497 {
  /* whatever CSS you need here */
}

as Drupal puts the class node-page-NID in the body of each page created for a specific node.  If the "other nid" exists in the local or live site, then you will have to get a bit fancier, but this does show that Drupal can target specific node pages.

Another way would be to use hook_preprocess_html() a custom module or theme, eg, something along the lines of:

function YOURMODULE_OR_THEME_preprocess_html(&$variables) {

  if (isset($variables['node']) && $variables['node']->nid == THE_NID_YOU_WANT) {
    $variables['classes_array'][]='SPECIAL_CLASS';
  }

}

Just realize the above snippet is dull ax; eg, you would probably want to do something better than just hard coding a nid in there, eg storing it in a variable specific to the machine (look into variable_get() and creating an admin form for your theme/module).

If it is something else, eg, you want to have a field that allows the user to somehow specify something special in the display about this (and other similar nodes), you can certainly do that as well above, eg, look at that field instead of the nid and then add a class if it has a certain value.


Do I need a cron task for processing a queue?

When Drupal runs cron tasks, it automatically handles any cron queue defined from modules, in drupal_cron_run(); first hook_cron() implementations are invoked, and then the cron queues are emptied.

Inmplementing hook_cronapi(), you can add an entry for another function handling the cron queue of your module.

function mymodule_cronapi($op, $job = NULL) {
  $items = array();

  $items['queue_users_for_synch'] = array(
    'description' => 'Queue all user accounts for synching.',
    'rule' => '0 3 * * *', // Run this job every day at 3am.
    'callback' => 'mymodule_queue_all_users_for_synching',
  );

  $items['clean_queue'] = array(
    'description' => 'Clean the queue for the user synching.',
    'rule' => '0 4 * * *', // Run this job every day at 4 AM.
    'callback' => 'mymodule_clean_queue',
  );

  return $items;
}

function mymodule_clean_queue() {
  $queues = module_invoke('mymodule', 'cron_queue_info');
  drupal_alter('cron_queue_info', $queues);

  // Make sure every queue exists. There is no harm in trying to recreate an
  // existing queue.
  foreach ($queues as $queue_name => $info) {
    DrupalQueue::get($queue_name)->createQueue();
  }

  foreach ($queues as $queue_name => $info) {
    $function = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      $function($item->data);
      $queue->deleteItem($item);
    }
  }
}

The alternative is letting Drupal handle the cron queue for you, but that happens when Drupal cron tasks are executed. If you want to empty the cron queue of your module more frequently, you can only add a new cron task handled by the Elysia Cron module.

The Elysia Cron module handles the cron queues in elysia_cron_run(); this function is being invoked from elysia_cron_cron() (an implementation of hook_cron()), drush_elysia_cron_run_wrapper() (a Drush command callback), and from its own cron.php. If you followed the instructions in the INSTALL.txt file (in particular in "STEP B: CHANGE SYSTEM CRONTAB (OPTIONAL)"), and replaced any invocation of http://example.com/cron.php with http://example.com/sites/all/modules/elysia_cron/cron.php, the Elysia Cron module should be already handling the cron queues. The code I suggested could be used to speed up handling the cron queues used from your module, if there is effectively the need of doing so.

// This code is part of the code executed from modules/elysia_cron/cron.php.
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_override_server_variables(array(
  'SCRIPT_NAME' => '/cron.php',
));
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  if (function_exists('elysia_cron_run')) {
    elysia_cron_run();
  }
  else {
    drupal_cron_run();
  }
}


Programmatically change webform confirmation page

When completed I want the user to be returned to this page with no message

  I just need to force the confirmation redirect to reload the current
  page.

The following should do the trick:

Better yet:


Registration form customization to meet COPPA and similar "under 13" laws?

Simply go to Home > Administration > Configuration > People > Account settings and add fields you need. Use Conditional Fields module to conditionally show a text box.

Now you need to use Rules. See registration rules post for example - what you want is to automatically enable account if checkbox is empty, and send email if checkbox is checked. How to do the very last thing, and how to process verification link, is a material for a separate question.

Questions that may help with further development a bit:

How do I Send HTML Emails via Rules?
how to create rules to send email notification for node reference content?
and more...


How are current anonymous users calculated?

Have a look at what's written in Comment nr 5 of issue nr 799262, ie:

Basically, the anonymous user count in Drupal core's "who's online" block counts how many sessions are stored in the database, minus the number of authenticated sessions.
If you haven't correctly configured PHP to periodically cleanup the active sessions, the table will continue to grow. I just cleaned one today with ~75,000 old anonymous sessions. This not only causes confusion in the who's online block, but also has a severe performance impact on your site if it's mildly busy.
This article shows you what you need to put in settings.php to ensure your anonymous sessions are being cleaned: https://techcommons.stanford.edu/topics/drupal/sessions-table-cleanup


The page title in Drupal doesn't have a machine name. If you want to add one, you can use Safeword module. How to do that: after installing the module, add a new field to that content type where you want to add the machine name; select field type as "Machine name from node title" and widget as "Machine name". After doing this, save the content type and you'll have the machine name for node title.


In nodereference field of a content type, Is it possible to show the content type name added with the autocomplete results?

I created a new custom Module nodereference_patch with below hook

/*
 * Altering nodereference/autocomplete menu using menu alter
 */
function nodereference_patch_menu_alter(&$items) {
  $items['nodereference/autocomplete']['page callback'] = 'nodereference_patch_new_nodereference_autocomplete';
}

Then, I copied the nodereference_autocomplete function into your custom module, changing it's name to nodereference_patch_new_nodereference_autocomplete.

Then I changed this line:

$matches[$row['title'] ." [nid:$id]"] = '
'. $row['rendered'] . '
';

to

$matches[$row['type'] . " | " . $row['title'] . " [nid:$id]"] = '
' . $row['type'] . " | " . $row['rendered'] . '
';

I copied _nodereference_potential_references function from nodereference.module to custom module and renamed it as _nodereference_patch_potential_references

Then I changed the following line as

$references = _nodereference_potential_references_standard($field, $string, $match, $ids, $limit);

to

$references = _nodereference_patch_potential_references_standard($field, $string, $match, $ids, $limit);

I copied _nodereference_potential_references_standard from nodereference.module to custom module and renamed it as _nodereference_patch_potential_references_standard

Then I added 'type' element to $references[]. ie) changed following array from

$references[$node->nid] = array(
    'title' => $node->node_title,
    'rendered' => check_plain($node->node_title),
);

to

$references[$node->nid] = array(
    'title' => $node->node_title,
    'type' => $node->node_type,
    'rendered' => check_plain($node->node_title),
);


Just general ideas, not a solution...

I would check out the entity reference module (https://drupal.org/project/entityreference) as a starting point, to get an idea of how it works, so you can plan your project with this in mind. Entity reference makes it easy to link one entity to another, then build views to generate lists of related items. Entity views attachment (EVA, https://drupal.org/project/eva) can help you attach views of related items to entities. (i.e. you could display a list of letters as a view attached to a person)

You may also want to check out the addressfield module (https://drupal.org/project/addressfield) especially if you have international addresses to work with. It's a little tweaky, since it handles the entire address as a single field, but it saves you the trouble of implementing several fields to catpture each address.

From your description, it seems like you would want at least these content types: letter, person, address (or place). But it's hard to say for sure without knowing your complete vision.


The code you are using above is for Drupal 7, not Drupal 6. In Drupal 6, it would be the following one.

function blue_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      // code from your blue_block_info()

    case 'view':
      // code from your blue_block_view()

  }
}


Pressflow + CDN, node access counter not updating

Finally found a working solution.

Module - http://drupal.org/project/jstats gets the job done, make sure to copy the jstats.php file into root.

Thanks


How to locally export config from a remote environment?

Edit: Turns out drush has a config-pull command to handle exactly this:

https://drushcommands.com/drush-8x/config/config-pull/

However, it doesn't work with config_ignore as far as I can tell.

The original answer for posterity:

I've found that this bash command does the trick (on Mac OS X):

yes n | drush @site.env cim sync --preview=diff | \
sed -E 's/([\-]{3} ).*(\/.*.yml)/\1a\/config\/sync\2/' | \
sed -E 's/([\+]{3} ).*(\/.*.yml)/\1b\/config\/sync\2/' > cim.patch && \
interdiff -q cim.patch /dev/null > cex.patch && \
git apply cex.patch && \
rm cex.patch cim.patch

We use the preview argument of drush config-import (passing in 'n' when it prompts to import), clean up path names with sed, reverse the patch from import to export, and finally apply it and clean up. Note that you have to be on the same git branch as production.

With drush 9, the output and yes functionality changes a little, so you can instead use:

drush @site.env cim sync --no --preview=diff 2>/dev/null | \
sed -E 's/([\-]{3} ).*(\/.*.yml)/\1a\/config\/sync\2/' | \
sed -E 's/([\+]{3} ).*(\/.*.yml)/\1b\/config\/sync\2/' > cim.patch && \
interdiff -q cim.patch /dev/null > cex.patch && \
git apply cex.patch && \
rm cex.patch cim.patch


Client needs Ubercart member sign up function, but there is error with edit/option_prices

If there is a problem it sounds like it's an issue with the menu tab links being generated for your nodes; node/test/edit/option_prices isn't a valid path, it should should be something like node/$nid/edit/option_prices.

The module enables that path if the UC Attributes module is enabled. It sounds like you've installed that module so I would substitute "test" with whatever product NID you're trying to test. Once you've confirmed it's working there, you can troubleshoot why your tab link is generating a bogus path.


I solved the problem by enabling the Disable SQL Rewriting option in Query Settings in my views. This action might have some security implications so lets hope for the best for now.

You can find the discussion here.


How to set the facet block title to the currently applied filter?

I'm not sure about faceted, bacause i've never used it before.
But if page are reloads on click you can use hook_block_view_alter hook the common workflow of using this - get param from url and replace title depends on it.

If page doesn't reloads you can use ajax command, or something similar to achieve what's you need.


Using the jQuery Update module throws the "F is undefined" error

I use jQuery Update on every site we make.

One typical problem it has, is that it can cause problems on admin pages.  The issues for the module has a patch (http://drupal.org/node/775924#comment-3010750) that fixes the problem.  You can also edit this to use any version of jQuery you want, as long as you place the proper versions in the module folder.


How do I set a content entity field as required?

You need to use the ->setRequired(TRUE) option on the field. IE

$fields['source_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Thingy'))
      ->setDescription(t('Pick a thingy'))
      ->setSetting('target_type','thingy')
      ->setRequired(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'options_select',
        'weight' => 5,
      ))
      ->setDisplayConfigurable('form', TRUE);

You will also need to uninstall and then reinstall your module to have the change reflected in the database before this will work.


How to resolve the error about 'A partially-completed form was found'?

Since "deleting partially filled nid in webform submissions table" (as in your question) seems to not solve your issue, you may want to have a look at comment nr 2 in issue 2560907, which states:

  A webform node is being displayed on that page and there is a draft submission for the current user. You don't have to find the id -- the form will be displayed, unless theming or another module is preventing it.


What Plugin goes "type" of a FieldStorageConfig type?

My Bug was actually in

entitity_get_form_display()->setComponent('field', array(
type=>my_field_type))

it should have been

entitity_get_form_display()->setComponent('field', array(
type=>my_field_type_widget))


Drupal 7 Views, Nested User > Content views filter by exposed date

In the outer view, add a relation
Via this relation add the field filters (for example - field_date)
In the outer view field which references the inner view you can pass arguments -> field_date.

In the inner view -> add contextual filters, which will be field_date.

I hope this gives you some direction.


Unexpected error during import . . . plugin does not exist error on drush config import

I was able to solve this with an update hook.  By deleting the config and then reimporting it this way, it doesn't trigger the unexpected error.  You need to run "drush updb" first, before "drush cim" for this to work.

use Drupal\Core\Config\FileStorage;

/**
 * Reimport filter.format.full_html and filter.format.basic_html.
 *
 * This is to remove the dependency on the examplefilter filter
 * which is being deleted.
 */
function mymodule_update_8003() {

  $config_ids = [
    'filter.format.full_html',
    'filter.format.basic_html',
  ];

  foreach ($config_ids as $config_id) {
    Drupal::configFactory()
      ->getEditable($config_id)
      ->delete();

    $config_path = config_get_config_directory('sync');
    $source = new FileStorage($config_path);
    $config_storage = \Drupal::service('config.storage');
    $config_storage->write($config_id, $source->read($config_id));
  }
}


Show a field in table if current user is node author

Two modules can help you do that. Note that you'll likely choose one of these two modules. they aren't dependent on each other. They can both help you get what you want in different ways.

Views PHP
Computed Field


How to set the user must login as member before purchase?

Use the Commerce Checkout Redirect for implementing this:

  This module redirects anonymous users to a page where they can login or create a new account when they try to checkout.


Filter view by taxonomy terms of current user

It's the same process as D7 (see related thread)

But all you need to do is add a relationship to the taxonomy term and then add a contextual filter with the Term ID set as the fixed value.


Multiple path aliases based on taxonomy term

You can use pathauto module.
After installing the pathauto module, please configure the path of article content type from here admin/config/search/path/patterns.

Note:
To use pattern require token module. Then use like following pattern:

categories/[node:field-token-of-term-reference-field]/[node:title]


View modes are configuration entities.

Like anything else that is a config entity, it's very simply to put into "code": Make it default configuration. Create it in the UI, do a configuration export (admin/config/development/configuration/single/export), and then place core.entity_view_mode.$entity_type.$view_mode.yml file into config/install inside your module.

The view mode will then automatically be imported and created when the module is installed.

Note that it's not hardcoded then, so a user could remove it. If you want to prevent that, you can implement hook_entity_view_mode_access() to deny delete access to your entity for everyone.

By default, you will have a problem re-installing the module because it will not remove that view mode when you uninstall the module and display an error when you install it again. There are two ways to fix that:

Move the config to config/optional instead of config/install. Then it will only be created if it doesn't exist yet.
Add an enforced dependency on your module, which will ensure that it will be removed when the module is uninstalled. Note that this only works if you had this in place when you installed the module the first time.

Like this:

  dependencies:
    enforced:
      module:
        - yourmodule


How to send an e-mail to a user selected in a webform via a user reference field?

Even though your question doesn't say so (yet), I'm assuming (as per your "... I have a form component of the users, that is a user reference field...") that you're also using the Webform References module. Some details about that module (from its project page):

  Provides a webform component that can reference a node/term/user in Webform. It provides "Select List", "Autocomplete", "Checkbox" and "Radio" as widget.

If you also have the Webform Rules module enabled, then it is possible to create a rule (using Rules), which does what you're asking for. Here is an export of a rule that will send an eMail to the eMail Id of the referenced user:

{ "rules_email_submitted_webform_to_referenced_user" : {
    "LABEL" : "eMail submitted webform to referenced user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form_id" ],
          "selected_webform" : { "value" : { "webform-client-form-191" : "webform-client-form-191" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform submitted contains the field labeled \u0022[data:demoform_userref-title]\u0022 which has value \u0022[data:demoform_userref-value-raw]\u0022." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_userref-value-raw]" },
          "PROVIDE" : { "variable_added" : { "referenced_user_txt" : "Referenced user" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "referenced-user-txt" ] },
          "PROVIDE" : { "conversion_result" : { "referenced_user_uid" : "Referenced User Uid" } }
        }
      },
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "referenced-user-uid" ] },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "drupal_message" : { "message" : "referenced_user_txt: [referenced-user-txt:value] AND referenced_user_uid: [referenced-user-uid:value] AND\r\n\r\nUser fetched: uid=[user-fetched:uid] name=[user-fetched:name] mail=[user-fetched:mail]" } },
      { "mail" : {
          "to" : [ "user-fetched:mail" ],
          "subject" : "Hey [user-fetched:name] you have new mail ...",
          "message" : "The webform submitted contains these fields:\r\n\u003C\/ul\u003E\r\n\u003Cli\u003Ethe field labeled \u0022[data:demoform_title-title]\u0022 which has value \u0022[data:demoform_title-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_text-title]\u0022 which has value \u0022[data:demoform_text-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_number-title]\u0022 which has value \u0022[data:demoform_number-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_option-title]\u0022 which has value \u0022[data:demoform_option-value-raw]\u0022.\u003C\/li\u003E\r\n\u003C\/ul\u003E",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about this rule (prior to trying to import this rule in your own site, make sure to adapt (rename) what's needed to fit your case):

The form ID I'm using is 191.
All form components have machine names starting with demoform.
The machine name of the reference user is demoform_userref.

The Rules Event and Rules Condition should be straight forward, though the actual Rules magic happens in the Rules Actions:

Show a message on the site (just for demo purposes).
Add a text variable (to capture "some" webform data about the selected user, has to be text ...).
Convert a variable from a text to an integer variable (we need an integer for the next Rules Action, text won't work ...).
Fetch an entity by ID (the integer variable, to fetch the user with that ID).
Show a message on the site (just for demo purposes).
Send an eMail (to the eMail ID from the fetched user).

Demo

After submitting my demoform, the messages shown are like so:

The webform submitted contains the field labeled "User" which has value "123".
referenced_user_txt: 123 AND referenced_user_uid: 123 AND User fetched: uid=123 name=Pierre.Vriens mail=pierre.vriens@somewhere.com

Moreover, an eMail got delivered to pierre.vriens@somewhere.com ...

Subject:

  Hey Pierre.Vriens you have new mail ...

Message:

  The webform submitted contains these fields:
   * the field labeled "Title" which has value "Some title".
   * the field labeled "Text" which has value "Some text".
   * the field labeled "Number" which has value "7".
   * the field labeled "Option" which has value "C".


How can I reorder active menu items programmatically?

You need to use hook_menu_alter.

Make sure you declare the function with the & in front of items argument, this is what allows the function to modify the $items array passed to the function:

function MYMODULE_menu_alter(&$items)

In your function you can access every menu item in an array structure like so:

   $items['node/%/edit/schedulenew'] = array(
            'title' => 'Schedule1',
            'access callback'=>'user_access',
            'access arguments'=>array('view cssswitch'),
            'page callback' => 'cssswitch_schedule',
            'page arguments' => array(1),
            'type' => MENU_LOCAL_TASK,
            'weight'=>4,
        );

If you just redefine the 'weight' property, it will allow you to re-order your menus.

Be sure to clear your cache after each menu changes, or go to the menu page, load the menu edit page and save it, this also rebuilds the menu.


drupal http_request give solr parse exception

i found out I have had to urlencode the bracket part of my url for it to work

urlencode('(7000 OR 7001)'


As you can see in the documentation:

  $expire: One of the following values:

  CACHE_PERMANENT: Indicates that the item should never be removed unless explicitly told to using cache_clear_all() with a cache ID.
  CACHE_TEMPORARY: Indicates that the item should be removed at the next general cache wipe.
  A Unix timestamp: Indicates that the item should be kept at least until the given time, after which it behaves like CACHE_TEMPORARY.

Please note - it's not "at most". It's "at least". So your code works just the way it is to be expected. If you want to force-expire it, use cache_clear_all( __FUNCTION__ , 'cache_block'), for example in hook_cron() or at the beginning of your code.

Also note that it looks like you are re-saving cache at each use. That's not an usual thing, saving data is CPU and HDD expensive. It costs more than not caching at all. So consider only setting cache if it was not found in the first place, and needs to be regenerated. If cache is already set, let it expire and don't set it again.


It can be attached to whatever you like - the important thing is that you render it.

So you could quite simply use:

$foo['#attached']['css'][] = drupal_get_path('module', 'MODULE') . '/MODULE.css';
drupal_render($foo);

Or stick it in a var like you're already doing:

$variables['SOMETHING']['#attached']['css'][] = drupal_get_path('module', 'MODULE') . '/MODULE.css';

And in the template:

drupal_render($SOMETHING);

It works because drupal_render() unconditionally calls drupal_process_attached() on any element it finds with an #attached property, regardless of what you're doing with the result of the render (or if there's even anything to render).


How to prohibit access to a view if the user is not the user in the account path?

The submitted by is not an access will not do it
I will post all the steps below since I am not sure what you have done (your view is translated in french)
Basically you will have a view of webform submissions with relationship to the user and filter the current user
creating the view

adding the user relationship

adding the current user filter

the finished view with important parts highlighted

the current logged in user should see ONLY their submissions NOW


How can I display seveal menus with different classes

Why not just add each menus through block layout interface? visit admin/structure/block.

You will get unique id each.


There is more easy way to do this: Use the module functions.

paragraphs.module contain these functions:

paragraphs_bundle_save()  to create and update bundles
paragraphs_bundle_delete() to remove bundles
paragraphs_bundle_load() to get the list of bundles or load a bundle

/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Create new Bundle.
  $bundle = new stdClass();
  $bundle->name = 'Test Bundle'; // user friendly label
  $bundle->bundle = 'paragraphy_test'; // machine name
  $bundle->locked = 0;
  $status = paragraphs_bundle_save($bundle);
}


Why can't I change anything in hook_node_view_alter?

hook_node_view and hook_node_view_alter are only going to give you control over the inner content of a particular $node that you may be viewing. Such as the inner content when going to www.mysite/node/2

Now if you have additional "blocks" or maybe as you called them "side panels", these are not a part of the $node array and thus cannot be changed in hook_node_view or alter. If the side panel is indeed a block, then you can change it's output with hook_block_view and hook_block_view_alter. Among other things depending on what you are trying to do. The process is to find the block ID, and target it inside your hook. However I may be wrong, because it really depends on what the block is.

You will need to provide a printscreen showing exactly what you are talking about if we are going to figure out the right direction you should take on altering it.

I would suggest downloading the "devel" module, enabling it, then look at the ouptut from hook_block_view_alter and see if it's what you're looking for.

function mymodule_block_view_alter(&$data, $block) {
  dpm($block); //make sure the module devel is installed and enabled for this function
}


How to Install multiple version of Drush?

In your .bashrc:

alias drush5=/path/to/drush5/drush
alias drush6=/path/to/drush6/drush

With this, drush5 will give you Drush 5, drush6 will give you Drush 6, and drush will give you whichever of these appears first on your $PATH.

Rename your aliases to suit.


Is there any way not to use the Drupal Image-style system?

The Drupal image style system let you upload an image in whatever form you choose, and the image style will transform it into the size, shape, etc. of the selected style according to preset rules that you find in the configuration for image styles.

One of the benefits of the Image style system is that it allows reuse of images in different styles.  You just upload the image once, and than you can use a thumbnail size version in the teaser, and a large size in the main article - or two different styles of the same image in two different nodes, etc.

There is one folder per style (I believe there are 4 default styles, but you can create and add your own styles if you want to, and this will add more folders below the styles directory).

Drupal does not create a copy of the image for a particular style until that style is requested.  While there are 4 folders, if you don't reuse an image, it will only be created in one style - meaning that there will be two copies of that image on your disk: The original, and the scaled, cropped, whatever, copy that Drupal has created for that style.

In other words, you need to condsider the (IMHO) substantial benefits of Drypal's image style system before you decide to get rid of it.

But if you don't want to use it, you can do without.

However it is a bit more involved than just removing the image style folder.

Basically, what you do is to resize, crop, etc. the image yourself, before you upload it to the site.  Then you create (by hand) a link to the original that you've uploaded from whereever you want to use it.  If you do this with all images, Drupal will never attempt to create a copy for a particular image style and the image style folder will be empty.

If you're sure you're never is going to allow Drupal to style an image, I suppose you can remove the image style folder at this point, but I would leave the empty folder it in place to avoid breaking the site if I at some point forget that I'm not supposed to use Drupal's image styles.

If you think that a lot of unused copies of images are living below the image styles folder, you can flush all (or a subset) with the following Drush CLI command:

drush image-flush

This leaves the file structure below the image styles folder in place, so if a flushed image is requested, it will automatically be recreated in the requested style.


IIS - how to handle file permission problem

Seems like issue is that Drupal is trying to write a temporary file somewhere it cannot write, like in the site's docroot...

Try running below commands using drush and make sure write access is available for temp directories..

~$ drush vget file_directory_temp

~$ drush vget file_temporary_path


How can I render a view on user-profile.tpl.php that includes the user name as an argument in Drupal 7?

use views_embed_view to embed a view:

$views = views_embed_view('VIEW_NAME', 'DISPLAY_ID');
print render($views);

The DISPLAY_ID is typically 'page' or 'block' depending on the displays you have setup in views.

You can build the view with a contextual filter to get all nodes with a user reference.

If you don't need to embed the view in the middle of your user profile you can just use a block output and show that block before or after your user profile.


How to display the term description on top of view

I haven't used Drupal 6 since 2010, so I can't speak to what used to be.

There are a few options here, given the differences in Views for 7/8 vs 6.

You can attach a field in the view header for the term description.
You can create a separate block display, and put that block on any term path.

I usually opt for #2, so I can put the term description and term name in a hero region, and keep the main view output uncluttered. Although you can use TVI in various ways, I stick to creating taxonomy/term/% as the page paths so feeding arguments so it is simple. So for the block, create a contextual filter and feed it the taxonomy term ID from URL.

You could also have the view render the term as a view mode as well, instead of fields. It's pretty flexible.

edit: The reason it shows without using TVI or Views is because the page callback for a term path hardcodes and prepends it: https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.pages.inc/function/taxonomy_term_page/7.x .

That is one of a handful of reasons modules like TVI were created in the first place, so you can arrange your own display(s). Since TVI is injecting a View, it does not hardcode anything into the output:

/**
 * Replace taxonomy page callback.
 *
 * If more or less than one term is given then pass the request off
 * to the original taxonomy module page callback.
 *
 * @param int|object $tid
 *   The term tid or the term object.
 * @param null|int $depth
 *   The shown depth.
 *
 * @return array
 *   The build array.
 */
function tvi_render_view($tid, $depth = NULL) {
  if (is_object($tid)) {
    $tid = $tid->tid;
  }

  list($view, $display, $term, $settings) = tvi_get_view_info($tid);
  // Load metatags if needed.
  if (module_exists('metatag')) {
    metatag_entity_view($term, 'taxonomy_term', 'full', NULL);
  }
  if (is_object($view) && $display) {
    $output = t('There was no content found matching this term.');

    if (isset($settings->pass_arguments) && $settings->pass_arguments == 1) {
      // Pass all arguments to views. Exclude /taxonomy/term.
      $args = array_slice(arg(), 2);
    }
    else {
      $args = array($tid);
      if (NULL !== $depth) {
        $args[] = $depth;
      }
    }

    if ($view->display[$display]->display_plugin == 'block') {
      // If it's a block display, views returns a block array which won't work
      // as a page callback so we need to explicitly set the page title
      // and just return the $block['content'].
      $block = $view->execute_display($display, $args);
      drupal_set_title($block['subject']);
      $output = $block['content'];
    }
    else {
      global $language;
      module_invoke_all('entity_view', $term, 'taxonomy_term', 'full', $language->language);
      $output = $view->execute_display($display, $args);
    }

    return $output;
  }

  // Taxonomy is last resort - used if no standard views are found.
  module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  return taxonomy_term_page($term);
}

This is easily solvable in a few minutes with either solution above.


How to group uploaded documents into folders?

In Drupal, this is probably easier to create a custom content type Document, to which you add a file field.  You can then add a taxonomy term reference field targeting the included Tags vocabulary (in Drupal 7) and then tag the files however you like.  Then, you can create views using the Views module to display the files however you like.  This approach offers a lot of flexibility but will be very complicated to set up your first time.

Alternately, if you have a simple structure, you could create a custom content type Group of documents and attach a file field that allows for unlimited uploads.  Then, you could create a node of the Group of documents content type for each page and upload the files that way.

I didn't describe a way to organize the documents into folders because Drupal doesn't really care about folder structure.  If you really wanted to have a folder structure, it would be better to just upload them via SFTP and let users browse the directories without interfacing with Drupal at all.


Website owners to claim their websites by uploading control file ?

It shouldn't be too difficult to code it:

If you have the website URL and the control file name stored in a node you can use drupal_http_request to perform a GET against the URL and filename.

If you get a status 200 returned the file exists and you can update another field on the node to indicate that the URL has been successfully validated.


What order should configuration import and module updates be run?

Updates must be run before configuration is imported

A pending issue against core will ensure that the code and schema versions match before allowing configuration to be imported.

Problems with config import before updates

An update hook relying on a configuration value could end in a different result than if it were run on the pre-import value.
An update could potentially fail if it tried to create configuration entities that already exist.

Concerns for config import after updates

If an update that introduces a new configuration entity is run first, it will create a new configuration item that will have a differing UUID than the one that is in config.  However, once the config is imported the entity should be replaced with the config version.

There could be a potential problem here if replacing the entity would affect associated content.  For example, if an update migrates content from one field to another, on config import the field would be completely replaced and the content potentially lost.  In this instance the deployment process may need to be adjusted to run the updates on the target environment and export the resulting configuration.


View field with link to excecute action plugin

I'm thinking about setting up a route with a csrf token and an access check on a controller that manually performs the action:

my_module.my_action_callback:
  path: '/node/{node}/my_action_callback'
  defaults:
    _controller: '\Drupal\my_module\Controller\ActionController::my_action'
    _title: 'My action'
  requirements:
    _permission: 'perform my action'
    _csrf_token: 'TRUE'
    _custom_access: '\Drupal\my_module\Controller\ActionController::my_action_access'

In ActionController::my_action I could perform the action programmatically:

\Drupal\system\Entity\Action::load('foo')->execute($data);

I had hoped there was a less complex and more elegant way using an existing view plugin.


How to print a date field value on a page?

You should use Drupal's 'format_date' function.

Example:
format_date(strtotime($entity->field_mydate['und'][0]['value2']) ,'custom','F j, Y');


How do I display highly customized content?

Looks like this is a job better suited for a JavaScript web app (Angular, React, etc.) than using Drupal to render the UI. You can create a dummy module whose only job is to load the JavaScript for your webapp. Then it's all JS from there.

For the back end, assuming Drupal is also powering the data layer, you can use the REST API features of the Views module to send and retrieve data.

Additionally, I wouldn't use block layout for the layout of the site since it's a global layout. This hampers further customization of the layout of the site. Consider using Panels to create dedicated pages that have their own layout. Imagine block layout, but only for a specific page or set of pages.


Display multiple timezone values from a single date/time entry

I guess that could be done using jQuery (or a separate module that does the same) but to me, the easiest way would be jQuery.
So you load your date/time field a second time in your view, "Rewrite the output of this field" so you can give it a different HTML structure and different classes name e.g.

GMT +10:00

Here's a link on how you could do that: getTimezoneOffset via javascript
The great thing with "getTimezoneOffset" is that it accounts for daylight savings time as well.
Example of your Views Field:


Node registration form block - hide if registered

Node registration not providing a function in it's API for that, however you could include the "node_registration\includes\node_registration.api.inc" file and use their internal function that the module use to check for user access for  a specific node.

// Include the file
    module_load_include('inc', 'node_registration', 'includes/node_registration.api');

 if (_node_registration_user_registered($node, $account)) {
    //do something
  }


How to wrap module output with common html?

The only thing I see you could do is to have one commeon theme function and let one module depend on the other (you should specify this in the .info file). If you are going to have more modules with them same requirement you could have a central output module doing the theming.


Redirect HTTPS to HTTP for a bilingual site

I would do the https to http redirect inside of .htaccess. Setting the base_url in settings.php will only fix it after the user clicks on a link. The landing page will still be https. I would use something like this in your .htaccess file:

RewriteCond %{HTTP_X_FORWARDED_PROTO} ^https$ [or]
RewriteCond %{HTTPS} ^on$
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Pre-select a role on user register form and hide from display?

well..after staring at this question and trying a bunch of things on my own I think I stumbled upon the answer. Using HOOK_user_presave did the trick! This helped immensely: https://drupal.stackexchange.com/a/79065/28353

function mandatory_role_user_presave(&$edit, $account, $category) {
global $user;
if(in_array('venue admin', $user->roles)) {
  if($account ->is_new) {
    $roles = user_roles(TRUE);
    $rid = array_search('customer', $roles);
    if($rid != FALSE) {
      $edit['roles'][$rid] = 1;
        }
      }
    }
  }


create contact form block with prepopulated entity references and send email to content author

Consider looking at the Bean module. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

As a bonus, the Bean module also works great in combination with the UUID and UUID Features Integration modules.

On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module.


No need to declare a form element as #type = 'markup', as this is the default type.

$html = 'My HTML';

$form['mymarkup'] = array(
  '#markup' => $html,
);

Refer to: https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x


How to access remote index in search_api?

Using the services_search_api Module is the right way, but you have to apply patches from the following Issues:

Support keys: provide Key Field for searching Solr Indexes. See Comment #1
Undefined functions: add required functions from previous Services Module. See Comment #4


How to save database connection easy and safe?

Well, there is the encrypt module which can encrypt your data. Be sure to use the 7.x-2.x branch.

And yes, store the key somewhere on the filesystem that is not easily accessed and it should be hard for an attacker who has db access to be able to decrypt the info.

Just be sure that there's no way to execute php via the Drupal interface. A module like paranoia can help in that.


create thumbnails of Vimeo videos programmatically

You you can use the Vimeo Simple API to get the video thumbnails.

There is a fantastic write up here on stackexchange so I won't reinvent the wheel, but for a quick re-cap you can use the following code (thank you @Fluffy from link above.)

<?php

//Video ID - Easy to find in URL (example ID below)
$video_id = (int) 6271487;

//Format you would like returned. (Can be php, xml or json)
$format = (string) 'php';

//Build request URL
$request_URL = "http://vimeo.com/api/v2/video/$video_id.$format";

//Get data and unserialize
$response = unserialize(file_get_contents($request_URL"));

//Echo's url to image.
echo $response[0]['thumbnail_medium'];

?>

Optionally, check out the Vimeo Advanced API method: vimeo.videos.getThumbnailUrls


It's in the nature of image compression that compressing an already compressed image can result in larger filesize. The image-toolkit (be it GD or image magick) can not know on what level the image is already compressed and will try to make the best of it (following the quality setting that No Sssweat describes). So you may want to try to set this to 100% to prevent repeated compression.

Further reading:

Efficient Image Resizing With ImageMagick
In search of the most optimized image in Drupal 7


How can I create a custom landing page for a specific taxonomy term?

To display only node content with a specific taxonomy term checked, add Content: Has taxonomy term to the Filter Criteria of your view. Once you add the filter, you will be prompted to select your taxonomy term vocabulary as well as the term you wish to filter your view by. Once completed, you will only see content associated with the desired term.

If you're using Panels, as your post's tags indicate, you can create your landing page using Pages (comes with panels). Make sure the view you create is a block, not a page, and it will be easy to plug into any panel.


How detect format of date field in form alter?

For the Date popup selector, the #date_format element in the form element. For example:

    //The date field has the format of "d-m-Y"
    $form['date_field'] = array(
      '#type' => 'date_select',
      '#title' => t('My Date'),
      '#date_format' => 'd-m-Y',
      '#date_label_position' => 'within',
      '#date_year_range' => '0:+1',
      '#description' => t('This is a test date picker'),
      '#default_value' => date('Y-m-d H:i:s'),
    );

There's an D6 documentation page on d.o, but it's still valid for D7 last I looked.


Just for the record, if you want to do this with Crumbs:

Go to /admin/structure/crumbs/entity-parent.
For content type "News", enter "news" as parent path.

Likely it already works now.
If not, check the order and status of plugins on /admin/structure/crumbs.
Also check /admin/structure/crumbs/debug, where you can simulate breadcrumb-building for specific pages.


No, you can't, see the following question/answer: https://drupal.stackexchange.com/a/33493/31

If you only want to allow certain arguments, you need to validate the argument and return MENU_NOT_FOUND. Or you can use a named argument, e.g. cars/%brand, which will automatically call the brand_load() function, pass the value of the parameter to it and if that function returns FALSE, then it's automatically returned as 404. This is used for node/%node, user/%user and so on.


shorten input text size and maxlength with exposed filters

You should be able to use a regular hook_form_alter and has a great answer already, check it out and it should answer your question.


Adding more Data to a Commerce Feed Upload

A Commerce feed fundamentally isn't any different to a regular feed so if you need additional data attached to your product you should be able to create the additional fields you need on your product type and in Feeds map the data from your CSV to the Product Type fields in Commerce.

With regards to sorting, wouldn't you be doing that in Views when you're actually displaying the imported products?


Why my first tab is missing for local menu tasks defined by hook_menu()?

You need 3 menu items and 2 view pages. The parent menu and the default menu will share some configuration.

  $items['node/%node/ecg-outcomes/add-new-user'] = array(
    'title' => 'Add New User',
    'page callback' => 'SOME CALLBACK',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
  );
  $items['node/%node/ecg-outcomes/add-bulk-ghost'] = array(
    'title' => 'Add bulk',
    'page callback' => 'SOME CALLBACK',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK ,
    'weight' => -8,
  );
  $items['node/%node/ecg-outcomes/registration-report'] = array(
    'title' => 'Registration Report',
    'page callback' => 'SOME CALLBACK',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK ,
    'weight' => -7,
  );

  return $items;

As the outcome-viewer is set up as a view and you want it as the default menu tab, you need to set up two almost identical pages in your view as follows:

View Page 1:

Path: node/%/ecg-outcomes
Menu: Type : Menu tab, Title : Outcomes, weight : 50

View Page 2:

Path: node/%/ecg-outcomes/outcomes-viewer
Menu: Type : Default menu tab, Title : Outcomes Viewer, weight : -10

METHOD 2
I think it can also be done with 4 menu items and 1 view page, in which case you only define view page 1, and include this menu item:

$items['node/%node/ecg-outcomes/outcomes-viewer'] = array(
    'title' => 'Add New User', // NO page callback and access callback necessary
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
);


How to use views and LDAP query to get a list of names in a webform?

If you have a valid ldap query with names and emails your basically there with Views and LDAP.

You want to make a custom webform component in a module using PHP code. You can use views_get_results to get the results of the LDAP view as an array.

Then just build a webform component as you would a Forms API select widget with your values.

You then tell the webform to use your component in the UI.


How do I define a template file for a specific node ID?

In Drupal 7, node--[node-id].tpl.php is used as template file for nodes, as well as node--[node-type].tpl.php. Nothing else needs to be done, except, as Clive wrote in his comment, you also need to have node.tpl.php in the directory containing the template files used by your theme.

Notice there is a difference between node--[node-id].tpl.php, and page--node--[node-id].tpl: The latter is also used for pages at node/[node-id]/edit, or node/[node-nid]/delete. See the comment at the beginning of theme_get_suggestions().

  Build a list of suggested theme hooks or body classes in order of specificity. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, for $base = 'page', http://www.example.com/node/1/edit would result in the following suggestions and body classes:

 page__node              page-node
 page__node__%           page-node-%
 page__node__1           page-node-1
 page__node__edit        page-node-edit


Managed files are deleted on cron run for D7.


Can I highlight an invalid form field without assigning a message for it?

D'oh.  In Drupal 6 at least, just call form_set_error(FIELD) without the message and it should highlight the field and not set a message.  You are sending a space, so you are getting a space as a message.

Code in Question:

function form_set_error($name = NULL, $message = '', $reset = FALSE) {
  static $form = array();
  if ($reset) {
    $form = array();
  }
  if (isset($name) && !isset($form[$name])) {
    $form[$name] = $message;
    if ($message) {
      drupal_set_message($message, 'error');
    }
  }
  return $form;
}


Adding  to options on node edit and node create screen

There is the Taxonomy Term Reference Tree module that will format terms hierarchically.

  This module provides an expandable tree widget for the Taxonomy Term
  Reference field in Drupal 7. This widget is intended to serve as a
  replacement for Drupal's core Taxonomy Term Reference widget, which is
  a flat list of radio buttons or checkboxes and not necessarily fit for
  medium to large taxonomy trees.

This module produces nested ul lists, which seems optimal for styling hierarchies, if needed.


Output node creation date between two fields

Yes, you would need a module like Display Suite only if you want to do this in UI. For a solution in code you can add extra information to the render array $variables['content'] in a preprocess hook:

mytheme.theme:

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mytheme_preprocess_node(&$variables) {

  $node = $variables['node'];

  if ($node->getType() == 'article') {
    $variables['content']['created'] = [
      '#markup' => t('
Node created: @created
', [
        '@created' => format_date($node->getCreatedTime(), 'medium'),
      ]),
      '#weight' => '5',
    ];
  }

}

Adjust weight to position it between the two fields.


Can't use file field in custom form - gives AJAX errors

This is a bug in Drupal. The patch in comment #6 works.


Adding of social media links( Facebook, Google Plus)

Maybe should you try ServiceLinks, instead. Very straightforward to implement.

My two cents.


Correct way to get field definitions for entity types

Think this is an OOP question... so the correct answer is to switch by the type of the instance. In PHP you do this with "instanceof", like here in MappingTest.php:
protected function filterNumericFields(&$fields) {
    foreach ($this->view->field as $id => $field) {
      if (!($field instanceof NumericField)) {
        unset($fields[$id]);
      }
    }
  }

Note: dpm is bad with nested objects... you should set up a debugger like xdebug.
Another Note: Each content entity has a getFieldDefinitions method:
   /**
   * {@inheritdoc}
   */
  public function getFieldDefinitions() {
    if (!isset($this->fieldDefinitions)) {
      $this->fieldDefinitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($this->entityTypeId, $this->bundle());
    }
    return $this->fieldDefinitions;
  }


As per Clive's comment the error was Omega-Tools. I had disabled it but it required uninstalling and then I even had to delete the module from the modules directory to stop it from showing up in the modules page. After this I encountered this issue ( https://www.drupal.org/node/2200473 ) and then everything worked. Thanks Clive.


How to display related data along with node

there is surprisingly many ways to acheive it :)
this is one that will require some work, but should be sane and scalable :

in a hook_node_load, load the data and attach it to the $node ($node->my-data)
[optionally] in hook_preprocess_node, create a variable for the template
in your template file, show the value aproprietly


How to get new migrations to show up in the Migrate UI

First, the function *_migrate_api() in *.migrate.inc should include the $api with the key api of 2, and the key migrations of the array for your migration.

If you have newly added your migration, drastically changing the code etc, you perhaps need to make Drupal recognise the hook you have just created in your migration module; a guaranteed way for that is to disable once and (re)enable your migration module.

Then you need register your migration.  If you use Drush,

drush migrate-register --group=YourMigrationGroupName

would do a job.  After Flusing all caches (drush cc all etc), you will see the migration in your migration UI (hopefully!).

I am not an expert, but the above is based on my recent experiences.


View Render output in bootstrap tab style

In my opinion it's better to create two seperate view (display blocks). One shoud be grouped by Allestimento and other one by Descrizione. Create for the page custom template and add tabs there.


Drupals clean-urls (.htaccess) breaks with mass vhost

I had to add a slash before index.php to get this working for WordPress. Has to do with VirtualDocumentRoot not setting the DocumentRoot to the same value I guess.

RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]


Vocabulary terms deleted but still visible

taxonomy_term_data is the canonical location for term data so it sounds like there might be other issues going on (a broken admin display, caching, DB corruption via orphaned parent/child term, we can only guess).

If you want a safe way to remove taxonomy, invoke the taxonomy API functions (they are the same tools the admin interface is using) via Devel, drush eval, or some other dev tool where you can execute arbitrary PHP that uses these functions to remove your desired terms:

For example:

$my_bad_tids = [1, 2, 3];
$terms = taxonomy_term_load_multiple($my_bad_tids);
foreach ($terms as $term) {
  taxonomy_term_delete($term->tid);
}


how to give parameters in url for getting json parse for both taxonomy terms AND nodes

you can use taxonomy_select_nodes to find all nodes associated with a term.

Return nodes attached to a term across all field instances.

Parameters

$tid: The term ID.

$pager: Boolean to indicate whether a pager should be used.

$limit: Integer. The maximum number of nodes to find. Set to FALSE for no limit.

$order: An array of fields and directions.

API


Convert D6 user timezone offset to D7 timezone string

I would use the following code.

$map = array();

foreach (timezone_identifiers_list() as $zone) {
  if ($timezone = timezone_open($zone)) {
    if ($datetime = date_create("now", $timezone)) {
      if (($offset = $timezone->getOffset($datetime)) !== FALSE && !isset($map[$offset])) {
        $map[$offset][] = $zone;
      }
    }
  }
}

Keep in mind that the same offset is used for different timezone identifies. Showing just an identifier for each offset would be less useful for users.

For example, for Europe you would show the following list. (The list is partial.)

Europe/Amsterdam 7200
Europe/Athens 10800
Europe/Dublin 3600

In your list, Europe/Rome, Europe/Madrid, Europe/Malta, and Europe/Kiev would not appear because the offset is already used for the three entries I shown.

A better code would the following one.

function mymodule_get_timezones() {
  $map = &drupal_static(__FUNCTION__);

  if (isset($map)) {
    return $map;
  }

  foreach (timezone_identifiers_list() as $zone) {
    if ($timezone = timezone_open($zone)) {
      if ($datetime = date_create("now", $timezone)) {
        if (($offset = $timezone->getOffset($datetime)) !== FALSE && !isset($map[$offset])) {
          $map[$offset][] = $zone;
        }
      }
    }
  }

  return $map;
}

As side note, I would not use format_date() if you use "custom" as date format, and you are not interesting in translating the returned date. In such case, the following code that is executed from format_date() is extra, and useless, for you.

  // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
  // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
  // input string.
  // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
  // The read-ahead expression ensures that A matches, but not \A.
  $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);

  // Call date_format().
  $format = date_format($date_time, $format);

  // Pass the langcode to _format_date_callback().
  _format_date_callback(NULL, $langcode);

  // Translate the marked sequences.
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);

In the case I described, that code can be replaced with the following one.

return date_format($date_time, $format);


How to edit e-mail settings for project issue content type

suggestion 1 :

drush vset project_issue_reply_to_NAME_OF_CONTENT_TYPE test@example.com

suggestion 2 :

in a custom hook_update_N() :
variable_set('project_issue_reply_to_NAME_OF_CONTENT_TYPE', 'test@example.com');


One of the ways to solve it is to use the Paragraphs module.
How to start with Paragraphs for Drupal 7
It's basically entity reference fields with layers.
You create a Paragraph field as a container for each data set, then within paragraph create fields for color and lists (checkboxes).
BTW why not upgrade to D8? D8 supports this type of structure better.


How to hide few default fields for specific user

Hi for this there is many possible way to achieve this you can use
https://www.drupal.org/project/field_permissions/releases/7.x-1.0-beta2
(The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.)
or by custom module

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

  if ($form_id === 'you_form_id') {

  if (in_array('user_role_type', $user->roles)){
    //do stuff

     // Use var_dump  to dump the $form array to see the fields.
     // var_dump ($form);

     unset($form['mail']);
     unset($form['pass']);
    }
  }
}


How to set conditional edit permissions on webforms?

Just place a hook_form_alter() or a hook_form_FORM_ID_alter() (just for your webform) in your module.

Then inside the code check that the webform status is valid before committing the update or redirect to to an error page.


Copy the template also. For example if you have a node--old-content-type.tpl.php file you'll need to copy it to node--new-content-type.tpl.php.


How do I restrain domain names of e-mails in the Drupal registration form?

I'm not sure if you have any experience in PHP or custom module development but I don't have time to give you a working example.  However I will point you in the right direction.

• Create a custom module

• Use hook_form_alter to alter the form with the form id user_registration

• In your hook_form_alter add a custom validation function and ensure it is the first validation function that runs

• In your hook_form_alter unset the mail element and add two elements for the two parts of your form (the text input and the dropdown list of domains)

• In your custom validation function, use the submitted values of your form elements to create an email address and assign it to the element you unset before, mail

• Make sure that in the validation function, you don't allow users to submit blank values

Edit for a fuller answer to be added

Ok, apologies for taking my time.  This code is untested but should hopefully work for what you want to do.  First of all, try to avoid doing things like this in the theme layer.  The theme layer should be for themes only, so you want to create a custom module.

To create your module you need to create a .info file.  Alter the following code and paste it into your text editor and save it as example.info.  Remember that you can change the names of the files etc to whatever suits you, just replace the word "example" with whatever name you want to give it.  Please note that Drupal deliberately omits the closing ?> PHP tag.

name = "Example module"
description = "Gives an example of a module."
core = 6.x
package = Other

Next, you want to save a file called example.module.  Inside this file, you will want to copy the following code.  This code follows the instructions that I gave you in my previous answer.  I have tried to comment this code as well as possible in order to try to show you what is being done and why.  This should do what you want it to do.

<?php

/**
 * Implementation of hook_form_alter()
 */
function example_form_alter(&$form, &$form_state, $form_id) {
    // If the form is the user_register form
    if ($form_id == 'user_register') {
        // Attach our custom validation function as the first validation function
        array_unshift($form['#validate'], '_example_user_validate');
        // Hide the email address field
        $form['mail']['#type'] = 'hidden';
        // Give the email address field a random default value (in this case a random number and a timestamp)
        // as we cannot unset it due to Drupal's validation rules
        $form['mail']['#default_value'] = rand(1111, 9999) . '@' .time() . '.com';
        // Add our new text entry field
        $form['mail_first'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#default_value' => '',
      '#size' => 60,
      '#maxlength' => 64,
      '#required' => TRUE,
    );
        // Add our select list of possible email domain values
        $form['mail_last'] = array(
      '#type' => 'select',
      '#prefix' => '@',
      '#options' => array(
              // These are the possible email address domains
              'yahoo.fr' => 'yahoo.fr',
              'yahoo.com' => 'yahoo.com',
              'example.com' => 'example.com',
            ),
      '#required' => TRUE,
    );
    }
}

/**
 * Function to piece together our email address
 */
function _example_user_validate(&$form, &$form_state) {
    // If our two form elements have values
    if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
        // Set the email address to the correct value
        $form_state['values']['mail'] = $form_state['values']['mail_first'] . '@' . $form_state['values']['mail_last'];
    }
}


This sounds like cashier functionality. There has been some effort for D6, see Drupal POS (Point of Sales) System. I haven't used this.

Ideally, this would be done with JavaScript (I have once done it for a non-Drupal system).

A cheap workaround would be the Save & Edit module, where you just save the node and continue editing it, effectively updating the calculations. On demand, not automatically.

A smoother workaround would be updating (on demand) the form with ajax. Ajax module  has no D7 version, but in the issue queue is mentioned this sandbox project which supposedly can ajaxify the node edit form:
Asaf (ajax submit for any form).

You need one extra module for actually displaying Computed field on node edit form: Field extra widgets. Select the widget "read only".


How to print a CCK image field alt text in a node template?

If you install the Devel module, you'll be able to use:

<?php dpm($node); ?>

It will provide all available fields that you could use. Another method might be to use theme('image') to help clean up your image theming.


Custom field displayed based on author node

How about implementing hook_field_access() in your custom module.

This hook takes operation edit/view as parameters and returns access to the user for the operations.As a sample code

function MYMODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && $field['field_name'] == 'your_field_name') {

   // $entity will be the node,so check node author with current user.
   if($entity->uid == $user->uid) {
      return TRUE;
    }
   else {
    return FALSE;
    }
  }
}


First off, when there are failures, check the messages table to see what the specific failures are:

$ drush8 mmsg upgrade_d7_file

In this case, I'm sure what you'll find is that it couldn't copy the files, because it couldn't find them - your .yml file does not include source_base_path, so there's no way for the migration to know where to copy the files from.

I'm guessing when you ran drush migrate-upgrade --configure-only to generate your migrations, you forgot --legacy-root - this value (either the address of your site such as http://www.example.com if you want to scrape the files directly over the web, or an absolute local filepath if you've copied the files onto your D8 server) will be used to set source_base_path in your destination configuration.


I'd do something along the lines of checking the value of share_with_rep_region before defining the collapsed state of your fieldset. i.e.:

// whatever the default value of the select is before
// the user has interacted with it in any way
$default_value = '';

// set collapse true
$collapse = TRUE;

// assuming you're passing $form_state into your form definition, if not, do so
if ($form_state['storage']['add_rep_share_fieldset']['share_with_rep_region'] !== $default_value) {
    $collapse = FALSE;
}

$form['add_rep_share_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Share with Rep'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#collapsible' => TRUE,
    '#collapsed' => $collapse,
);

I hope this shows the basic idea behind what I'm trying to say: $collapse = true by default, IF the user has interacted with the form in any way, $collapse = false


It depends on how complicated your content/site structure is, authored by the user account that got deleted, but it can be fairly easy if it's just nodes and sum such content.

Use which ever migration method you're most comfortable with. Migrate module is popular, but Feeds may be more user-friendly? Don't hang on module reviews here ;)

One way to go about it is to create a separate dev instance of your site by copying the live Drupal folder, and restoring the database backup that contains your deleted user and content. Like a time machine viewing your site at a moment in the past :)

You can use Views to list all content from that user, export it as CSV, or some other parsing case. Views gives you a nice overview of what's there so you can check you got everything. You can output post times, statuses, references to other entities...

Then build Feeds importer for what you exported. Test the import on yet another dev instance of your site, the copy of the current db. TEST everything thoroughly before importing to a site that matters, this should be obvious. Migrations are notoriously tricky and long affairs.

You could go as far as to restate the user with account history etc with some more magic, but it seems you only need the content so it will probably easier to just assign authorship to another user or anonymous if it doesn't clash with permissions, or create a completely new user, you can name it the same as the old one but the ID will be different.


How can the Panels IPE "add content" modal be customized?

You can do that for all panels pages from
admin/structure/panels/settings/panel-page

Also if you use panelizer you can customize what appear in IPE for every content type.
admin/structure/types/manage/[content-type]/panelizer

Also you can install panopoly_magic module without other panopoly features, only the module "panopoly_magic.info" since it does not deponent on any thing in panopoly distribution.


Fixing D7 Bug: Block caching within views breaks JS

This is indeed an annoying bug.

I'm still looking for a permanent solution as well.  Meanwhile, I have been able to mitigate the effects of this bug by doing the following:

Install and enable Cache Expiration module
Setup the expiration setting of your content types or taxonomy terms so that cache for the problematic pages is expired on insert/edit/delete (adjust to your needs)
Implement hooks:
hook_entity_insert, hook_entity_update, hook_entity_delete and manually delete panels / views / block cache of the problematic blocks/content.
For example: cache_clear_all('my_view:my_display', 'cache_views_data', TRUE);

This is obviously far from perfect, since it forces regeneration of cache at every update but it does help in displaying content properly.


How to print Blocks in commerce-product.html.twig

You can use hook_preprocess_commerce_product to load the block and pass the variable to your twig file.

function YOURTHEME_preprocess_commerce_product(array &$variables) {
  $block = \Drupal\block_content\Entity\BlockContent::load(4);
  $variables['custom_block'] = \Drupal::entityTypeManager()->
    getViewBuilder('block_content')->view($block);
}

and then in your twig file you will have the {{ custom_block }} variable set.

On a sidenote, this answer helps a lot when trying to programatically load blocks.


Adding Custom Fields to Apache Solr Search Results appears to have the instructions.

  To do this, we will use the two hooks used in the last example: hook_apachesolr_update_index() and hook_apachesolr_modify_query().  To start, we need to add the data to the Solr index.

Modified the code to work with a field_keywords_field (note: field_keywords_field[0]['value'] is what I'm using, you may need to debug this if your keyword field is multi-value or something)

/**
* Implementation of hook_apachesolr_update_index()
*/
function mymodule_apachesolr_update_index(&$document, $node) {
  // Index field_keywords_field as a separate field
  if (isset($node->field_keywords_field) && !empty($node->field_keywords_field)) {
    // addField($key, $value, $boost), change $boost to give this field a higher score
    $document->addField('sm_field_keywords_field', $node->field_keywords_field[0]['value'], '2.0');
  }
}

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
  $params['fl'] .= ',sm_field_keywords_field';
}


How do you programmatically get the current user's status?

Assuming this is Drupal 8, try $user->isBlocked().
If this is Drupal 7, you probably just need to call user_load($uid) first in order to get a fully-loaded user object before checking the $user->status. Or try user_is_blocked($name).


Losing custom #theme settings set in hook_field_widget_form after an error

This one turned out to be a fairly simple fix. I had theme_mymodule_checkboxes living in mymodule.admin.inc which was not being included on every page. Moving the function to the mymodule.field.inc which is specifically included in the module file caused the theme function to be included and fixed the error.

Many thanks to the drupal user Ayalon who found this fix.


As @No Sssweat recommend, the D8 Migrate Modules is good way. With your way, you have to add property pre_hashed for field pass.

$values = [
  'name' => 'test',
  'mail' => 'test@test.com',
  'roles' => [],
  'pass' => [
    'value' => $hashed_drupal_7_password,
    'pre_hashed' => TRUE,
  ],
  'status' => 1,
];
$account = entity_create('user', $values);
$account->save();

You can find this property in FieldType Password


I have some difficulties with page.tpl.php

I mean page.tpl.php overrides node pages

That isn't true, I just think you haven't quite understood how templates work in Drupal. The hierarchy for templates is:

html.tpl.php
  page.tpl.php
    Everything else (including node.tpl.php)

So as you can see, node.tpl.php is inside page.tpl.php, it's not a replacement for it, nor does it override it. But since you're not outputting the main content block in that template file, it stands to reason that the page content will be empty. Unless otherwise specified by perprocessing/template suggestions, page.tpl.php will be used for every single page.

You also need to know that everything (including the main content) is a block, which must be put in a region in page.tpl.php to be displayed. You would typically find the main_content block in the content (or similarly named) region.

To fix your problem, you need to add the main content region back into page.tpl.php.


display 2 tables with checkboxes by ajax button

You should not put the table-building code in the ajax callback. Put the code to build the tables into the hook_form_alter() implementation that you are using to add the button. You can use $form_state['triggering_element'] to tell if the button has been pressed, and only execute the query and build the tables if you need to.


module_load_include not working including inc file

You need to add inc into your implementation of the function.  Also you don't need to add the extension .inc as part of the filename:

$file_path = module_load_include('inc', 'MYMODULE', 'FILENAME');

Documentation: module_load_include();.


The code shown in the question would throw an error about user_login_finalize() not being defined. The code isn't loading the User module and the DrupalKernel class doesn't load any module.
I generally use the code shown in authorize.php as guideline on how to bootstrap and programmatically log in a user. In this case, to programmatically log in the user whose ID is 1, I would use the following code.
use Drupal\Core\DrupalKernel;
use Drupal\user\Entity\User;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Route;

$autoloader = (require_once 'autoload.php');

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->boot();

  // A route is required for route matching.
  $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
  $kernel->preHandle($request);

  if (PHP_SAPI !== 'cli') {
    $request->setSession($kernel->getContainer()->get('session'));
  }
} catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');
if ($account = User::load(1)) {
  \Drupal::currentUser()->setAccount($account);
  // Add your code.
  $response->setStatusCode(200);
  $response->send();
}

Since it seems you are trying to access a specific page after logging in the user #1, it's probable you need to change the two lines following the A route is required for route matching. comment and use a different route name.


How to use "replacement tokens" created for a Message type in Views?

"To add profile pics of both user/team member or the email or any information in the view ..." (as in your question), you cannot use the replacement tokens (= @utilisateur and @equipier in your case). These tokens can only be used as part of your Message Text (as you are already doing), as indicated also via  ... which the message text makes use of ... on the Message Types form where you enter those tokens.

However, Messages are fieldable entities. So what you can do is like detailed in the steps below ...

Step 1:

Define a field in your Message Type corresponding to each of those tokens. As an example, add fields similar to these (for equipier and for utilisateur), with machine names like so:

field_equipier_user_name.
field_equipier_user_id.
field_utilisateur_user_name.
field_utilisateur_user_id.

Your replacement tokens appear to be uid values, note that I'm using a similar uid, but also the name as an alternative (it could as well be an eMail field, etc).

Step 2:

Extend your rule to also perform a Rules Action like "Set a data value" (for each of your fields you added in the previous step). To continue the example, add these actions in your existing rule:

 ,
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-equipier-user-name" ],
    "value" : [ "user:name" ]
  }
},
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-equipier-user-id" ],
    "value" : [ "user:uid" ]
  },
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-utilisateur-user-name" ],
    "value" : [ "user:name" ]
  }
},
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-utilisateur-user-id" ],
    "value" : [ "user:uid" ]
  }

Step 3:

Extend your view to also add those extra Message Type fields to your view (as extra fields of your view. Be aware: if later on you add more fields to your Message Type (and rule and view afterwards also), you'll only have actual values in the corresponding columns of the Views results for message that were created after you added those extra fields.

BTW, the Views error near the end of your question seems like a different question (not addressed in this answer ...).

PS: this answer applies to D7 ...


hook_menu not producing expected tab structure, problem?

So this works:

/**
 * Implements hook_menu().
 */
function newforms_menu() {
  $items = array();
  $items['admin/config/content/newforms'] = array(
    'title' => 'NewForms',
    'description' => 'Configure web forms via drag and drop.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('newforms_administration_settings'),
    'access arguments' => array('administer newforms module'),
    'file' => 'newforms.admin.inc',
  );

  $items['admin/config/content/newforms/list'] = array(
    'title' => 'Forms',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/config/content/newforms/components'] = array(
    'title' => 'Components',
    'type' => MENU_LOCAL_TASK,
    'page arguments' => array('newforms_components_list'),
    'access arguments' => array('administer newforms module'),
  );

  return $items;
}

I think there were two things happening.  I have two theories.  One was that Drupal essentially saw two identical tabs and said "this is dumb I'm not doing this" and didn't render the components tab.  The other theory is that as soon as Drupal saw a different page argument for the second tab (components), it demanded an access arguments specification.  I'm not sure which is true, if both are true, or if both are wrong, but this works.

The moral of the story is that things in hook_menu don't inherit the way you expect them to sometimes.

EDIT:

This is straight from the hook_menu documentation.

// Make "Foo settings" appear on the admin Config page
$items['admin/config/system/foo'] = array(
  'title' => 'Foo settings',
  'type' => MENU_NORMAL_ITEM,
  // Page callback, etc. need to be added here.
);
// Make "Tab 1" the main tab on the "Foo settings" page
$items['admin/config/system/foo/tab1'] = array(
  'title' => 'Tab 1',
  'type' => MENU_DEFAULT_LOCAL_TASK,
  // Access callback, page callback, and theme callback will be inherited
  // from 'admin/config/system/foo', if not specified here to override.
);
// Make an additional tab called "Tab 2" on "Foo settings"
$items['admin/config/system/foo/tab2'] = array(
  'title' => 'Tab 2',
  'type' => MENU_LOCAL_TASK,
  // Page callback and theme callback will be inherited from
  // 'admin/config/system/foo', if not specified here to override.
  // Need to add access callback or access arguments.
);

The second to last line is what tripped me up.  For every MENU_LOCAL_TASK you must add an access callback/access argument.  Mystery solved.


You'll need to re-index the site when new records are being added.
You can do it by visiting http://your-site-url/admin/config/search/settings and click "Re-index site".

P.S: This will queue the items for re-indexing. The items will actually be re-indexed when "cron" runs for the next time (manually or scheduled cron job.


I had seen similar error in the past and I followed these steps which worked for me:

Manually disable the module in db
Clear the cache
Re-enable the module


Deleted nodes appears in Views VBO list with their pathauto links


Custom module menu item declaration leads to error 404

I would guess that trailing slash on the path is throwing you

$items['eventi/book/%'] = array(
  'title' => 'Book',
  'page callback' => 'eventi_book',
  'access arguments' => array('allow booking'),
  'page arguments' => array(2),
  'type' => MENU_CALLBACK
);

Also, if you use %node for the variable in the path, the menu router will call node_load() on the given nid from the path and you'll get the full $node object in your callback function, like so:

$items['eventi/book/%node'] = array(
  'title' => 'Book',
  'page callback' => 'eventi_book',
  'access arguments' => array('allow booking'),
  'page arguments' => array(2),
  'type' => MENU_CALLBACK
);

// ...and so on, until...

function eventi_book($node) {
   return $node->title;
}

Also note that your callback function should return a value, not echo it.


You must use content ID, which is now the same thing.

That is the one to use as contextual filter, in Drupal 8.