Should I log the user out after calling an API using the Services module?

If you log the user out, the session ID that you received and used to modify users will expire, so it's recommended to do so.

I can imagine the following scenario:

You leave the user logged in. Someone else who have access to the server that you used to do the aforementioned actions somehow figures out the recently used session ID. They can use it to log in to your Drupal site within the maximum session lifetime.


variable_get() is used to store and retrieve systemic variables , you can found them in system table in DB, or you can change them using variable_set()


Must be:

Drupal.attachBehaviors($('#main'), context);


How to customize a specific content type display?

with the FieldUI, (enable in modules), you can place the fields,
see here /admin/structure/types.
with display suite you can even do it more sophisticated.

but in the end you want to have your own theme, or adjust the one your using for css etc.


How to handle config changes on core update?

Schema updates in different versions of core and contrib which cause changes to the config will cause an issue where your config becomes outdated.

On your local environment, run:

drush updb
drush cex

Then you can commit and push your configuration, and on your target (i.e. production, or stage, etc) environment, run:

drush updb
drush cim

Failure to do so will cause hard-to-diagnose issues in some case. More info and examples at:

Update hooks which modify configuration can lead to unstable sites; figure out how to deal with this.


How do I get an uploaded image URL or the default for use in a template (code improvement)

You don't need to load all the fields, you can just load the image field:

$uuid = $vars['node']->get('field_hero')->getFieldDefinition()->getSetting('default_image')['uuid'];
$file = \Drupal::service('entity.manager')->loadEntityByUuid('file', $uuid);

On a different note, the first line of your code assumes that $vars['node'] exists, which it won't on non-node pages, so you should change it to:

if (isset($vars['node'], $vars['node']->field_hero))


how could I access users profile using settings parameter in drupal behaviours?

You should use Drupal's drupal_add_js function with the 'settings' option (more info).

Example:

global $user;
$uid = $user->uid;
drupal_add_js(array('myModule' => array('uid' => $uid)), 'setting');


Where do I get a webhook url for a facebook messenger bot?

If you are working in a local development environment, you will need a publicly accessible IP address or domain name to route the FB request to your local server messenger bot webhooks.


Doing a global OR with the db abstraction layer

It is possible to nest db_and() and db_or() calls, and pass the result into a condition() call. See Conditional Clauses documentation page for more information.

  The first parameter of condition() can also accept another conditional
  object. That inner conditional object will be incorporated into the
  outer conditional, surrounded by parentheses. The inner object may
  also use a different conjunction than the outer object. That way, one
  can build complex nested conditional structures by creating and
  building up conditional objects "bottom up".

  The db_condition() helper function will return a new conditional
  object. It takes a single parameter that is the conjunction that
  object will use. In general, the helper methods db_and(), db_or(), and
  db_xor() will cover almost any expected case. That allows conditionals
  to be inserted inline in a query for a very compact syntax.

function a() {
  $q = db_select('table', 't');
  $q->addField('t', 'field1');
  $q->condition(db_or()->condition(b($q))->condition('t.field3', 'some val', '=');
  $q->execute();
}

function b($q) {
  return db_and()
    ->condition('t.field1', 'some val', '=');
    ->condition('t.field2', 'some val', '=');
}

This should produce the query SELECT field1 FROM table t WHERE ((t.field1 = 'some val' AND t.field2 = 'some val') OR (t.field3 = 'some val')).


User profile layout vs. contact form option

found the answer / an answer to my question: Installing and enabling the module profile2 helped. The missing fields ("Contact user element") showed up in the fields list and became sortable through drag'n'drop.


Can panelizer automatically switch layouts based on a condition?

Visibility rules are the way to go.

Granted the built in ones are not always as sophisticated as one might like at times, but on the other hand, access plugins are among the easiest to do on your own, allowing you arbitrary conditions.

See What are Ctools plugin (content type, access, etc), and how does one create them? for a example of how to implement one.

It can also be worthwhile checking the Ctools issue queue for a plugin that matches your requirements. Development of Ctools has almost gone away with all the active contributors working on D8 instead, but I have found useful patches in the queue.


How do I replace a module with a dev version through the UI?

I just found that I can run drush dl <module_name>-8.x-1.x-dev and confirm that I was to override the old module.


In Drupal 7 Views how do you set permissions via roles for an attachment display?

From you screenshot you gave permission to anonymous user, authenticated users and instructor. So the attachment will be visible to all users. Choose only admin for the attachment and for the page it is attached you do not need to set permissions. You settings should look something like the image below

Make sure you always apply permissions to the current display and not to all display.


Perhaps something like this will help:

/**
 * Implements hook_preprocess_search_result()
 */
function MYTHEME_preprocess_search_result(&$variables) {
    $node = $variables['result']['node'];
    if (is_object($node) && $node->nid) { // if the result is a node we can load the teaser
        $variables['teaser'] = node_view($node, 'teaser');
    }
}

That will provide the variable $teaser to your search template. In search-result.tpl.php you can then access your field data:

    <?php print render($teaser['field_icon']); ?>

<a href="<?php print $url; ?>"><?php print $title; ?>

    <?php if ($snippet): ?>
      <?php print $snippet; ?>
    <?php endif; ?>


How to get the shipping address programmatically in drupal commerce - what wrapper should i use?

Ok i did this in this way

function commerce_shipping_biagetti_service_rate_order($shipping_service, $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $shipping = $order_wrapper->commerce_customer_shipping->commerce_customer_address->value();
  //$shipping is an array containing all shipping data


Node access by role or user, what module(s) should I use?

The Content Access module gives you role permissions at the content type and (optionally) node level. By default, node level permissions are disabled but you can enable it on a type-by-type basis.

If you install ACL module, Content Access can give you per user permissions at the content type and node level.


How do you hook into a path being created via pathauto?

The UI has this built in as it happens, if you visit http://mysite.com/admin/build/path/pathauto and look in the "General Settings" fieldset you'll find a textbox containing a list of strings to remove from aliases:

hook_pathauto_alias_alter is definitely the right way to do it; it's available in both the 1.x and 2.x branches. Have you run any debug code to see if the hook is actually being called? And did you clear the caches? Hook implementations are cached (in Drupal 7 anyway; I can't remember if they are in Drupal 6 or not).

In case you're still wondering most modules that declare hooks come with a MODULENAME.api.php file which lists those hooks and how to use them. In the case of pathauto the file and hook function declarations are there, but sadly there's no documentation.


if this is a registration function for anonymous users do they have the respective access caubo_registration content permission set in User Permissions?


How to configure an additional field for a bundle that is created by a custom module

You have to add the field via the UI.
Then you can export the yml config files required by the field by

Using drush cex sync
Navigating to admin/config/development/configuration/single/export and export the changed/new files on admin/config/development/configuration manually.

Copy the new/changed files to your config/install folder and you are good to go


Permission for private file to anonymous

It sounds like you might want to check out the Private Files Download Permission module which may provide exactly the functionality you're looking for.


Having my own theme for creating and editing Nodes: No WYSIWYG Editor

Since the weight did not work as expected I tried to set the scope for every script to 'header' except for ckeditor files. > Did not work

Because I had no clue I tried the opposite way:

  // Set scope for every script to footer.
  foreach ($js as $index => $value) {
    $js[$index]['scope'] = 'footer';
  }

  // Except for ckeditor files.
  $js_ckeditor_utils = &$js['sites/all/modules/ckeditor/includes/ckeditor.utils.js'];
  $js_ckeditor_utils['scope'] = 'header';
  $js_ckeditor = &$js['sites/all/libraries/ckeditor/ckeditor.js'];
  $js_ckeditor['scope'] = 'header';

This works - I don't know why, but it works.


granularity of views filter on date field

1) Double check your field is collecting the correct date attributes.
2) Make sure "Date Views" is enabled under Modules (Requires: Date API, Views, Chaos tools).

If the above are okay then try creating a new date field making sure you're collecting all date attributes. This should rule out any issues there might be with the field. It could also pay to try create a new date field in a different content type and see how views reacts.

If the new date field doesn't work and views still can't filter down to seconds granularity then try a new test view.

Tested with no problems on Drupal 7.18, Date 7.x-2.6 and Views 7.x-3.5.


How to hide Regions and Themes in the block setting admin page?

it's a bit late but for the people in the same situation :

function MODULE_form_alter(&$form, &$form_state, $form_id){
    global $user;
    if($form_id == 'block_admin_configure'){
        if(in_array('your_role_name',$user->roles)){
            hide($form['regions']);
            hide($form['visibility']); //for the visibility region
            hide($form['visibility_title']); //for the visibility region
        }
    }
}


For the select Form element, the array key is the value, and the array value is the display of the option. That's why you're getting 'key1' for example.
If you want to achieve your goal you can write it this way:

'#options' => [
    'empty' => $this->t('Select an item'),
    $this->t('value1')->render() => $this->t('value1'),
    $this->t('value1')->render() => $this->t('value2'),
    $this->t('value1')->render() => $this->t('value3'),
],

Although this doesn't seem right :D
Also, while you're at it, you should check 'Select' form element documentation as you shouldn't add 'empty' value but rather use the '#empty_value'and '#empty_options' properties.


I would add this as a comment if I could. Looking at your code, it looks like you're only adding rows to $rows is $part['wtcr_sku'] is an empty string (line 258). It's possible you could be filtering out rows because of that.


Only show the complete form at the end of the quiz

I don't know enough about the Quiz module to say for sure but have you checked out the theme functions available for Quiz?

There is a theme function called theme_quiz_take_summary().
It has a form that it adds if the quiz is set to display_feedback. Maybe it's a setting for the quiz somewhere?

// Get the feedback for all questions. These are included here to provide maximum flexibility for themers
if ($quiz->display_feedback) {
  $form = drupal_get_form('quiz_report_form', $questions);
  $output .= drupal_render($form);
}

If you want to have your own version of that theme function you should place the whole function in your theme and replace theme_quiz_take_summary() with NAMEOFYOURTHEME_quiz_take_summary().


Views generated block - how to override filter on some pages?

I would create a custom module for this, sounds like it could be done quite easily.

Create an admin interface where the 4 default links can be entered.
Create fields on nodes, where the special links can be entered.
In the block view, try to load the node, if possible check for custom links and use default links if needed.

The above solution is good and flexible if you only want links.

If you instead want node references, with the posibility of getting more data, like an image, taxonomy term etc, nodequeue could come in handy instead, as you with views can setup a more sophisticated display easily. It would however become a bit more tricky to override, but could be done via preprocess functions or hook_views_query_alter.


How to handle / cleanup obsolete aggregated css / js?

This is actually by design so that cached pages with older versions of files don't get broken. See this closed issue.

TL;DR: They will be deleted automatically 30 days (or whatever your drupal_stale_file_threshold variable is set to) after they were created via drupal_clear_css_cache() and drupal_clear_js_cache(). So the solution is to modify the drupal_stale_file_threshold value to something lower than the default 30 days.

When are old files deleted

  Old cache files are not deleted immediately when the lookup variable is emptied, but are deleted after a set period by drupal_delete_file_if_stale(). This ensures that files referenced by a cached page will still be available.

  drupal_delete_file_if_stale() defaults to 30 days - so if a) Cron is running properly and b) you see aggregated files older than 30 days, you have a different problem.

variable_get('drupal_stale_file_threshold', 2592000) is the 30 day check.
variable_set('drupal_stale_file_threshold', 172800) would change the timeout to two days. On a site where cache handling is strictly controlled, the time could be even shorter.

Source: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_build_css_cache/7
See drupal_delete_file_if_stale() for more information.

Is there some reason both .css and .css.gz files are kept?

  If CSS gzip compression is enabled, clean URLs are enabled (which means that rewrite rules are working) and the zlib extension is available then create a gzipped version of this file. This file is served conditionally to browsers that accept gzip using .htaccess rules.

  Source: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_build_css_cache/7 (In the function comments)

Also see drupal_build_js_cache() which is nearly identical to drupal_build_css_cache().


Finally...

using this command

 composer global require drush/drush:8.*

But i need to refer few steps before running this command.

  composer.json  # Removed the line containing drush like below

  {
          "require": {
              "drush/drush": "7.*"
          }
      }

composer global update
composer global require drush/drush:8.*

source https://github.com/drush-ops/drush/issues/2006


How do I add a filter to a checkbox list in a content editing form

You can change the Reference method option in your Field settings to Views: Filter by an entity reference view.
You first have to build the Views listing taxonomy terms, Display of type Entity Reference. Add the exposed filter there for the term name. Save the View.
Then you'll be able to select that ER Views Display in your Field settings.


what is the difference between Drupal.formatPlural() and Drupal.t()?

Actually after some playing aroud with the code I HAVE FOUND THE ANSWER :
formatPlural($count, $singular, $plural, array $args = array(), array $options = array());

code
the formPlural function enable us to translate a string in plural or singular format according to the first argument $count , a $singualr string will display if $count = 0 or 1 otherwise if $count > 1 the $plural string will be displayed , and in plural string we can get the $count value using @count , for example in the code bellow  :

the first formPlural function will return $singular  string since
$count = 1
the second formPlural function will return $plural
string since $count > 1

var typeVar = 'list';
var singular = Drupal.formatPlural(1, 'I have 1 item', 'I have many @type items', {'@type': typeVar});
$('#translate_singular_item').html(  singular   );

var plural = Drupal.formatPlural(3, 'I have 1 item', 'I have @count @type items', {'@type': typeVar});
$('#translate_plural_item').html(  plural  );

output

Back-office Translation
now we can translate both singular and plural string :


How do I create an uncacheable field plugin base?

May be you can try :

use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\views\Plugin\views\field\UncacheableFieldHandlerTrait;

class MyFieldPluginBaseCustom extends FieldPluginBase implements CacheableDependencyInterface  {

    ...
    public function render(ResultRow $values) {
        //do some work with the current node (the current row view)
        if(node_parameter_test_isOK() == true)
            return "string A";
        }
        else{
            return "string B";
        }
    }
  public function getCacheMaxAge() {
    return 0;
  }
  public function getCacheContexts() {
    return [];
  }
  public function getCacheTags() {
    return [];
      }
}


If you want to cycle the <li>'s then you need to call .cycle() on the <ul> element. At the moment looks like you're trying to cycle the <ul> elements inside the <div class="homepage-slider">. If there's only 1 child element cycle doesn't progress further since there's nothing to cycle.


Render comments in a custom Twig template

After adding comments as field in your content type

In node--article.html.twig :

{{ content.field_myfieldnamecomments }}


Re-import nodes daily using feeds and hook_cron

There is no need to do that manually.

Under Settings for Node Processor just select Replace Existing Nodes.

For further details you can check https://www.ostraining.com/blog/drupal/feeds/ which explains the steps in detail.

There is a field called GUID. Make sure that you set it to an appropriate value so that nodes will be updated(deleted and reimported). If the GUID in your site matches to that of the import then current nodes will be deleted(irrespective of whether they were created manually or imported) and the nodes from your news source will be reimported.


Add a remove item button on checkout page

This is a pretty common support request, and the gist of it is you cannot use Views form functionality on Views embedded in the checkout form. The reason is pretty simple to understand - you end up nesting a FORM tag within a FORM tag because Views doesn't know that it's building form elements to render inside another form. The solution is not so simple.

The best advice I've been able to give thus far is to disable the cart contents checkout pane and create a Views block instead that uses the form functionality. However, if someone removes an item from the cart after making a change elsewhere on the page, the page would refresh and that data would be lost. Thus you'll want to figure out a way to have that remove button work via AJAX, which is totally possible through the forms API but remains undocumented as far as I know. If you do code a solution, a blog post about it or doc page on d.o would be great.


How to include most specific tpl files in a less specific tpl file?

It can be difficult to track the way different template files are used. First, I recommend turning on theme debugging by putting this in your settings.php

$conf['theme_debug'] = TRUE;

See this documentation for more information about theme debugging: https://www.drupal.org/node/223440 The main thing to know about that option is that it will print out the file names of the templates being suggested.

For your specific question, php includes are not the mechanism by which themes reference other themes. Rather the variables in one template are often "render arrays" (arrays with a very particular structure that sets up certain template files to be called). Here is the documentation on Render arrays in Drupal 7: https://www.drupal.org/node/930760 Ultimately, changing the template file selected involves working with render arrays in one form or another.


How to restrict users of other roles from seeing the site administrator details?

That's kind of a "asking for a module to do X" question, which is not really allowed but I do think it is a very common task.

There are a few approaches/modules to this, we are using the combination of https://www.drupal.org/project/userprotect to prevent users from editing users that already have the administrator role, and https://www.drupal.org/project/roleassign to prevent them from giving the administrator role to a user that they are allowed to edit.

There is also https://www.drupal.org/project/administerusersbyrole, which in the 8.x-2.x branch attempts to solve this without requiring users to get the administer users permission, which is more safe, but it also requires core patches because a lot of things in core itself can't really deal with users being able to edit other users without that permission yet.


No commerce_price field in product after Kickstart

The commerce_price field should be on products referenced by the display. Typically what happens is an importer will migrate all product entities first (which corresponds to each SKU in the remote system) and then set the product reference field value of a product display to point to those product entities. The SKU is unique, so it can be used as unique ID to reference displays to SKUs when you don't actually know product IDs.


You can use the Ubercart Webform Checkout Pane module.

  This module allows you to define Webform nodes as checkout/order panes
  in Ubercart.

  This is useful if you want to collect additional information during
  the checkout process. For example, you may want a quick survey or
  require additional fields that apply to the entire order.


field_info_field API to get human readable name

You can't, no - the labels are set statically in code (in image.field.inc), they don't come from the API:

// Add the additional alt and title fields.
$element['alt'] = array(
  '#title' => t('Alternate text'),
  '#type' => 'textfield',
  '#default_value' => isset($item['alt']) ? $item['alt'] : '',
  '#description' => t('This text will be used by screen readers, search engines, or when the image cannot be loaded.'),
  // @see http://www.gawds.org/show.php?contentid=28
  '#maxlength' => 512,
  '#weight' => -2,
  '#access' => (bool) $item['fid'] && $settings['alt_field'],
);
$element['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#default_value' => isset($item['title']) ? $item['title'] : '',
  '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
  '#maxlength' => 1024,
  '#weight' => -1,
  '#access' => (bool) $item['fid'] && $settings['title_field'],
);


Altering the type of a menu item to local task (tab)

The following hack worked, to create a new local task item with definitions identical to the original menu item except it's a local task. But is it the optimal way?

<?
/**
 * Implements hook_menu().
 */
function MOMODULE_menu() {
  $items['messages/newmessage'] = array(
    'title'            => 'Write new message',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('privatemsg_new', 2, 3, NULL),
    // 'file'             => 'privatemsg.pages.inc',
    'access callback'  => 'privatemsg_user_access',
    'access arguments' => array('write privatemsg'),
    'type'             => MENU_LOCAL_TASK,
    'weight'           => 5,
    'menu_name'        => 'user-menu',
  );

  return $items;
}


Assuming I have interpreted what you're trying to do, try adding the Event "Content is viewed", with the Condition "Content is of type" and configure the Condition to be of node type: 'Page'. If you could explain exactly what you're trying to achieve I may be able to suggest a better solution!


This could be working for example if you'd use a taxonomy term reference instead of a text field. Just create a taxonomy with your workdays as terms.

use these tags on your content
in views add a field to show the term your content is tagged with
in the format options choose 'group by' and select your taxonomy field

Now the content should be grouped by the workdays. To achieve the correct sorting order you can either rely on the term-ID (which is created in chronological order) or just arrange your terms with drag and drop (in the terms dialog).


You can try this module: https://www.drupal.org/project/nodeaccess_userreference. I use it too and it works very well.

As the module's page says, it "Gives content access permissions to users for content that references the users with User reference or Entity reference."

With this module you can define permissions just for the entire entity, you can't define them to the single fields.


multidomain, multilanguage, keep indicization, multiheadache

One way to would be to build this with domain access use a different domain for each language to meet your criteria. Repoint the old urls to the new ones.

Another way would be by indicating the language in the url.  Read more about it here: http://indico.cern.ch/event/216222/contribution/10/attachments/345315/481614/multilingual-training.pdf Start at page 37.

Probably a few other ways.


I think it's because you're missing the type, however, to make things easier and more compatible, why not load the "stock" widget and make modifications?

Try adding this instead of your $element declarations:

$element += text_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

That should load the default text form, then you can make modifications. You can take a look at the code it uses directly: see line 502 of text.module.

Your simplified code might look something like this:

   //load the default text instance
   $element += text_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

   if ($instance['widget']['type'] == 'autocomplete_speaker_name') {
      $element['value']['#autocomplete_path' ] = 'jsbu/speaker/autocomplete';
   else if($instance['widget']['type'] == 'autocomplete_venue_name')
      $element['value']['#autocomplete_path' ] = 'jsbu/venue/autocomplete';
    }

   return $element;


you should use session manager for storing current sessions for anonymous users

private_tempstore gives us a temporary store that is private to the current user

refer to this link asked some days ago session storage for anonymous users


How to reference a view using entity reference field type?

Sounds like you know what your doing. Like you say either create a 'view mode' in your content type or create a view. All you have to do with the view is create a relationship (under 'relationships' in the advanced section) to get your entity reference and set a filter for the tutor.

Tried to find something similar to your issue, hope it helps. How to use Entity Reference and Views


You can try using taxonomy_get_children($termid) to get children of term and then taxonomy_get_parents($termid) and again taxonomy_get_children() to get the siblings .
The following is the code I used in such situation :

<?php

if (isset($page['#views_contextual_links_info']['views_ui']['view']->args[0])){
    $termid = $page['#views_contextual_links_info']['views_ui']['view']->args[0];
    $terms = taxonomy_get_children($termid);

    if (empty($terms)) {
        $parent = taxonomy_get_parents($termid);
        $terms = taxonomy_get_children(key($parent));
    }
}

if (isset($node->field_category['und'][0]['tid'])) {
    $termid =  $node->field_category['und'][0]['tid'];
    $terms = taxonomy_get_children($termid);
}

?>


On D.O., where to file reports for spam users?

The only way I know is creating an issue in the webmaster queue. There is a Spam category there.


For the "book page" content type, try using the path:

[node:og-group-ref:title]/[node:book:parents:join-path]/[node:book:title]


how do i add last name new field in default user registration page

I would use the content profile module, you can add new fields to a users profile just like how you use cck to add new fields to a node. There is a configuration option where you can then set which fields you want displayed on the registration form.


How to set block visibility by role in Drupal 8

I found a discussion about this here:
https://www.drupal.org/project/drupal/issues/2952962

And solution in 28 worked for me:
https://www.drupal.org/project/drupal/issues/2952962#comment-12549257


Can't choose a Taxonomy term as a Context condition

Turns out this was user error. I wasn't the one to set up the taxonomy vocabulary in the first place, and it turns out that the guy who did set the vocabulary to be Tags. You can't use Tag vocabs in Context conditions. I unchecked the "Tags" box and now everything works as expected.


How to display data collected in a form on a page templated in module's tpl file?

You need to use hook_theme in your module to manage content in tpl file.

Example,

Creating template file using the hook_theme function

    /**
    * Implements hook_theme
   */

    function example_theme(){
      return array(
        'exampletheme' => array(
            'template' => 'exampletheme',
        'arguments' => array('example_array' => NULL),
          ),
      );
    }

Now, we can use "exampletheme" theme to display content. Below is the page callback function for the menu item.

 function example_callback(){

  $array = array(1,2,3);

  return theme('exampletheme',  $array);
}

Now, you need to create "exampletheme.tpl.php" file and you can render the "example_array" in the tpl file.


Where is place $content in node--product--type.tpl.php be generated and manipulated in drupal commerce?

I got it, It's hook_entity_view. We can read profiles\commerce_kickstart\modules\contrib\commerce\modules\product_reference\commerce_product_reference.module for reference.


If I am not mistaken, base themes do exactly what you describe.

For Drupal 7: https://www.drupal.org/docs/7/theming/creating-a-sub-theme
For Drupal 8: https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme

In your case, you can use 'Theme A' as the base theme, and specify that 'Theme B' uses 'Theme A' as the base in the .info file. You can then override the CSS and other theme features as you wish.


The last revision is always the one that will be used throughout the site. So if it is published then it will be shown. You cannot have one revision published and working on another revision that is not published yet.

Although maybe you can edit an older revision(make sure you do not tick the "create new revision" option while editing) and then, via revision overview, make it the current revision.

If you want to change the status of node(not any entity, only node entity) programmatically than you can call the $node->setPublished(TRUE) or $node->setPublished(FALSE) methods.


How to know the "name" of an input field of a commerce checkout form?

Give a try to this:

  form_set_error('customer_profile_billing][field_cif_nif_id', t('This field failed validation'));


how to stay on the same page on clicking a link


Go to your Webform and in Build tab add field of type Select (Select / Entity Select) and define all options (email addresses from which it is possible to send emails) in your field's detail form.
Then go to Webform settings and under tab Email handlers add new Email. Fill basic fields (subject, body) and as your sender (address from which email should be send) select name of the Select field you've created earlier. As receiver (address which should receive email) set whatever email you need.


Finding and display custom user variables

It's easier to have Xdebug installed so that you can add breakpoints, pause execution and inspect surrounding variables. Alternatively, you can use Kint to print out variables.


Some info missing on Drupal 7 ckeditor accordion instructions

Go to /admin/config/content/formats and click configure on the format that you'll be using.

Scroll all the way down and click on "Limit allowed HTML tags" tab. Now replace <dl> with <dl class>


Inserting div wrappers - changing hierarchy of the html

Completely forgot to return and give my solution. This is it:

jQuery(document).ready(function() {
    my_selection = [];
    my_selection.push(['#block-views-dyn-box-1-slider-block']);
    my_selection.push(['#block-views-dyn-box-2-slider-block']);
    my_selection.push(['#block-views-dyn-box-3-slider-block']);
    my_selection.push(['#block-views-dyn-box-4-slider-block']);
    my_selection.push(['#block-views-static-boxes-test-block']);
    jQuery( my_selection.join(',')).wrapAll('&ltdiv class="dyn-box-wrap"&gt&lt/div>');
});

I'm little more than a jquery novice, so I'm sure there are more efficient ways, but this worked just fine for me.


Result should return a value greater than or equal to the selected facet

I wasn't able to find answers on how to solve this with Facets alone, or writing custom code which is related to facet API. Honestly, I've been ignoring the most obvious solution to my problem which is Views exposed filter, and this is how I managed to solve my problem:

Create an exposed filter for GPA, which filters result that are greater than or equal to the provided GPA. I made this hidden by default.
I disabled the GPA facet I was using, and wrote my own GPA filter block. It's just a matter of querying the GPA field table, disregarding duplicates.
Wrote a custom script that captures the selected GPA value, from the custom GPA block I created, and then feed it hidden views exposed filter.
I added few more customization to it so that it behaves exactly like the rest of the facets.


How to check if user has passed the quiz already before granting user points?

Step 1 - Create a flag for tracking Passed Quizes

Use the Flag module to create a flag labeled (e.g) Passed Quizes. Here is an export of the flag I used for this (you should be able to import it in your own site also):

$flags = array();
// Exported flag: "Passed Quizes".
$flags['passed_quizes'] = array (
  'entity_type' => 'node',
  'title' => 'Passed Quizes',
  'global' => '0',
  'types' =>
  array (
    0 => 'quiz',
  ),
  'flag_short' => 'Flag this item',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Unflag this item',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'answers_full_node' => 0,
    'print' => 0,
    'question' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

This flag will be used in the custom rule, detailed in the next step.

Step 2 - Create a single rule to cover all situations

Here is a rule which illustrates how to resolve the challenge in your question:

{ "rules_process_a_quiz_when_passed_the_very_first_time" : {
    "LABEL" : "Process a quiz when passed the very first time",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "rules_conditional", "flag", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT flag_flagged_node" : {
                "flag" : "passed_quizes",
                "node" : [ "quiz-result:nid" ],
                "flagging_user" : [ "site:current-user" ]
              }
            },
            "DO" : [
              { "drupal_message" : { "message" : "Congratulations, this is the FIRST time you passed this quiz (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } },
              { "flag_flagnode" : {
                  "flag" : "passed_quizes",
                  "node" : [ "quiz-result:nid" ],
                  "flagging_user" : [ "site:current-user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "Congratulations, you passed this quiz yet ANOTHER time (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } }
            ]
          }
        ]
      }
    ]
  }
}

This rule requires the Conditional Rules module to be enabled (head over to the next step for some (multiple!) alternatives which does not need this extra module).

Here are the critical pieces of this rule to make Rules-magic happen:

The very first Rules Condition, which is "the" way to get access to all sorts of data about the quiz node itself (starting from "a" quiz result).
If the quiz node (to which this quiz result relates) is not yet flagged (by the flag from Step 1), and the quiz result is that it is at leastd equal to the pass rate of that quiz, then you have your very first hit you're looking for. At which time the quiz node gets flagged.

Use the Rules UI to import the above rule in your own site, after you enabled the Conditional Rules module and completed Step 1. After you are convinced it works as designed, simply add your additional Rules Action(s) to grant the User points ... only the very first time.

Step 3 - Possible Rules variations

Some variations of the rule included in Step 2, which should also achieve a similar result:

Replace the logic implemented via the Condtional Rules module by 2 equivalent Rules Components (so that you don't need the extra module). Refer to "What's the alternative to using the Conditional Rules module?" for way more details on this.
If you DO NOT want anything to happen if the quiz was already passed before, then the "else"-part of the Conditional Rules logic is empty. In that case you could rework the remaining Conditional Rules logic to a regular Rules Condition (to be executed as the very last one). As a variation, clone such rule variation in a 2nd variation, in which you just reverse that very same Rules Condition (with Rules Action as in the "else" part of the Conditional Rules logic).

Showtime

Here is a sample of a message I received after passing a quiz:

The very first time:

  Congratulations, this is the FIRST time you passed this quiz (with a score of 80 %, whereas the pass rate is 75 %).

The next time:

  Congratulations, you passed this quiz yet ANOTHER time (with a score of 100 %, whereas the pass rate is 75 %).

PS: I'm assuming this question is about D7 ...


Why am i getting PDO exception while running the following test from console?

You can't create and save entities in a unit test.

That's what kernel tests are for. You will also need to install the necessary entity schema then, make sure the necessary modules are enabled. One way to do that is to extend from EntityKernelTestBase.

Also, I strongly recommend to run the phpunit tests directly with phpunit, the error reporting is much better and it's faster as well.


Possible to show 'Request new password' tab with LoginToboggan 403 login page?

When a page is forbidden, logintoboggan pulls the login form via the following code:

drupal_get_form('user_login');

For some reason, which I haven't figured out, calling user_login doesn't include the links to 'reset password' and 'create new account'.  I've submitted a patch to the module, which adds an option in the configuration to include the 'forgot password' and 'create account' links.  It uses user_login_block instead of 'user_login' to render the form with the 'forgot password' and 'create account' links.

Here is a screenshot of the admin area:

Here is a link to the issue that contains the patch: Add lost password link to 403 login form

Edit: I think the reason that the tabs for 'Request new password' and 'Create new account' aren't displayed, is that they are MENU_LOCAL_TASK's on the 'user' page.  Logintoboggan redirects to 'toboggan/denied', so the tabs aren't being pulled in.


Integration with Single Page Application (React)

To provide the page hosting the React SPA, you will need to implement a custom module. This module would also contains all the JavaScript code of your application. If that's the only usage of React in your site, I suggest bundling everything in the module to make it easier.

I assume you should be able to retrieve the user authentication token and any other needed info in Drupal. You can then pass it to your application using drupal_add_js() (or #attach in a render array). Your application can then retrieve it with Drupal.settings

/**
 * Implements hook_menu().
 */
function MODULE_menu() {
  return [
    'admin/APPLICATION/PATH' => [
      'title' => 'Awesome React Application',
      'page callback' => 'MODULE_application_page',
      'access arguments' => 'access administration pages'
    ]
  ];
}

/**
 * Page callback for the application page.
 *
 * @return The page as a render array with #attached JS and CSS code.
 */
function MODULE_application_page() {
  global $user;
  $app_data = clone $user;
  unset($app_data->pass);
  $app_data->token = MODULE_get_user_token();
  $base_assets_path = drupal_get_path('module', 'MODULE');
  return [
    '#type' => 'markup',
    '#markup' => '

',
    '#attached' => [
      'css' => ["$base_assets_path/css/app.css" => ['preprocess' => FALSE]],
      'js' => [
        "$base_assets_path/js/app.js" => ['preprocess' => FALSE],
        [
          'type' => 'settings',
          'data' => ['MODULE' => $app_data]
        ]
      ],
    ]
  ];
}


Views - display node referenced by user profile field

Figured it out. Had to create a contextual filter on Content: nid and set the default value to PHP code:

$uid = $GLOBALS['user']->uid;
$user_data = user_load($uid);
return $user_data->field_office['und'][0]['nid'];

Really weird that this isn't easier to do.


Create a field (defined within same module) during module installation?

The function hook_update_N() only gets called by running update.php. You also need to implement a hook_install(), for example like this:

function mymybase_install() {
  mymybase_update_7200();
}

Do note that this only runs when you enable the module for the first time. So if you already enabled the module, you can test this by first disabling it and then uninstalling it. If you want to run the function each time the module is enabled, you should use hook_enable().


Call a Javascript Function and Update my Form Element at the same time

Just to ad to the above answer by Ollie.
To return form['id'] too (same as the default behavior), you can use ajax_command_replace

function myid_search_idnumber($form, $form_state){
    $commands[] = ajax_command_replace(NULL, render($form['id']));
    $commands[] = ajax_command_invoke(NULL, 'myid_update_id_number', array($form['id']));
    $page = array(
         '#type' => 'ajax',
         '#commands' => $commands,
      );
    ajax_deliver($page);
  }


You should try hook_views_post_build(). I haven't tried this but I was looking at the views api and noticed that hook_views_post_build shows an example of modifying the exclude property of a field.


Unable to get Video + VideoJS to play MP4s on ANY Android device

Many issues with playback are usually due to improperly formatted/encoded files. Different browsers/devices do not support the same media formats in their implementations of HTML 5 video. This due to mainly patent issues, open-source vs. proprietary and disagreement over which is the "best" format.

To make your video work in the latest versions of all major browsers, you will need to serve your video in both WebM format and MP4 format. To guarantee the broadest range of browser/device compatibility you may also need to include the Ogg format.

WebM: Firefox 4+, Chrome and Opera 10.6+
MP4: Internet Explorer and Safari
Ogg: Firefox 3.5+, Opera 10.5+

Go to http://html5test.com/ using your test devices to see what formats are supported.

Helpful info:

http://www.longtailvideo.com/html5/#media_formats

http://www.longtailvideo.com/html5/formats/


Prevent users from editing or viewing their own profile

Add this to a custom module:

function MYMODULE_menu_alter(&$items) {
  $items['user/%user']['access arguments'] = array('access user profiles');
  $items['user/%user']['access callback'] = 'user_access';
  $items['user/%user/edit']['access arguments'] = array('administer users');
  $items['user/%user/edit']['access callback'] = 'user_access';
}

This will put the user profile view under 'View user profiles' permission and edit under 'Administer users'.


FullCalendar does not display events except in the current month

My solution,
I switch in the view the 'contextual filter' the value 'when the filter values is NOT in the URL' from 'Provide default value' Type 'Current date' to 'Display all results for the specified field'.


How to prevent the user profile page of a blocked user to show up?

You should be able to implement hook_user_view in a custom module.

First create a page which contains your preferred content (e.g. "This user profile has been removed").  Let's call this node/1337 for now.

Secondly, you want something along the lines of the following:

function mymodule_user_view($account, $view_mode, $langcode) {
  if ($account->status == '0') {
    drupal_goto('node/1337');
  }
}

There are other parameters you can pass to drupal_goto if you wish (such as HTTP response code) - check out the API for more info :-)


Does your subtheme heritate from another theme? Maybe you can paste your logo in the super theme folder too to erase its default logo as well.

edit: Even if I think that it's not a good thing to change Drupal core or contrib modules/themes directly in the files.


Here is the right code:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function <your_module>_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['account']['name']['#title'] = t('First and last name');
  $form['account']['name']['#description'] = t("Rewrite this about spaces, periods (.), hyphens (-) and apostrophes (').");
}

feel free to ask :)
have fun!


How can I save an unpublished node skipping required fields validation?

I finally solved this using the Require on Publish module. It offers an additional checkbox to require only when publishing the node.

This module allows fields to be required only when the piece of
content is being published or is already published. This can be used
when you have fields such as tags or SEO information on your piece of
content that editors really don't need to fill in until the content is
going live.


Migrating Users from Older Versions of Drupal

Are Drupal's password hashing mechanisms consistent across different versions?

No, D7 and D8 use SHA512 with a salt. Drupal 6 uses MD5 without a salt.

If not, are there tools to support migrating user accounts and converting the passwords between versions?

Yes you can just rehash them.

If a no to migrations, are there modules that provide a standard experience for this situation that allows an old user to pick a new password?

Yes there is a really simple way (one example is). Make sure you BACKUP before you do anything. If this does not work for you, google how to convert drupal 6 passwords to drupal 7. There is a ton of different ways.

<?php
        require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
        $res = db_query('select * from drupal.users');

        if($res) {
                foreach ($res as $result) {
                        $hashed_pass = user_hash_password($result->pass, 11);
                        if ($hashed_pass) {
                          $hashed_pass  = 'U' . $hashed_pass;
                          db_update('users')->fields(array('pass' => $hashed_pass))->condition('uid', $result->uid)->execute();
                        }
                }
        }


How to change the path of views content?

may be you have used absolute url(starting from http://localhost:8082/content/..) instead of relative url(starting directly from content/..)


Unfortunately using rules is the only option to dynamically alter a product's price in Commerce 1.x. From the 2.0 roadmap:

  In Commerce 2.x, we should ensure that our modules define robust internal APIs that are then used by forms, Rules actions, etc. as opposed to embedding functionality into these systems' related callbacks. Most notably, we should seek to make price manipulation and price component management much easier as we open up the sell price calculation process to direct manipulation in module code (as opposed to strictly using Rules) when sell price pre-calculation is disabled.

emphasis mine.


Multiple forms in same page from single form builder returning the first form's value in submit

You'll need to implement hook_forms(), so that you can create 'aliases' of your forms.

For example, let's imagine a form named 'message_form', that you want to include multiple times on the page. To do this, you append a unique number to the form name each time when calling the form:

$page = [
  'form_1' => drupal_get_form('message_form-1'),
  'form_2' => drupal_get_form('message_form-2'),
];

return $page;

Next, you implement hook_forms() to watch for form names in the format above:

function hook_forms($form_id, $args) {
  // Act on form IDs that match the pattern message_form-[NUMBER].
  if (preg_match('/^message_form-\d+$/', $form_id)) {
    // The key is the form ID that has been passed.
    $forms[$form_id] = [
      // The callback is the actual form definition to be called.
      'callback' => 'message_form',
    ];
  }
}

Now each form being put on the page will have a custom form ID and therefore the system will know which form the submitted data refers to.


How to make a competition input form and a view?

To avoid writing a manual (to answer your question), here is a blueprint ...

Content type Game

Create a content type "game", with 2 entity ref fields to another content type like "player", and the other fields like date, etc.

3 Rules Components

Create 3 similar rules components (with parameters the score for player 1, and another parameter for score of player 2):

a 1st Rules Component with a Rules Condition to check if player1 has won, in which case you perform a 1st Rules Action to "set a data value" to set the "comp score" for player 1, and a similar 2nd Rules to set the "comp scrore" for player 2. Then add an extra Rules Action to save the entity (to ensure the comp value is also saved).
a (similar) 2nd Rules Component to check if player2 has won.
a 3rd , and one if the score was equal.

Custom rule

Create a custom rule like so:

Rules Event: before saving content of type "game"
Rules Actions: Perform 3 Actions, whereas each of these action performs one of the Rules Components create as described above.

Create a view games

Create a view of all your games. In doing so, use the Views Calc module to "add up the scores".

PS: I'm assuming this question is about D7.


For bypass Drupal permission, you can implements hook_file_download():

/**
 * Implements hook_file_download().
 */
function mymodule_file_download($uri) {
  if (someCondition()) {
    if (!user_access('some permissions')) {
      // Access to the file is denied.
      return -1;
    }
    else {
      return array('Content-Type' => file_get_mimetype($uri));
    }
  }
}


Is there a module/solution for allowing users to block each other on an SNS site?

Take a look at the Ignore User module.  From the project page:

  This module allows a user to "ignore" content from other users that
  they do not wish to view. Node and comment content from an ignored
  user is hidden from view on a page. A message is displayed above the
  hidden block of content with a link to the user's "ignore list" and a
  link to toggle display of the ignored user's block of content in that
  node or comment.

Not sure if it will handle blocking a profile view or not, but it should block content.


Can I create a node that acts as a pointer to another node of the same type?

You can create a view that lists contests in newest/descending order and limit it to 1 item, and use that to return the nid of the lastest contest, or if you are comfortable with SQL, do something like select nid from {node} where type="contest" and status=1 ORDER BY created DESC limit 1 to get it.

You can then use that as an argument to another view that returns recipes based upon what contest they reference, eg, all recipes with a contest node reference of nid.

You can do that all inside the views UI with default arguments and so forth, or create a module to do it.

MORE SPECIFICS--the easy part:

create a view, filter it on published recipes
put in the fields area whatever you want to see, eg, the title linked to the recipe, a node teaser, etc.

MORE SPECIFICS--the hard part:

add an argument to the view:

a. select the field in recipe that is the node reference to contest

b. in action to be taken if argument is not present, select php code and enter:

$nid=db_result(db_query('select nid from {node} where type="contest" and status=1 ORDER BY created DESC limit 1'));
  return $nid;
save everything :)
Preview the view.  What should be happening now is the view will be returning all recipes that have the latest contest nid (aka node reference) in the field you entered in the argument above.


What are some drupal 7 mega menus that allows view blocks to be inserted?

You can use Menu Attach Block module to render block as menu.

  Menu Attach Block allows you to attach blocks to standard core Drupal
  menu items. This is especially useful for creating complex dropdown
  menus and mega menus.

  Any block can be used, including blocks generated by other modules.
  Blocks generated by Views are particularly good candidates for
  embedding.


Which module will allow a user to grant another user permissions for editing content of content type

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

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

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

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

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

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

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


Those are added there via Javascript of the Lightbox and Admin Menu modules. You can either disable those modules or modify/override their Javascript. You could also use custom Javascript to remove the classes from the body element. Anyway, the question is, why would you want to remove the classes?


There is no bug.  I ran the import the first time, then discovered that I was migrating nodes to the wrong content type, so ran it again with the correct content type.

Thing is, if you don't configure your destination content type as allowing comments, then comment migration will be skipped for all sources mapped to that destination.

So, I thought d2d ui wasn't working correctly when all the time it was my configuration.  Oops!


If you are getting that error is because you are probably using a shared host instance at 1and1, and these instances are mostly better for simple static HTML sites of the kind you would create by hand in Dreamwweaver, for example.

If you are hosting a small Drupal site with a few modules, a small database, and a few visitors, then perhaps 1and1's cheapest (shared host) package will suffice. But as your sites grow bigger, shared host packages tend to not cut it (regardless if they are hosted at 1and1, godaddy, dreamhost, etc).


How do I display a sorting button in views?

You can set your filters and sorts to be exposed, which means the end user can interact with them choosing how to sort or filter the results,

There is also a setting in the "Advanced" column on the right of the views admin page called "Use AJAX". Set that to "Yes" and you will no longer have to have page loads when the user changes filters and sorts.

Note: If your view is a block view, you must turn on ajax for exposed filters to work.

Also, in the "Advanced" column if you click the "Settings" link for the "Exposed form style" option. In there you can check the "Autosubmit" checkbox, which will mean the view will be reloaded when the user selects a filter, without them having to click submit. This may or may not be desirable depending on your use case.

One last thing is the "Exposed form in block" setting. If you set that to "Yes" then a block will be available that will contain the filter and sort settings, so you can put them wherever you want, instead of them having to be in the top of the view.

Note: You cannot use exposed form in block with a block view. A potential workaround (I have not actually tried it) is here - https://drupal.stackexchange.com/a/38994/10729


Previous setup:
Create a new computed field for the content type where you want to work:
Extract the names from the multivalue field (entity referenced field)

foreach ($entity->field_campos as $field) {
}
foreach ($entity->field_campos as $field) {
}
foreach ($field as $index => $valores) {
$terminos[] = $valores['value'];
}
$item2 = field_collection_item_load_multiple($terminos, $reset = FALSE);

$referenced_titles = array();
foreach ($item2 as $indice => $values) {
  $referenced_node = node_load($values->field_nombre_2['und'][0]['target_id']);
$entity_field[]['value'] = $referenced_node->title;
}

Now that every node from this content type has a special field for extracting the values in a more "flat" way we can compare two views.
The first with the name list (usually partial) and the second, a views containing the full name list.

<?php
$result = views_get_view_result('calendari_intern', 'nombres');
$result2 = views_get_view_result('nom_expedients', 'entityreference_1');

First load both arrays. The first one, is the view result with partial name list. The second, is the view of the full name list.

Extract and create a new array saving only the names from the arrays:

foreach ($result2 as $index => $val) {
$expedient[] = $val->node_title;
}

Do the same in the other one:

foreach ($result as $index => $values) {
$entidades[] = $values->_field_data[nid][entity];
}
foreach ($entidades as $indice => $valores) {
if ($valores->field_nombres[und] !=NULL)
$casi[] = $valores->field_nombres[und];
}
foreach ($casi as $indice2 => $valores2) {
 foreach ($valores2 as $indice3 => $valores3) {
if ($valores3["value"] != NULL) {
$misnombres[] = $valores3["value"];
}
}
}

Then compare the arrays with array_diff function.

$diferencia = array_diff($expedient, $misnombres);
echo '<pre>';
print_r ($diferencia);
echo  '</pre>';
?>


You can get it like this :

$term = taxonomy_term_load($tid);
$field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
if ($field_header_image) {
  $headerimg = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
}
print render($headerimg);

If you want to use an image_style :

$headerimg = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'my_image_style', //place your image style here
  ),
));

Here is a contextual answer if you are on your taxonomy term page.

In your file template.php use the theme_preprocess_page function like this :

function mytheme_preprocess_page(&$vars) {
  $term = menu_get_object('taxonomy_term', 2);
  if ($term) {
    $field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
    if ($field_header_image) {
      $vars['headerimg'] = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
    }
  }
}

Then in you page.tpl.php you can print render($headerimg);


Change the name of uploaded file based on content type and entity id

You might be able to do this with hook_ENTITY_TYPE_update().  Take a look at the D8 version of the upload_replace module code for an example of changing filenames.


Images are directly served by the web server. You need to configure your web server to server images (and other files) with the appropriate headers. On Apache HTTP server, this is usually done with the mod_expires module.


how do i programmatically set the ANONYMOUS USER permissions on a site install profile?

There is a constant for the anonymous RID named DRUPAL_ANONYMOUS_RID.

So, you would be able to use something like:

user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('your permission 1'));


Filter Taxonomy reference field on Workbench Access permission

You must install Taxonomy Access Control module. Follow this steps:

1) Enable the module.

2) Go to admin/config/people/taxonomy_access

3) Click configure link for role "editor"

4) Click "Add vocabulary" link. Then select the vocabulary where you have terms "Term A", "Term B" and "Term C" and press "Add" button.

5) Click "Add term" link. Select "Term A". Configure permissions for this role and term (you should select "Allow" in every case). Once done press "Add" button.

6) Do the same for Term B

7) Do the same for Term C, but this time select "Deny" in every case.

8) Press button "Save all"

9) Go to previous window and do the same but this time for role "editor c". However you have to do the opposite: Terms A and B should have "Deny" in every case and Term B should have "Allow" in every case.

I hope this helps you! If it doesn't, you should checkout the Organic Groups module too. In case you need Organic Groups notice you also have OG Vocabulary module.


I have faced the same issue and resolved it by selecting "POST" method from dropdown list.

Find the below image:-

OUTPUT:-
{
    "current_user": {
        "uid": "1",
        "roles": [
            "authenticated",
            "administrator"
        ],
        "name": "admin"
    },
    "csrf_token": "XXXXXXXXXXXX",
    "logout_token": "XXXXXXXXXXX"
}

Note: we can get this output for the first time, if we try for the second time we will get message like

  {
      "message": "This route can only be accessed by anonymous users." }

because postman works as a browser.
To get it work for the second time we need to remove the cookie from postman.

Kindly let me know if I am wrong.
Thanks..


Can't track why Boost-Crawler doesn't work

What you're seeing may be correct behavior. Boost Crawl (a submodule but without its own drupal.org page) is careful to warn that; "Minimal crawler - expires and regenerates pages only when content is edited and on next cron run" [Emphasis added.] SO, it will track content that you have edited, not crawl the site and thereby refreshing the page cache.

Enabling Boost and boost crawl on my site, and then running cron (using drush -v cron to spy cron output) I essentially saw what you saw, in my case just my home page. Running Xenu (explained below) triggered a populating of the boost cache for my entire site. Maybe this is what you were expecting?

If you want to refresh your site's boost cache index, check out either

xenu link slueth
httrack
or on Mac SiteSucker

You didn't ask, but each of these are invaluable web site QA tools as well.


How to use last parameter (term) as a filter in a view

Yes, you can add a separate block with the same settings and in the contextual filter get form from the url.

Add the blocks in the same region and in the visibility settings select Only the listed pages and add docs/*/* for child terms and to the other block add docs/* for the parent terms.

UPDATED:

If you have a Taxonomy type page view then you can do the following thing.

Create tow pages with path as docs/* for parent terms and docs// for child terms i.e. form.

In the contextual filter add term id and select This Page override. and check Provide default value. In the Type drop-down select Raw value from URL and then from Path select 3 for docs/%/% path and 2 for docs/% path.


Multi-site installation and one theme: how to know on which multisite user is?

i would suggest doing multiple themes, one per site/group of sites - where they all have a common theme as parent.

that way you can overwrite specific elements on individual sites without having to worry about adding all the logic to check what site your currently rendering content for.


Read contents of uploaded file before saving

The ['value'] value is typically found on fields that just store 1 kind of thing, like a text field. Other field types use whatever they need – case in point, the file field type will have an array of many values:

$node->field_some_file_field_name['und'][0] = array(
  fid => 650, // The file ID, which is important and cool.
  display => 1, // Show the file when a user views the node.
  description => 'foo',
  uid => 7, // The user ID who uploaded this file.
  filename => some_file.pdf, // The **original** filename.
  uri => public://some-dir/some_file.pdf, // The URI to access the actual file.
  filemime => application/pdf,
  filesize => 3067583,
  status => 1,
  timestamp => 1352331360,
);

The FID is a cool thing, because the file_managed table stores the references to files (including all of the info above) and an entity only needs to know the FID in order to join with this table and get all of the file's metadata without reading the file.

To read the contents of the file, you have a few options:

drupal_realpath($uri) function to generate the server path to
the file
file_create_url($uri) function to generate an HTTP path
to the file (i.e. an image to be displayed in an <img> tag.

Not sure what you mean explicitly by "read contents", but a literal file_get_contents() would look like this:

$filepath = drupal_realpath($node->field_some_file_field_name['und'][0]['uri']);
$file_contents = file_get_contents($filepath);

If you want to check the MIME or filesize or something like that, you already have that data available to you in the field's array.

If you can elaborate on "reading" the file and what you might like to do before the file field is attached to the node, please update your post and I'll try to update this answer accordingly. There may be another, better place for your work to happen.


Solved by upgrading to the most recent version of Meta tags module.

Thank you to Patrick Kenney for pointing me in the right direction.


Create block user flag, hide users from view

I couldn't find a way to do this within Views, despite the seemingly simple task and the various decent explanations found around the internet (nit3ch's comment included). The explanations limited the view results too much or in the wrong way.

I ended up using a Views PHP filter field to perform the filtering task:

global $user;
$flags = flag_get_user_flags('user', NULL, $row->uid);
if( array_key_exists('block', $flags) && array_key_exists($user->uid, $flags['block'])){
    //dsm($row); // optional debug
    return TRUE; // prevents row from being displayed
}


Programmatic user registration not forcing user to activate account

You can use the LoginToboggan Prevent preauth module is available for Drupal 6 and 7.
And it realy does all the stuff. We can have "Email account activation without admin approval and also a user set password".

Code:

    $new_user = array(
      'name' => $username,
      'pass' => $password,
      'mail' => $email,
      'status' => 1,
      'init' => $email,
      'roles' => array(logintoboggan_validating_id() => TRUE)
    );
   $account = user_save(NULL, $new_user);
   // Send mail with account confirmation
   _user_mail_notify('register_no_approval_required', $account);

P.S. Don't forgot to uncheck 'Immediate login' option.


How to use Display Suite to trim whitespace from a field

Sorry for the digression — but semantic markup does matter. This articles speaks well to what it is: https://boagworld.com/dev/semantic-code-what-why-how/

Your input filter (or, less possibly, your rich text editor) is adding the paragraph tag. Check out the input filter you're using for this field. If this filter has "Convert line breaks into HTML (i.e. <br> and <p>)" enabled, found here: admin/config/content/formats/<inputfiltername> — this could be adding paragraph tags. Keep in mind changing this will impact how all your fields that use this input filter are rendered. You can always create an additional input filter to suite your needs.


Webform module uses the mail() for sending the mails. SMTP Authentication Support module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server.

Along with SMTP Authentication Support module you would need to install the Mail system module and configure it to assign a smtp class to webform which is  step by step explained in this tutorial.

If you have SMTP module installed in your drupal site than you would have to configure the SMTP settings (/admin/config/system/smtp) for sending the email

Example (Configuring SMTP for GMAIL):

A. INSTALL OPTIONS:
 1. Turn this module on or off: (SELECT "ON")

B. SMTP SERVER SETTINGS:
 1. Server: smtp.gmail.com
 2. Backup server: (LEAVE BLANK)
 3. Port: 465
 4. Use encrypted protocol: (SELECT "Use SSL")

C. SMTP AUTHENTICATION:
 1. Username: (ENTER YOUR GMAIL EMAIL ID)
 2. Password: (ENTER YOUR ABOVE EMAIL ID PASSWORD)

D. E-MAIL OPTIONS:
 1. E-mail from address: (ENTER YOUR GMAIL EMAIL ID AS ENTERED ABOVE)
 2. E-mail from name: (ENTER SITE NAME, ITS DEFAULT VALUE IS DRUPAL VERION)
 3. Allow to send e-mails formated as Html (ENABLE CHECKBOX IF YOU WANT)

E. SEND TEST E-MAIL:
 1. E-mail address to send a test e-mail to:
   (ENTER YOUR EMAIL ID AT WHICH YOU WANT TO RECEIVE TEST MAIL)

Instead of GMAIL if you want to use some other service provider than check their server details and the port details.


How to display something conditionally in template file depending on the current path

Drupal core's template suggestions allow for naming page templates based on the path of the page. So, theoretically, if you had www.mysite.com/registration-a, then you could use the the page template name page--registration-a.tpl.php and so forth.

However, if this does not work, you can create a page preprocess function in your theme or module that adds some template suggestions based on the path.  For example:

function THEME_NAME_preprocess_page(&$variables) {

 if($arg[0] == 'registration-a'){
 $variables['theme_hook_suggestions'][] =  'page__registration_a';
 }

 if($arg[0] == 'registration-b'){
 $variables['theme_hook_suggestions'][] =  'page__registration_b';
 }

}

this would allow you to use page--registration-a.tpl.php and page--registration-b.tpl.php, etc.

For reference, $arg is an array that contains the different parts of a URL, so if you had the path mysite.com/registration/customer, then $arg[0] would be 'registration' and $arg[1] would be 'customer'.


Works by me but only with jQuery version 1.8 and lower.

The above comment worked like charm!!!
I had jquery 1.10 so i downgraded it to jquery 1.8


Assigning (adding) an entity reference when an Order process is completed

Not a hook but an event.

Orders have an attached workflow. You can listen to the event of an order being placed, see the state_machine module for documentation on this. Basically, you need to define an event subscriber service, subscribe to the event commerce_order.place.post_transition, then check if order is an ebook and if so act based on the order customer ID.

The subscriber method needs like this:

public function orderStateChange(WorkflowTransitionEvent $transition_event) {
  $entity = $transition_event->getEntity();
  // Check the transition id and whetever else you need on the order and then do your thing.
  if ($transition_event->getToState()->getId() == 'completed' && ...) {

  }
}


Display Content Type Field in region--footer.tpl.php

Like I said, fast and dirty:

$nid = XXX;
$node = node_load($nid);
print check_plain($node->field_name['und'][0]['value']);

Put this into your Template. I assume your field is not translated.


Depending on your theme, you should be able to do something like this:

function YOURTHEME_preprocess_html(&$variables) {
  global $user;

  if ($user->uid) {

    if (arg(0)=='admin') {
      $variables['classes_array'][] = 'admin-page';
    }
    if (arg(0)=='node' && arg(2)=='edit') {
      $variables['classes_array'][] = 'node-edit-page';
    }

  }

}


There might be better ways to do it, but this what I did in my case.

In hook_form_alter loop through the '#options' for this field.
Store every item in a new array skipping the one you don't want as options for this field.
 (in my case it was the item at index 0 with value 'N/A').
Assign this new array of options as '#options' for the field.

Worked for me.


Custom entity api create options list for checkboxes without field api

To store multiple value property values, without the field API, you may find it easier to create a generic extended properties table for one-to-many relationship with the base table.

e.g a table

Table: my_entity_properties

Columns: entity_id | revision_id | name | value

You can then store the extended properties in that table in the save function for your entity - each field value will be a row with the property name and value pair.
You then load them in the attachLoad function, grouping by the revision_id and property name to load the values for that entity revision.


File (Field) Paths upload/remove not recognized

I have finally discovered the issue. Even though the node shows a status of published there is actually a draft. Up until the upgrade users were able to publish the content they created using Workbench Moderation. Now after saving an edit to the node the status never changes to draft and will not allow the user to publish the content. The only way the content can be published is by an administrator setting the Moderation status at the bottom of the page and then saving the record.

I have not been able to find a way to correct this issue yet. I will post a separate question that has a clearer description of the issue now that I have one.


The solution to the the problem is to dynamically add event subscribers later in the page load process, so for example:

  /**
   * {@inheritdoc}
   *
   * We can't return the plugin-based events here, but we set up
   * a response to do that at a later stage
   *
   */
  static function getSubscribedEvents() {
    // Subscribe to kernel request very early.
    $events[KernelEvents::REQUEST][] = ['onRequest', 900];

    return $events;
  }

  /**
   * Add the plugin events at this stage - early in the process.
   *
   * @param GetResponseEvent $event
   */
  public function onRequest(GetResponseEvent $event) {
    // Find every event mentioned in a plugin...
    foreach ($this->notifierManager->getNotifierEventNames() as $eventName => $plugin_id) {
      // Add the event to the dispatcher as a listener, to call that routine...
      $this->dispatcher->addListener($eventName, [$this, 'onNotification']);
    }
  }

The list of event names is cached in getNotifierEventnames().


Deny Access (instead of 404) for non-existant user accounts

I would try setting up a conditional redirect from your 404 page to your custom users-specific error page, that only fires if the path of the referrer is user/*.

I would try to do this using Rules.


Why do I need to enable the Drupal Bootstrap theme when using a Bootstrap subtheme?

I do not why, but bootstrap sub-theme requires bootstrap theme also enableled in order to inherit all settings, in D7 theme and sub-theme must be to be in sites/all/themes folder, D8 theme and sub-theme in /themes folder, just do it and all will work fine.


How to import Profile2 users with taxonomy terms using Feeds?

In the feeds reference importer>mapping click the button under "Search taxonomy terms by: Term name" on the term reference mapping you're wishing to search and click the check box, then save.


Creating a list of node-options in different node

I think what you're wanting can be accomplished with views.  You may need to add some fields to make the context work for your needs.


How to do core development with composer-based install?

I'm providing an answer to this even though it's probably off-topic and I have a heavy bias here.
For core development we shouldn't use a composer-based install pattern such as drupal-composer/drupal-project because we're modifying the software project itself. Generally composer require or create-project or init is used when we want to create a new library, project or piece of software and dependencies to it, but not when working on an existing library or framework.

At the moment the best way to get started if you are new to core development is to visit https://drupal.org/tools. Use either the ResilioSync option or download the latest quicksprint tools release instead. This is the tool set that the Core Mentoring program currently uses to get started from scratch.
This isn't the only place/work flow for core development. Many of the core/strategic initiatives, or working groups within core development, may have a preferred development environment. For instance the Javascript Modernization Initiative has excellent documentation for their unique work flow and challenges.
Of course, if you already have an environment, then cloning the repository and running composer install works as well.
Finally if Composer piques your interest, the Composer Initiative (this is probably only relevant from 2019-2021) may change the way that we can work on core. And this could be a way to contribute and answer your question.

Please ask any questions you might have in #contribute on Drupal Slack or in one of the contribution channels on either IRC or Drupal Chat.


If you already have a custom node template (tpl file) to theme your node then you're halfway there.  You can use <?php print_r($node); ?> to see the node structure and find out how to print your fields.

For example, to print those 3 fields, you can use something similar to:
<?php print $title; ?>
<?php print $node-field_img['view']; ?>
<?php print $node->content['body']['#value']; ?>

Remember to use the print_r($node) to check the structure and print the fields similarly as above while including the HTML for the layout.


Fatal error: Allowed Memory Size of (X Size) when running drush migrate-upgrade

You need to check for the right php.ini file. Be aware, that drush is using the CLI (command line interface) version of PHP, which might use a different php.ini file than the version used by your web server.

Your above error message states, that the CLI version has a memory limit of 128MB only (which is the default value that might even be used when there is no php.ini file for your PHP version).

In Windows you can find out the used php.ini file - or the folder where it is expected - by typing the following command to your Windows command prompt:

php -i | findstr /c:"php.ini"

In Unix compatible systems you could use grep instead:

php -i | grep "php.ini"


How do I update a user profile with entity_metadata_wrapper()?

Since you are using an entity wrapper, you must use $entity->save to save the updated user object. In your case, use $wrapper->save.
user_save() can be used when the user entity is loaded using user_load().


How do I create a file download popup form?

Email Download does just what you want.

  A tiny module to make downloads only available to people who submit their email address to the site in case the site creator doesn't want visitors to be required to create an account. The email is checked for validity and a cookie with a hard to guess authentication string is stored in a browser cookie. The next time (and of course this first time) the user makes a download, the cookie is checked and the user can proceed. This of course requires cookies to be on on the client side.


How do I create a file object from a local file?

You need to specify the path to your module:

$module_path = drupal_get_path('module', 'module_name');

$uri1  = file_unmanaged_copy("$module_path/checklist1.pdf", 'public://checklist1.pdf', FILE_EXISTS_REPLACE);


Is there a built-in way to get a language+country locale pair?

you can get default country value using

<?php
print variable_get('site_default_country', '');
?>


User images slideshow: first slide from reference entity

Found a solution here using view field views module by putting my user entity field view inside my node entity view.


Change all article text format to basic html

While you might just need to add/configure the full_html text format, you can update the text format for all body fields to basic_html via a DB query ( and clear cache )

db_update('node__body')
  ->fields(array('body_format' => 'basic_html'))
  ->condition('bundle', 'article')
  ->execute();

db_update('node_revision__body')
  ->fields(array('body_format' => 'basic_html'))
  ->condition('bundle', 'article')
  ->execute();

The raw SQL equivalent (e.g for PHPMyAdmin) is:

UPDATE node__body set body_format = 'basic_html' where bundle = 'article';
UPDATE node_revision__body set body_format = 'basic_html' where bundle = 'article';

Backup your database first


You can see here

  In Drupal 8 hook_boot() was removed since the same results can be
  achieved with other ways, for example:

  A module that needs to interrupt the request very early based on certain conditions can use an event listener (see #1794754: Convert
  ban_boot() to an event listener) (Note that modules are loaded by this
  stage unlike in Drupal 7.)
  A module that needs to run on cached pages should prompt its users to add code in settings.php


How do you add help text to a form item?

The description doesn't live under #attributes, but under the element directly.

So you must do something like this to get it to work:

$form['field_event_date_value2']['#description'] = 'DD/MM/YYYY';

The HTML class is not the fieldname, but rather something like field_event_date_value2 in your case.

If that is not the correct fieldname, you can try to print_r(array_keys($form)) to see if you can see what the correct name is.


Add a custom action on admin content page

Here is a sample code which creates a custom action plugin which modifies node title.
action_plugin_examples/src/Plugin/Action/ArchiveNode.php
<?php

namespace Drupal\action_plugin_examples\Plugin\Action;

use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\pathauto\PathautoState;

/**
 * Provides an Archive Node Action.
 *
 * @Action(
 *   id = "action_plugin_examples_archive_node",
 *   label = @Translation("Archive Node"),
 *   type = "node",
 *   category = @Translation("Custom")
 * )
 */
class ArchiveNode extends ActionBase implements ContainerFactoryPluginInterface {

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Logger service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * The path alias manager.
   *
   * @var \Drupal\path_alias\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * Language manager for retrieving the default Langcode.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = new static($configuration, $plugin_id, $plugin_definition);
    $instance->logger = $container->get('logger.factory')->get('action_plugin_examples');
    $instance->messenger = $container->get('messenger');
    $instance->aliasManager = $container->get('path_alias.manager');
    $instance->languageManager = $container->get('language_manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function access($node, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $node */
    $access = $node->access('update', $account, TRUE)
      ->andIf($node->title->access('edit', $account, TRUE));
    return $return_as_object ? $access : $access->isAllowed();
  }

  /**
   * {@inheritdoc}
   */
  public function execute($node = NULL) {

    /** @var \Drupal\node\NodeInterface $node */

    $language = $this->languageManager->getCurrentLanguage()->getId();

    $old_alias = $this->aliasManager->getAliasByPath('/node/' . $node->id(), $language);

    $title = $node->getTitle();
    $date = $node->created->value;
    $year = date('Y', $date);
    // $old_alias = $node->path->alias;
    $new_title = $this->t('[Archive] | @title', ['@title' => $title]);
    $node->setTitle($new_title);
    $node->setSticky(FALSE);
    $node->setPromoted(FALSE);

    $new_alias = '/archive/' . $year . $old_alias;
    $node->set("path", [
      'alias' => $new_alias,
      'langcode' => $language,
      'pathauto' => PathautoState::SKIP,
    ]);

    $node->save();

    $message = $this->t('Node with NID : @id Archived.', ['@id' => $node->id()]);

    $this->logger->notice($message);
    $this->messenger->addMessage($message);

  }

}

action_plugin_examples/config/optional/system.action.action_plugin_examples_archive_node.yml
langcode: en
status: true
dependencies:
  enforced:
    module:
      - action_plugin_examples
  module:
    - node
    - pathauto
id: action_plugin_examples_archive_node
label: 'Archive Node'
type: node
plugin: action_plugin_examples_archive_node
configuration: {  }

Note : plugin yml file needs to be in the below format.

system.action.<plugin_id>.yml


Hooks and preprocessor confusions. A few important questions

Not quite. Generally speaking, normal hooks are used to control the behavior (functionality) while theme hooks are used to control the appearance of your site. If you want to understand more about hooks, you may want to read What are the different types of hooks?.
Since Drupal 7, you can implement hooks in your theme. That said, the best practice is to put alterations to the site behavior in a custom module, and use your theme only for alterations to the appearance.
That depends on the hook. The output of a block can be altered by implementing hook_block_view_alter.
All modules that are built 'the Drupal way' should use theme hooks and render arrays to generate their output. You can always implement a preprocess function in your template.php to alter variables before they go to a template, or override a theme function or template to make it do what you want. See the Theme guide, more specifically Overriding themable output to learn more.

I hope that answers your questions.


Unable to rebuild a form in submit handler

What exactly do you expect to happen when it's "rebuilding"?

I should simply call buildForm() again, but that will build the same form, so visually, you won't see a difference. The only ondication would be that it's doing only a POST request, while a non-rebuilding form submission does a redirect to the same page after submitting.

If you e.g. want to see additional rows in your list, you need to store the desired max with $form_state->set('max_rows, 5) and then in your buildForm() method, read it again from there with get()


Making contextual node paths and reference lists

You need the Views Module.  I have both of the other modules enabled, so I am not certain exactly what functionality they contain applies.  The module Views Field View allows the user to contain a view in a field of another view.  I do not think that is necessary for what you want to do.  If you are not familiar with views I recommend watching the "Taming the Beast" video series at Nodeone.se. It will give you a good idea on how you will want to proceed.


Using code we can calculate total weight using product quantity and weight from uc order. Then its possible to add additional weight according to your conditions and pass the calculated total weight according to your need.


Here are 2 possible paths. I used the first one:

Path 1:

Stage A:

Go to Structure > Contact forms, and there to "Personal contact form".

Under "Manage fields" delete any custom fields you might have added.
Under "Manage display", make everything as hidden (under both labels && formats).
Optional - Under "Manage form display", make everything hidden.

This will totally hide the native personal contact form.

Stage B:

Create a new form, from scratch; Add desired fields to it under "Manage fields", and under "Manage form display" && "Manage display" hide all automatic fields taken from "Personal contact form".

Link to the new form from a menu, and that's it.

If you are new to Drupal in general and using Drupal 8, check Youtube for video tutorials on how to create basic contact forms and make sure to use the steps above if you want to build your contact-form from scratch.

Path 2

It is best to use the native "Personal contact form" and its native fields that are auto-replicated for other secondary forms if you pursue a minimalist approach, and I, as one who pursue such approach would gladly use it if I could have its fields auto-translated to my sites default language, but without the well known bug in the current Drupal 8 branch (8.1.x) yet to be fixed:

Due to the bug, you can't use the management interface in English and forced to have a XYZ language translated management interface - In some cases it's problematic from at least one reason).

Until this bug will be fixed I personally will use the first path, and might change to path B sometime in the future (in any case its a matter of minutes).

Notes

I suggest creating your block names only as a singular-phrase names, that doesn't contain any non-letter characters.


Is it possible to detect access to table on site db table and redirect the db query to a db shared by multiple websites?

You don't need to intercept all the query done for a database table. It is enough you change the settings for the database in the settings.php file.

Suppose that the default database definition is the following one.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'collation' => 'utf8_general_ci',
);

If you change it as follow, you change the database used for that particular table.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => array(
    'oauth2_server_client' => 'otherdatabase.',
  ),
  'collation' => 'utf8_general_ci',
);

In this way, you are telling Drupal that for the oauth2_server_client table, the otherdatabase database needs to be used. That database needs to be accessible from the same database user (username, in my example).

Generally speaking, you can alter the query done from a module if:

The query is a dynamic query
The module added a tag to that query, such as in the following code

$query = db_select('node', 'n')
  ->addTag('node_access');

In that case, you could implement hook_query_alter() or hook_query_TAG_alter().

In your case, since you want to change the database table used for all the queries to that table, I would change the database definition in the settings.php file.


How do I modify the content of a select list field?

Have a look at Restricting node reference values to owner

As described there, you can select a view as the source for the node reference selection. In that view, you can apply whatever conditions you want to that list.


How do I translate the tab menu of a view?

Go to admin/config/regional/translate/translate and search for the tab titles you want to translate. Since you have the required modules installed you should be able to find them there.


How can I do with Views and Drupal 7 what the Views Or module does in Drupal 6?

In your views filter area it is possible, Click re arrange if existing filter there, other wise configure it on adding new.

In the following window you can configure the or or and, between fields and filter group


Unable to access translated node content

Turns out this issue was due to my settings on the Detection and selection page at /admin/config/regional/language/detection. I reordered URL to be above User and the translations are now showing.

Hopefully, this is able to help someone else in the future.


Modelling one-to-many relationships with content types

From my understanding of your question,I think you need to use Entity Reference


Try to use any of these modules.

Conditional Fields - This module definitely solve your issue. How to use.

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API.

Dependent Fields

  The Dependent Fields module (formerly AHAH Dependent Fields) allows
  cck based fields to specify another field as a controller field, and
  react to its changes on the form using AHAH/AJAX without the form
  re-loading.

Dynamic dependent fields

  Makes field value or options depend on other field values when editing
  entity.


How should I setup Drush to work with Drupal 8.8.1 using Git Bash on Windows 10

No, you don't install Drush globally anymore. You install the Drush Launcher instead. It will provide you a global drush command that automagically uses the local Drush from each project.

  Drush Launcher

  A small wrapper around Drush for your global $PATH.


Cannot load ctools automodal associated menu call from another module

I think you need specific class for your link to be preprocessed as a modal link (but i don't know the 'automodal' feature so maybe im wrong)


How do I create a new Slideshow in the header?

This is just a guess since the information provided is very limited: Often slideshows in the header are output as background images on the theme level. So maybe you should have a look at your page.tpl.php (and maybe also your template.php) to see if at some point the view is called from there and not from the panel.


why importer cannot map to custom field type

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

hook_feeds_processor_targets_alter

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

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

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


Load block programmatically, result: <drupal-render-placeholder

When calling ->render() it is rendering a structured array tree assuming that it is part of a whole page which will then do placeholder replacements later.

Use renderRoot() if you are the last instance and e.g. return this directly as an AJAX or JsonResponse.


How can I protect a disabled form from being submitted?

Found the issue! It seems to be a Drupal bug.

#access set in #after_build does not completely override the #access settings, set in hook_form_alter.

In theory, a form is altered by hook_form_alter and hook_form_alter is altered by #after-build. When I try setting #access in hook_form_alter, to alter the form, everything works. However, when I try setting #access permissions in #after_build, to alter hook_form_alter, it only hides the form, still allowing anyone to submit it, by altering the code on the client side.

As a temporary solution, I disabled URL alias permissions, by unchecking "Administer URL aliases" and "Create and edit URL aliases".


How do I test a CKEditor text format field with Behat/Mink?

This doesn't yet have official support in the Drupal Extension.  The linked thread has some examples that use traits.
However, I found this gist by johnennewdeeson to be a faster, easier solution for me, just cut and paste into FeatureContext.php:
  /**
   * @Then I fill in wysiwyg on field :locator with :value
   */
  public function iFillInWysiwygOnFieldWith($locator, $value) {
    $el = $this->getSession()->getPage()->findField($locator);

    if (empty($el)) {
      throw new ExpectationException('Could not find WYSIWYG with locator: ' . $locator, $this->getSession());
    }

    $fieldId = $el->getAttribute('id');

    if (empty($fieldId)) {
      throw new Exception('Could not find an id for field with locator: ' . $locator);
    }

    $this->getSession()
      ->executeScript("CKEDITOR.instances[\"$fieldId\"].setData(\"$value\");");
  }


Edit view link redirected to preview link automatically

It is not a problem, it's done on purpose for convenience of being able to quickly edit the view and return to the page where you were at initially.

If you want to stay at edit page then just remove the ?destination=node part from the URL: http://localhost/xxx/drupal/admin/structure/views/view/products/edit/block_14


Using Drupal Commerce Product Reference Field, missing products

Check the setting of this field. It looks like it is set to 10. Just make it blank and it should allow for all of the products to be shown.