Content access based on the content author's role

The permission on "own content" is connected to the node's author's uid and only relates to role in that a user with the role holding that permission can edit a node they created.

How I would solve your use case is with a hook_node_access in a custom module.
https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_access/7
WARNING: I just threw this together as an example, I did not test, and you need to put in the right role values.

hook_node_access($node, $op, $account) {
  if( $op !== 'update'){
    // not my use-case
    return NODE_ACCESS_IGNORE;
  }

  $author = user_load($node->uid);
  if( in_array( 'role1', $author->roles) && in_array( 'role1', $account->roles) ) {
    // the user editing has the same role as the author
    return NODE_ACCESS_ALLOW;
  }
  // repeat ... etc.

  // we did not find what we were looking for, continue with normal access check
  return NODE_ACCESS_IGNORE;
}


Programmatically find out what fieldset a field belongs to, if any

If you call field_group_info_groups with the entity type and bundle, it will return all the field groups on the bundle, the fields should be in the children array under ['form'][YOUR_FIELDGROUP] e.g.

     $fieldgroups = field_group_info_groups('node', "YOUR_NODETYPE");
     $field_names = $fieldgroups['form']['YOUR_FIELDGROUP']->children;

$fieldnames should now contain a list of all the fields that pertain to YOUR_FIELDGROUP. Which you can now parse through using a foreach loop.

     $node = node_load(2);
     foreach ($field_names as $key => $field_name) {
      $field_items = field_get_items('node', $node, $field_name);
      // Do something cool here.
     }


How do I check if the form is an add/edit/delete form?

You could use what said in this answer, with a slight modification.

function example_form_alter(&$form, &$form_state, $form_id) {
  if (strpos(request_path(), '/add') !== FALSE) {
    $page = 'add';
  }
  elseif (strpos(request_path(), '/edit') !== FALSE) {
    $page = 'edit';
  }
  else if (strpos(request_path(), '/delete') !== FALSE) {
    $page = 'edit';
  }
}


Turns out that in order to add to an existing field you have to drill down into the array.  The correct place to add the property is

$form['field_username']['und'][0]['value']['#ajax']


How does core triggers cleanup of expired sessions in database?

Configuring Garbage Collection

  When a session opens, PHP will call the gc handler randomly
  according to the probability set by session.gc_probability /
  session.gc_divisor. For example if these were set to 5/100
  respectively, it would mean a probability of 5%. Similarly, 3/4 would
  mean a 3 in 4 chance of being called, i.e. 75%.

  If the garbage collection handler is invoked, PHP will pass the value
  stored in the php.ini directive session.gc_maxlifetime. The
  meaning in this context is that any stored session that was saved more
  than gc_maxlifetime ago should be deleted. This allows one to expire
  records based on idle time.

  However, some operating systems (e.g. Debian) do their own session
  handling and set the session.gc_probability variable to 0 to stop
  PHP doing garbage collection. That's why Symfony now overwrites this
  value to 1.

  If you wish to use the original value set in your php.ini, add the
  following configuration:

# config/packages/framework.yaml
framework:
    session:
        gc_probability: null

  Source: Symphony's official docs on Configuring Sessions and Save Handlers

In Drupal this is seen in /sites/default/default.settings.php

/**
 * Some distributions of Linux (most notably Debian) ship their PHP
 * installations with garbage collection (gc) disabled. Since Drupal depends on
 * PHP's garbage collection for clearing sessions, ensure that garbage
 * collection occurs by using the most common settings.
 */
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

Since the above "most common settings" is set to 1/100, Garbage Collection would run 1% of the time.

Now, as per the code comment, I presume this does not get put into settings.php when it gets auto-generated if your distribution has one already set one in one of its files as I don't see this in my settings.php

You can also set this in services.yml as seen in this answer.

In Conclusion

Note that while Drupal is built on top of Symphony, it does not rely on Symphony for this. I just quoted their nice explanation from their documentation.

We learned that PHP automatically calls this gc() method every session.gc_probability/session.gc_divisor % of the time and if you look at PHP docs on SessionHandler.

  SessionHandler is a special class that can be used to expose the
  current internal PHP session save handler by inheritance. There are
  seven methods which wrap the seven internal session save handler
  callbacks (open, close, read, write, destroy, gc and create_sid).

  Source: http://php.net/manual/en/class.sessionhandler.php

core/lib/Drupal/Core/Session/SessionHandler.php

/**
 * Default session handler.
 */

class SessionHandler extends AbstractProxy implements \SessionHandlerInterface { ...

 /**
   * {@inheritdoc}
   */
  public function gc($lifetime) {
    // Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough
    // value. For example, if you want user sessions to stay in your database
    // for three weeks before deleting them, you need to set gc_maxlifetime
    // to '1814400'. At that value, only after a user doesn't log in after
    // three weeks (1814400 seconds) will his/her session be removed.
    $this->connection->delete('sessions')
      ->condition('timestamp', REQUEST_TIME - $lifetime, '<')
      ->execute();
    return TRUE;
  }


How to delete all Drupal content owned by a particular user?

A possible alternative to achieve what you're trying to do, is to use a combination of modules Views and Views Bulk Operations (VBO). With these modules in place, you could simply create a view of all the nodes "owned" by a user, and simply use the out-of-the-box VBO action to "delete an item" (after adding a VBO field like "Bulk operations: Content"). And by creating a similar VBO view, using the VBO field "Bulk operations: Content revision", you can probably also cleanup up the revision data.

If you need more sophisticated business logic to decide about the criteria related to "owned by a user", you could add Rules to such solution also and implement a variation of the solution described in my answer to "How to bulk update select list fields?", i.e.:

Create a Rules Component with a Rules Condition to checks if the node matches the criteria you're interested in.
Create a VBO enabled view of all nodes to be checked, whereas you'll use the Rules Component as your custom VBO action.

Done ...


Drupal 6: Having issues with multiple paged tables in pages with multiple tabs (JQuery UI tabs)

The problem was being caused by how the pager logic handles existing URI encoded parameters: it simply copies them, pre-pending any new URI encoded parameters used by the pager logic. The result being a duplicate of my 'active tab' parameter "tabset", the previous one present in a copy of the prior URI parameters, and the one I introduced in the paging link.

My solution was to parse the request URI myself inside my form logic, with knowledge that the first encountered "tabset" value is the active one, not the second (older) version at the end of the URI.

$activeTab = 0;
  $requestUri = $base_root.request_uri();
  if ($requestUri == '') {
    _devReport( '$requestUri is empty!' );
  }
  else {
    $requestArray = explode( '/', rawurldecode($requestUri) );
    // if course, this parsing logic is specific to my WebApp URI setup:
    if (($requestArray[0] == 'http:') &&
        ($requestArray[3] == 'WebApp')) {
      // this should always be true, but just in case:
      if ($requestArray[4] != '') {
        $split1 = explode( '?', $requestArray[4] );
        $split2 = explode( '&', $split1[1] );
        if ($split2[0] != '') {
          $split3 = explode( '=', $split2[0] );
          if ($split3[0] == 'tabset') {
            $activeTab = $split3[1];
          }
        }
      }
    }
  }

Now $activeTab has the correct value, even though it may be present a 2nd time in the URI with a different value.


As @Kevin already suggested.

In the following image, Please, see the red circle. From that input text area you can change the Label. Are you looking something else?


The admin/structure/types page lists all the content types implemented by modules, or the content type you created.
In the case of the Quiz module, there are content types created from sub-modules, such as the Short Answer module, all listed under the Quiz Question package. Once you enable the modules you need, you will see extra content types, on admin/structure/types.


How can I block users from registering with disposable email addresses?

Like you mentioned it is impossible to block all disposable domains.

If you want to end the madness, the most effective solution would be: Upon registration you send a confirmation link or code to a mobile phone number

Take a look at:

SMS Framework module
VoIP Drupal module

Using Unique field you could make sure that the phone number can only be used once.

Checkout: How to send SMS messages (Drupal Tutorial)


You probably want hook_page_build():

function slidedown_page_build (&$page) {
  $path = drupal_get_path('module', 'slidedown');

  drupal_add_js($path . '/slidedown.js');
  drupal_add_css($path . '/slidedown.css');

  $page['page_top']['slidedown_template'] = array(
    '#weight' => -1000,
    '#markup' => theme('slidedown_template'),
  );
}

I can't remember if that hook is too late to add JS and CSS.  You may need to put those in a template_preprocess_html().  That is a better choice that hook_init().


You can alter the title of the link using hook_node_view_alter in a custom module.

For example

function MY_MODULE_node_view_alter(&$build) {
  // dpm($build['links']['node']['#links']);
  $build['links']['node']['#links']['personal_blog']['title'] = t('view company blog');
}

You will have to use some logic to only apply the link to a certain user etc.

I'm not sure about the actual link concerned so if you have devel installed, uncomment the dpm() part and inspect the array to find the correct link.


You also have the chance to deliver double size low-quality images always. It is a valid and very popular technique.

You can do it with CSS or use the following module:https://www.drupal.org/project/hires_images


Using Entity reference + Views to create members select list

The view will need to know which group, which means a Context Filter.  So options there are usually the current url or the current signed in user.  Depending on where your entity reference is, and how you are getting to it, there might be a context available to fill your filter.  Then the view will be usable to limit the options in your reference field.  The more details you can provide about the use case, the better I can make this answer.


Multiple points openlayers geojson display only the last of it

Finally, i found out that the problems (only the last point and that point wasn't at the right place) had nothing to do with my geojson file : i created a new layer and by default it had projection EPSG:3857, but i needed a projection with GPS coordinates => EPSG:4326 see this . With that change, every point is now displayed. I guess with the wrong projection, all the points where somehow stacked, and then only the last one was displayable.

In Openlayer > Layers

Use Projection EPSG:4326 (instead of EPSG:3857)

In Openlayer > Map
Use

Map Projection EPSG:3857 (Default)
Display Projection EPSG:4326(Default)


You could do this in the preprocess_html function.

You should take a look at the i18n module, which allows you to have different frontages for each language, which could be an alternative (and better) way of solving the problem.


Only alter hooks and some specific theme-related hooks can be implemented in a theme.

hook_user_login isn't one of them, you need to implement it in a module.

To create a custom module see the official Creating custom modules docs. You essentially need a .info.yml file and a single .module file containing this:

function MYMODULE_user_login($account) {
  // Your code here
}


Usually how you set up product display is via nodes, so 1 node have a relationship to 1 or more products (Fx a specific t-shirt in different sizes). Since products themselves doesn't have a public display, they are rendered through the nodes you create. This means that it is also going to be the nodes that have the url.

Trying to create a node path alias based on 1 or more products is going to be very tricky, because you don't know how many products you have, what if the products has different taxonomy etc. Instead it might make more sense to using the taxonomy on the nodes, or maybe use them on both. A node with a taxonomy term is a pretty normal case which is well supported. This should fix all the problems you have with url aliasing.


If I understand well, I think that you can do this with Views, so you can expose a filter related with Taxonomy: Term ID related with your Vocabulary. Remember that you can use the operator 'Contains' if you want to be more laxed in the search.


JSON URL access restriction within Drupal

Simple answer is - you need to move credentials check and permission check to your Drupal. If app on a person's computer can see all the data, no matter what you do that person can see all the data just as well. So, in Drupal only allow certain role access to that path, and then only populate results with the data user should see.


manually adding terms to nodes directly from db

You may use the Feeds module to update all your nodes with new terms.


Creating a store open hours widget using Field API

I would check out the Office Hours module. It has a dev version for D7, you can either help finish the port, or at the least pick up some ideas on how to best accomplish this.


Think of "Support Client" as entity that pays for support. Or would pay if you'd charge. On your site you probably want two support clients: your company and external. Or, if you are B2B company, each of your client business should be defined as a support client, plus one for your own company. Then you can tie roles with support clients, like "marketing department" and "sales manager" are roles that belongs to "internal" support client, and "example company representative" belongs to "example support" support client.

Benefit of this is: all your internal roles can participate in your internal issues, and all roles of one of your clients can participate in theirs, but clients cannot peek at each other's support tickets, or at your internal ones.


How can I use $_SESSION in form handler drupal 8?

The suberglobal $_SESSION still works in D8 and is used by core several times.

For a correct Drupal 8 way see this change record. It shows how you access the session variable through the request object. But it doesn't show how to get the request object.

So this is an example for accessing the session in a form handler:

use Symfony\Component\HttpFoundation\Request;

  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {

    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);
    $form['counter'] = ['#markup' => '<p>#' . $value . '</p>'];

In a controller or form you can pull the request from the route parameter stack by putting a typed parameter Request $request in the build method.

If you are in a procedural form function get the request from \Drupal:

$request = \Drupal::request();


Fallback values for OG Meta Tags / hiding some unused OG fields

Also is there a good way to hide some of the OG tags that are not
  going to be used? (location, type and contact sections specifically).

You can use common css selector to do that:

.form-item-metatags-ru-og\:type-value,
.form-item-metatags-ru-og\:latitude-value,
.form-item-metatags-ru-og\:longitude-value,
.form-item-metatags-ru-og\:street-address-value,
.form-item-metatags-ru-og\:locality-value,
.form-item-metatags-ru-og\:region-value,
.form-item-metatags-ru-og\:postal-code-value,
.form-item-metatags-ru-og\:country-name-value,
.form-item-metatags-ru-og\:email-value,
.form-item-metatags-ru-og\:phone-number-value,
.form-item-metatags-ru-og\:fax-number-value {
  display:none;
}


How do I add a link to the category in menu?

Have you tried a root link, one beginning with a slash? such as /taxonomy/term/34


Drupal EU Cookie Compliance module conflict with theme JQuery

You can use https://www.drupal.org/project/jqmulti to manage multiple versions of jQuery on your site


Get tid as integer from tid array returned by EntityFieldQuery

The standard(?) pattern to get ids from a query over a single entity type is to use array_keys().  Something like this:

function get_tids_from_custom_field($vocabulary, $field, $value) {
  $vocab_machine_name = taxonomy_vocabulary_machine_name_load($vocabulary);
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', $vocabulary)
    ->propertyCondition('vid', $vocab_machine_name->vid)
    ->fieldCondition($field, 'value', $value, '=');

  $results = $query->execute();

  return !empty($results['taxonomy_term']) ? array_keys($results['taxonomy_term']) : array();
}

The results array is keyed by the entity ID.


Different prices in Shopping cart form and Shopping cart summary views in Commerce price table

In the shopping cart summary view, are you using the
(Line items referenced by commerce_line_items) Commerce Line item: Unit price (Price) field  or (Products referenced by commerce_product) Commerce Product: Price (Price) field to output the unit price?

You should be using Commerce Line item: Unit price, this one is overridden by the Override price with price table rule


If you use the Date module you can create one field and configure it to use a start and end date. Then the module will validate the end date is greater than start date automatically for you.


Dedicated image style for media gallery teaser

You can create your own image style at admin/config/media/image-styles by click "Add style" link.

Use below code in your template file to fetch particular image style.

$my_style = image_style_url('your-img-style', 'image/uri');
<img src=' . $my_style . '/>

More details about image style.


Verification code when adding new telephone number

You can follow verification message method. When a user add/updates a phone number, you can send a unique random number which he must enter to verify his phone number.

Create a table that will contain three columns phone-number, unix time stamp and the verfication-code. When a user adds a phone number, create and store the random number. When the user inputs the verfication-code(random number), look it up in the database and then authenticate the user. Once he is authenticated, you can remove the entry from the database.

If you mention that verification code is valid only for 5 mins, then you can run a cron job to clear the database entries which are older than 5 mins.


Background of CKEditor is black for authenticated user

Do you have Firebug installed (extension for Firefox) ?
With Firebug you can inspect element and see what css definition makes it black.
Then, in your theme css file you can override that settings by writting your own definition to make it white. like

.ckebackground {
background-color:#ffffff;
}

where ckebackground is "problematic" class that makes it black.


How we can get the value entered in search API autocomplete field in jQuery?

This works for me:

var search_key = $('.path-frontpage .ui-autocomplete-input').val();


Is it possible to use features or some other technique to compare two sites?

If you are using Drupal 8, yes you can. But if you are using Drupal 7 I doubt you can yet do it. There is a backport of Configuration Manager to Drupal 7, which might make it possible.

The reason I said you can't do it in Drupal 7 is that the settings are saved in database and it is very difficult to make a comparison of the databases for settings. So if you have already made the changes and don't have a log, I would suggest exporting individual features using Features Suit of Modules.

You can checkout my presentation http://www.slideshare.net/gokulnk/features-15841090 for related Features modules which will make your work easier.

As a suggestion next time you want to keep a journal of your configuration changes please use Journal Module which should serve you well to keep track and document your changes.


Can a Calendar, based on two different content types, output different html based on content type

You could use the Views PHP module.

Then add the content type to the view. You can exclude both content type and title from the the view only display the title through the Global PHP field. With in that you can place a condition to display the complete link if it is of Type A and only the Title if it is of Type B. You could also add the path to the node as a views fields if you prefer so that it can be used in the as href for the link in php field.


How can I debug an AJAX error in VBO? (PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri'

Duplicate entry '' for key 'uri' actually says a little more than AlexK realizes, it says both that there's a file without a uri, hence the '', and that you have more than one of these, hence the Duplicate entry.

I'm guessing there's a filefield on your users, and some of these have lost part of their data for reasons I don't understand. (The same thing happened to me once during a faulty export-from-one-site-and-import-to-another).

Why the process can be "forced" by repetition I don't understand, but close inspection of the user entity and any fields that could have a 'uri' key, both through devel and the raw data in the DB, should reveal what the source of the problem is.


HTML stored in text field and not rendered in view

I've never used this, but you could try the Simple Field Formatter


Drupal in sub directory, still not clear

Apache can handle this. You can leave the Drupal code where it is.

Have a look at the Apache documentation for Mapping URLs to Filesystem Locations. In particular, the differences between DocumentRoot and Alias.

In the absence of any other information, Apache looks for files/scripts in the document root. For a Drupal site located at https://www.myorganization.it/, it's enough to point DocumentRoot at the web directory. Apache will find index.php there.

But myproject isn't a directory in the filesystem. So you need to explicitly tell Apache about it, that any URL starting /myproject refers to the web directory. You can do that with the Alias directive:

Alias "/myproject" "/var/www/MY_ORGANIZATION/MY_PROJECT/current/web"

You'll also want to point DocumentRoot somewhere else to stop Drupal being visible at the root too (an empty directory will do).


Put off loading my theme banners to speed up Drupal

I think you're looking for a technique called "lazy-loading" to implement on your pages. Lazy loading means that the images are only loaded upon viewing them.

You can use the Lazyloader module as a start to implement it, however how it will exactly work for your site is completely dependent on your Drupal theme and module(s) configuration. One useful example (and starting point) is this blogpost, which explains how to implement the layloader module in combination with a slideshow.


You have two returns (the second will never be hit). You have declared your array twice. It should be this:

function human_theme($existing, $type, $theme, $path){
  return array(
    'human' => array(
      'template' => 'human',
      'path' => drupal_get_path('module', 'human').'/tpl',
      'type' => 'theme',
      'variables' => array(),
    ),
  );
}


How to modify the add node forms using hook_form_alter

See below code which works.. Form element is title instead of edit-title.. print $form array to investigate form elements...

function MYTHEME_form_alter(&$form, &$form_state, $form_id){
switch ($form_id){
    case "q_a_node_form":
        $form['title']['#size'] = 10;
        break;
    }
}

If you have installed devel module you can see elements using below code

dpm($form);


How to apply a patch for a Drupal module?

This patch also exists at this #1063434 - the original issue for the test you reference above. One easy way to apply this patch would be to use the Drush Issue Queue commands.

Install with:

drush dl drush_iq

Then use it like this:

cd /path/to/drupal/root
drush am 1063434-#40

Presto!  Patch applied! Then drush-iq will work even better if you check out the module from git (i.e. drush dl field_collection --package-handler=git_drupalorg).

If you don't want to use drush-iq, try:

cd /path/to/drupal/root/sites/all/modules/field_collection
wget http://drupal.org/files/field_collection-feeds_integration-1063434-40.patch
patch -Np1 < field_collection-feeds_integration-1063434-40.patch


Setting current node url as default value for "Link" field

You need to use module field default token to work global as well local token in field value. You can use your previous token i.e. [current-page:url:absolute].


In case of multiple values, the return value is an array of all selected values. Therefore, $selected_index is now an array and not a string.


some cck fields of content type not displayed (corresponding elements also not showing in devtool)

You say you enabled all modules under CCK which means you probably have Content Permissions enabled.

Content Permissions module gives you per-cck-field view/edit permissions (which are all off by default!). Check that you have the correct permissions set for your fields or disable the module if you don't need that granular control.


HTML escapes appearing in node titles on bespoke content type — substitutions?

Whilst Jon's suggestion of htmlspecialchars_decode got me part of the way there, it turns out that the sample code from Custom HTML in Drupal Node Titles was less helpful.

Whereas that blog post suggested I do something like:

function modulename_preprocess_page(&$vars, $hook) {
    $node = &$vars['node'];
    if($node->type == 'my_content_type') {
            $vars['title'] = htmlspecialchars_decode($vars['title']);
            $vars['head_title'] = $vars['title'];
    }
}

I actually needed to do this:

function modulename_preprocess_page(&$vars, $hook) {
    $node = &$vars['node'];

    if ($node->type == 'my_content_type') {
        drupal_set_title(htmlspecialchars_decode(drupal_get_title()), PASS_THROUGH);
    }
}

Problem solved!


Why page-view counters not working (displayed)?

I suppose the cause can vary.  However, it seems multilingual sites may have additional factors that contribute to make this counter-related stuffs go wrong.  Here are a couple of example cases for multilingual sites.

I assume you are using the path-prefix based language negotiation as the high(est) priority.
In your case (A), is the English the default language and no path-prefix is defined for English?  In your case (B), are the path-prefixes defined for all the enabled languages, including the default language?  In those cases, it is suspicious some module(s) that use i18n are causing a trouble.

First, check the database table node_counter.  If a node has a non-zero totalcount, and if you don't see the page-view counter when you view the node, then it is likely to be down to either the permission or your theme, which may not show the counter in the first place.

If the totalcount column has zero count, despite you (preferably as a non-authenticated user) have viewed the node (and have flushed all caches), then the statistics module is not working, either due to its own failure or other module(s) fail to access the statistics module.

Have a look at "Recent log messages" /admin/reports/dblog.  If you see (probably plenty of) "page not found" for modules/statistics/statistics.php, then the latter is the case, or at least is contributing.

In that case,

Confirm modules/statistics/statistics.php does exist, and the file permission is set to be readable to any one, as well as all the parent directory permissions are set to be readable and executable to any one.
In the table of "Recent log messages" /admin/reports/dblog, click the links (for TYPE: page not found) modules/statistics/statistics.php in the Message column.  What do you see?  Does the LOCATION include the language prefix (like /fr/)?
If that is the case, your module(s) try to access the non-existing page like fr/modules/statistics/statistics.php instead of the correct path without the language prefix.  Best figure out which module is causing the trouble and fix the module.  If that is not practical, alternatively you can control the path at the server level: read the answer to Why so many “page not found” for statistics.php?.


The issue was a standard PHP issue in a function that was being called during the batch operation.  In this case, the error does not matter, what matters is that I could not see anywhere that the error was happening.

Running migrations via the Migrate UI will not show errors, in some cases, anywhere.  To better troubleshoot it is recommended that migrations are run via Drush.  Running my migration through Drush I was able to see where the import was failing and why.


Whether you create a custom field then modify it later, or create it completely in code, you need to use hook_form_alter in your custom module and add/edit your field that way and add the ajax call inside this function.

If you create a custom field in config, then there's now a config dependency you will need to somehow move from your dev environment to production (either thru Features or Configuration modules). On the other hand, if you add all through your custom module you won't need to worry about config changes, so IMO that is a better way.


How to remove edit tab after create commerce order

You should edit the permissions for the user role in question. Doing so will mean they will not have access to edit orders, and only create them if you so choose to.

It might be a little easier to use the secure permissions module to manage the permissions in code.


Programmatically set the format for each value of a multi-value text field

Please, do not start with capital letter when naming variables, every time you do that a puppy dies.

As 'field_article_links' can have more than one value (probably is a unlimited field), you should treat its value as an array and not as single entity, where each element has its value and format.

To do that, you have to build an array with the field data, then put this array into the field.

The following code is working as you expect:

$links = array (1, 2, 3, 4, 5);
$field_data = [];
foreach ($links as $link) {
    $element = [];
    $element['value'] = $link;
    if($link === 3) {
        $element['format'] = 'full_html';
    } else {
        $element['format'] = 'dasdas';
    }
    $field_data[] = $element;
}
$node->field_article_links = $field_data;
$node->save();


Add a "Relationship" to your view:

And then select "Entity Reference" in the "Filters" select list. You can choose whether is a content entity that is referenced, or referencing.


Rebuilding or regenerating the teaser after changing the trim length in Drupal 7?

If you are using the Views module to display your teasers, and you are using fields in the View, then you need to set the trim length for each field in the View itself.
Are you using custom formatters? These might be buggy and/org disregard the trim length.
When you edit the node(s), check that the summary field is blank. (I quote from the node edit page: "Leave blank to use trimmed value of full text as the summary.")
For further troubleshooting, create a new node with a lot of dummy text. Does it get trimmed to 300 or 600 characters?

If the new node gets trimmed to the new value, but old nodes get trimmed to the old value, then there is a problem with your cache or with the old nodes.
If the new node also gets trimmed to the old value, then there is a problem with your fields or views.


Drupal showing blank page after migrating to a local server

Seems like you are using PHP shorthand. Can you change it to a proper  and see if that helps? Please see if the path is correct since drupal is using relative path (base_url, base_path). Also please update the $base_url in the settings.php if you have.


You can try this module:

Custom filter

  This module allows you to create content filter using regular
  expressions. Instead of creating a new module for each filter you
  need, now you can easily create and organize your own filters. Your
  filter will appear in the input format configuration page.

Pattern: /([^\"]*)\"([^\"]*)\"([^\"]*)/i

PHP Code: do not tick

Replacement Pattern: $1«$2»$3

REMEMBER to flush the cache!

ALSO note that this pattern could wreak havoc with tag attributes. So you will have to expand it to exclude quotes surrounding attributes. But that is a question for stackexchange.com.


Create a view to show comments on a user ONLY from that user

You should indeed use a contextual filter, selecting "When the filter value is NOT available", then "provide default value", and choose "user ID from loggued user".

That should work.


How to resolve error 'Unresolved dependency System ...' encoutered when trying to upgrade Drupal core?

The reason for your error is because of the last line in the info file of the Relation module, i.e.:

  dependencies[] = system (>=7.33)

In regular English it is something like "This version of the Relation module requires Drupal core to be at a level which is at least 7.33".

To resolve it perform these steps:

Disable of the Relation module.
Retry your core upgrade again (that error should not show up anymore, as per step "1.").
Re-enable the Relation module again.

I'd be interested to hear what result you get in that scenario ...

Note: since your site is pre 7.32, you may want to also work on things such as what is in suggested in the answers to Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?


Drupal 7 Webform settings: how to change the default text in button "next page"?

You can use hook_form_alter to alter things in forms like button texts. This can in drupal 7 be done in both the theme and a module, but in Drupal 6 it can only be done in a module.


Should I create fielded content types (with 1000+ tables) OR create custom entities with properties instead of fields (way less tables)?

It depends on your requirement. For example, if you want nodes to be revisioned then go for content types. If you do not want them to revisioned and just using them for storing content then I think entity would be a better option.

Update: 19th June 2016 Thanks to @jon-freed

  When it comes to performance-sensitive projects, nodes should really
  only be used for content, and we should separate as much as possible
  from nodes. Why? Nodes are revisioned, they fire a lot of hooks, and
  they have functionality that we likely won't need. Also if we know
  exactly what fields we should have in our entities, we can create our
  own custom entities to avoid all those joins of Field API tables.

As far as the choice between ECK and entity api module, it also depends on your requirement. Entity api module provides more control over an entity, for example if you want to create an entity controller for the entity then you should use entity api module. If you just want to create an entity and define some properties then go for ECK. ECK also allows you to created bundles for entities.

Also, you can easily create views for the entities, this site provides great example to work with entities.

Reference: Drupal 7 Entities: What are they, and what are they good for?

Update: (19th June 2016)

It is true that using fields will increase the number of tables, which means more JOINS during database queries. If the purpose is to store data only then you should go for properties. If you want to take advantage of Drupal fields (display the data in cool ways), then you should go for fields, but in this case you have to think about the performance.

We can add fields to nodes and custom entities. Therefore, using nodes will not affect performance. You can always alter properties of an entity using hook_entity_property_info_alter(&$info)


How to bulk delete empty taxonomy terms?

A quick solution:

Go to your folder theme and edit the node.tpl.php and put this code at the top of the file:

<?php

$query = "
SELECT taxonomy_term_data.tid AS tid
FROM
{taxonomy_term_data} taxonomy_term_data
LEFT JOIN {taxonomy_index} taxonomy_index ON taxonomy_term_data.tid = taxonomy_index.tid
LEFT JOIN {node} node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
GROUP BY tid
HAVING COUNT(DISTINCT node_taxonomy_index.nid) = '0'
";

$tids = db_query($query)->fetchCol();

foreach ($tids as $tid) {
  taxonomy_term_delete($tid);
}
dpm($tids);
?>

Then go to visit one of your nodes and the code will be triggered.

Take into account that if you don't eliminate the code from the node.tlp.php then every time that you access a node the code will be triggered.

EDIT: I (quickly) created a little module for you. Is not the best solution but I tested it and it works.

file: delete_unused_taxonomy_terms.info

name = Delete Unused Taxonomy Terms
description = Delete all unused taxonomy terms
core = 7.x
package = Administration

configure = admin/structure/delete_unused_taxonomy_terms

files[] = delete_unused_taxonomy_terms.module
files[] = delete_unused_taxonomy_terms.admin.inc

file: delete_unused_taxonomy_terms.module

<?php

/**
 * @file delete_unused_taxonomy_terms.module
 */

/**
* Implements hook_menu().
*/
function delete_unused_taxonomy_terms_menu() {
  $items['admin/structure/delete_unused_taxonomy_terms'] = array(
  'title' => 'Delete Unused Taxonomy Terms',
  'description' => 'Delete Unused Taxonomy Terms',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('delete_unused_taxonomy_terms_admin_settings'),
  'access callback' => 'user_access',
  'access arguments' => array('administer taxonomy'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'delete_unused_taxonomy_terms.admin.inc',
  );
  return $items;
}

File: delete_unused_taxonomy_terms.admin.inc

<?php
/**
* @file
* Calls results to administration's pages.
*/

/**
* Form constructor for module configuration.
*
*/
function delete_unused_taxonomy_terms_admin_settings($form_state) {
  $form['#submit'][] = 'custom_form_submit';
  return system_settings_form($form);
}

/**
 * Submit handler
 */
function custom_form_submit($form, &$form_state) {
  $query = "
  SELECT taxonomy_term_data.tid AS tid
  FROM
  {taxonomy_term_data} taxonomy_term_data
  LEFT JOIN {taxonomy_index} taxonomy_index ON taxonomy_term_data.tid = taxonomy_index.tid
  LEFT JOIN {node} node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
  LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
  GROUP BY tid
  HAVING COUNT(DISTINCT node_taxonomy_index.nid) = '0'";

  $tids = db_query($query)->fetchCol();

  foreach ($tids as $tid) {
    taxonomy_term_delete($tid);
  }
}

In your module folder make a folder named delete_unused_taxonomy_terms put the 3 files inside and install the module.

Then go to admin/structure/delete_unused_taxonomy_terms and click the button.

Reference:

How to delete true orphaned taxonomy terms
Create a Views that displays all unused taxonomy terms


Alter Color module fieldset within theme settings form

Definitly system-theme-settings is a core form where color module adding its fields using hook_form_alter in the same manner you are doing.

The point at which your hook_form_alter is invoked seems to be earlier then the color module's.

Check out hook_module_implements_alter to alter the registry of modules implementing a hook.


Will the Search API increase performance of searches in the Views Exposed filter?

It probably will, depending on the Search API backend you are using. Something generally true is if you are using any other backend than database, the querying for the search will be dispatched to this additional backend instead of the database, which is Drupal primary storage, and will avoid your database a lot of suffering.

It will also makes things easier to scale, since a lot of search engines can be replicated more easily than database. Even without this statement, you can at least put the SQL server and the search engine on different servers, which means they will eventually be faster since they won't have to share one box resources.

It doesn't mean it will be faster in all cases, it depends on your environment and configuration.

Regarding the queries themselves, if you are doing a lot of fulltext searches, using a backend such as Apache SolR (or any other search engine, Xapian, etc...) it will surely be a lot faster since they have been made for this. If you are doing facet oriented search, it will also help a lot.

But, in the end, if your views filter only are on exact strings, integers and such, it may not be faster in the end, it will just be more scalable.

You have to remember that creating an index for your data will also imply that you install a whole lot of modules in your Drupal site, you'll have to benchmark a bit. But if the primary business matter of your site is searching, I'd say give it a try.

I don't know if my answer sounds good.


How do I set up a new Drupal instance with all the modules from a previous one?

This is where the concept of drupal distributions comes in.

Yes you will need drush, a make file with the modules you need and a profile that installs these modules upon site-install.


Decryption failed because the HMAC could not be validated - error on Migration d2d dashboard page

I am not sure this will help you, but I ran into this error while using webforms:

  Decryption failed because the HMAC could not be validated.

My issue was I tried to encrypt a webform field after there was already unencrypted data saved for that field in the database. So when I tried to view the results of my webform, I would get the above error because it was trying to decrypt data that was not encrypted.

Perhaps this is what is happening when you try to migrate?

My solution was to manually clear the data from the database. Once I did that, I was able to get to the webform results page in the drupal admin and clear the data from there to be sure all evidence of it was gone. Because I am in development this was an ok solution.

I am guessing clearing the data will not work for you, but perhaps this will help point you in the right direction.


Setting managed file default value from ajax request

So after digging through Drupal core code I arrived at this solution:

In my ajax callback I load the actual file, set some managed file settings in the managed_file array, and then physically call the file_managed_file_process() function to setup the managed file display field array elements.

function load_image_callback($form,&$form_state) {
    // Load node from the selected value
    $node = node_load($form_state['values']['slide_nid'];
    $file = file_load($node->field_main_image[$node->language][0]['fid']);

    // Set the managed_file default value to the nodes main image file
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#value'] = array('fid' => $file->fid);
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#file'] = $file;

    // Process the managed file field with the set element
    $form_state['complete form']['slide']['slide_image']['slide_fid'] = file_managed_file_process($form_state['complete form']['slide']['slide_image']['slide_fid'], $form_state, $form);

    // Return the updated slide image wrapper to replace the existing one
    return $form_state['complete form']['slide']['slide_image'];
}


Using an F5 server as reverse proxy cache (instead of Varnish)

I have used F5 as a load balancer with Drupal without issue. We were using varnish between Drupal and the F5 as a reverse proxy.

Pressflow and varnish have been tested well together, F5 is quite a high end bit of kit so I don't know if anyone else has tried it. From what I remember F5 is very flexible so you should be able to get it to work in the same way as varnish (same headers being sent etc).


How to make taxonomy terms link to an external site?

Solving this issue for me required three modules:

Link module: Creates a link field for external links. Module page
Lexicon: A module that look for keywords and allow you to set up a lexicon that automatically link keywords to a page explaining them. Module page.
Field Redirection: A module that allow you to create pages that automatically redirect the user to a different page. Module page.

Install the modules and activate them.
Go to Manage fields of the vocabulary you wish to use for external links (structure-->taxonomy-->[your vocabulary]--> Manage fields). Add a link field to the vocabulary and set it's format to "redirect" (this is described in the documentation of the Field Redirection module).
Go to Manage display and hide all other fields (also according to FR module instructions).
Now it is time to set up the Vocabulary. Go to configuration-->system-->lexicon settings. Under the General tab, check "Link terms to the taxonomy term page" and uncheck the options that will make several terms appear on the same page (field redirection will otherwise always redirect to the link associated with the first term on the page).
Link targets are edited for each term in the taxonomy and you add the URL in the "Link" field of each term.

Lexicon is the module you interact with to make the links appear as you want them and any issues will probably be caused by improper setup of the Lexicon. Links/Redirect Field are a small add on that transport users to external websites instead of the lexicon page created by the Lexicon module.


How to configure relationships created by the User relationships module

User Relationships supports bi-directional relationships unless you have checked the "This is a one-way relationship" checkbox.

However, there is a bug in the current 7.x-1.0-alpha2 version, make sure you use 7.x-1.x-dev instead.

If the Relations module works for you, fine. But the main thing that UR provides is various user interfaces to request relationships, see/administer them in listings, approve them, see your relationships with other users when visiting their profile and tons of additional modules like integration with Privatemsg.

In fact, we plan on making UR just a fancy UI on top of the Relations project, but that's quite a way to go.


Hiding a Tab when the View from Field View is Empty

Try with this

$node = node_load($argument);
if ((isset($node->field_fotos) ||
     isset($node->field_summary)) &&
     (is_array($node->field_fotos) &&
     count($node->field_fotos) > 0) ||
     (is_array($node->field_summary) &&
     count($node->field_summary) > 0)) {
  return TRUE;
}
else {
  return FALSE;
}


Can node refferences be automatically resolved in a view?

Views relationships are used to bring in data from referenced nodes. From your view's administrative page, expand the Advanced section and add a relationship. Select the appropriate node/entity reference field that bridges your nodes. Now you can add fields to your view and configure them to use your relationship, which will pull in any data from the referenced entities/nodes. At this point your view should contain data you want, making it available to the web service.


Translation server suggests translation with old date

i didn't find answer for none of my questions but at least find a solution:

after testing clear cache without luck i did these steps:

user interface translation->setting->change translation source to 'local file only'->check update translation manually

and old translation suggestion was disappeared.

now with changing translation source to Drupal 'translation server and local files' i get related translation suggestion for my Drupal version.


How to put view results in an entity reference field?

The closest match to the link you shared is the Entity Browser module.

Goal of this module is to provide a generic entity browser/picker/selector. It can be used in any context where one needs to select few entities and do something with them.

The module allows you to build your own widgets (similar to the Media Library) to use with entity reference fields or in WYSIWYGs, via integration with the Entity Embed module. You can create widgets with multiple options, an option to create new content (with the entity_form submodule), and select existing content via view displays.


How to confirm that drush-based cron is being called from crontab?

It sounds like you've answered your own question. Viewing the admin DB log reports or running something like fin drush wd-show --type=cron should show cron execution entries. If you're not seeing those logs, it most likely means the crontab config isn't working.

You should check drush --root="/var/www/docroot" core-cron works correctly when manually executed in the container where crontab is configured (e.g. perhaps the crontab user doesn't have drush available in its path or drush can't find the DB config) & the /var/log/ dir (it will depend on the Linux distro the Docksal image is based on) for cron logs to confirm that its firing.


How can I create a patch for a contrib module or core which is not in version control?

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

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

Then, you make the change and run the following:

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

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


In your list $op, add:

$block[0]['cache'] = BLOCK_NO_CACHE;

However, note that Drupal 6 will not automatically update your block information, you will have to do that yourself, see privatemsg_update_6002() for an example.


Using Drupal's database for Apache authentication

I did in the past use the export_user_db module, but it is similarly lacking in D7 support.

I am now using modauthmysql quite successfully with D6; I also have an auxiliary module that I can publish to do single-sign-on between Drupal and Apache-authenticated sections of the website.

You are correct that the lack of a Drupal-7-compatible password hash is a limitation, but I don't think this would be too hard to add. Contact me on d.o if you would like to collaborate.

http://drupal.org/user/438598

If you really only need to serve static content, serving it from Drupal per the other answer is easier and better.


When adding a node, the site images do not show

It seems that the root of your Drupal site is http://localhost/bedsastro_new/ .

To reference an image with filename pic.jpg (using an img tag) which is located in the site's subfolder named assets/site-images, you should specify /assets/site-images/pic.jpg as the value of the src attribute within the img tag.

With that, Drupal will try to find that image at http://localhost/bedsastro_new/assets/site-images/pic.jpg, which is where your image is actually located, so that should work.


How do I fix my Commerce Feeds import process post updating my modules and core?

I have the same problem. I think that is because I am using a old version Drupal Commerce and it is incompatible the newer version of Feeds module that i am using.

but I manage to get it work by paste in this function:

function commerce_product_validate_sku($sku) {
  // Do not allow commas in a SKU.
  if (strpos($sku, ',')) {
    return FALSE;
  }

  return TRUE;
}

into the file "commerce_prouduct.module" located in:

{mydrupal-installation}\profiles\commerce_kickstart\modules\commerce\modules\product

I found that function in:

http://drupalcontrib.org/api/drupal/contributions!commerce!modules!product!commerce_product.module/7

Hope that help!

Apollo Tang


How to detect if form-building function is called for the first time?

You can add our own value to $form_state in a hook_form_alter().  If it doesn't already exist (eg., !isset($form_state['my_var'])), then you know it is the first build.


Restrict admin from disabling userprotect

Create another custom role, and add all of the permissions they will need, to that role. Leaving out the ability to administer user roles, and such.

It probably sounds tedious, considering you'll be adding back almost all of the same permissions that admin has. But, that "almost" is important and makes all the world of a difference with regard to security of your website.


Using rules how to redirect to a url + element id

You can use token from Replacement Patterns list. Token will be something like [node:field_node_ref].


Does memcache allow anonymous users to be served content when the database server is down?

As stated in the comments, memcache is probably not going to help you here.

Since you are using CF as a front end, you might be able to get by by creating a page rule to cache everything.  See this doc.  This assumes that your site is pretty static (e.g. not an e-commerce or has user logins.

I'd suggest creating a script to load all your pages prior to shutting down the sql server.  I.e., clear the CF cache then load all the pages into cache using the script.  A bunch of CURL statements should work.  Make sure to load ALL the content (e.g. images, css, scripts).

That said, I really would not depend on this.  Personally, I'd set up a temporary DB server, copy the DB to it, then change the settings.php to point to it when the main DB is being updated.  Then swap it back after the update.


"You don't have permission to access / on this server"

I can't imagine Drupal 8 is supposed to have this done on every installation.

You're right, it only needs to be done in .htaccess where altering the web server config isn't an option (think shared hosting).

In a local dev environment you don't have that problem, so just update the vhost with something like

<Directory "/var/www/site/public_html">
  Options FollowSymLinks
  AllowOverride All
  Require all granted
</Directory>

and re-start/load Apache for it to take effect.


I suggest you to use entityforms instead of webforms.

And then, you should enable entity tokens and Field default token modules.

Now you can add a text field to your entityform, which contains URL of the current page as the default value.

After that, you may hide that field by CSS.


Postfix server and Simplenews module interaction

You could try to add a [Reply-To:] header to your mails. Maybe your postfix will send the non-delivery notifications to this address.


Alter Add to Cart form POST data provided by #action

You can add other fields to your form as hiden, in the hook_form_alter for example add SKU field as hidden.

  $form['sky'] = [
    '#type'  => 'hidden',
    '#value' => YOUR_VALUE,
  ];

Hidden fields will submitted like others.


How to make a select form element with textfields for the array id and key?

Do you know of Drupal's core field type "List" or what it's called and its "Allowed Values" field? Where admins can enter key|value pairs divided by a pipe character?

It's exactly what you seem to describe.

I'd start by mimicking exactly that. But all in one form. Maybe multi-step. Maybe peppered with some Ajax...


How can I add an external (CDN) CSS style sheet to a theme?

My understanding was that for a sub theme you defined the CSS as such:

global-styling:
  css:
    theme:
      css/style.css: {}

...as discussed here: https://www.drupal.org/node/2165673


hook_form_alter #attributes and #disabled

Checkboxes are converted to their individual form elements in form_process_checkboxes (), so you'll need a process function:

// In the form alter...
$form['taxonomy_forums']['und']['#process'][] = 'MYMODULE_process_checkboxes';

function MYMODULE_process_checkboxes($element) {
  $element[334]['#attributes']['class'][] = 'test-class';
  $element[334]['#disabled'] = TRUE;
  return $element;
}


Render chart with data from Views PHP custom field

A work around for issue 1. & 2. Add Bar number as a field to each study node. Then add field to view, and aggregate.

How exactly is the Bar Number being calculated? You could use Rules to calculate this value when node is saved and save the calc number to your Bar number field. If there is no calculation, then ignore this part.

Use field permissions to not allow certain roles to change the value of this field, if needed.

Add a new field called Bar Number (machine name: field_bar_number) to your study content type.

You can create a custom module.

mymodule.info

name = My Module
description = Makes calculation for Bar Number field in Study content type.
package = Custom
version = 7.x-1.0
core = 7.x

mymodule.module

/**
 * Implements of hook_node_presave
 */
function MYMODULE_node_presave($node) {
  if ($node->type =='study') {
    // calculates bar number
    $node->field_bar_number = $node->some_field - $node->other_field;
  }
}

Use Views Bulk Operations and set title = title, and save again all your 500 nodes. As your custom module makes the calculation and sets the bar number before the node is saved. VBO Tutorial.


How to solve "Query failed" error in drush sql-sync output?

The reason you get a 'file not found' error when you run the import by hand is that Drush automatically deletes its temporary files when the command completes. So, the error you are seeing there is different than the 'Query failed' error you are getting from Drush.  Also, note that the --defaults-extra-file contains the credentials for your mysql connection, whereas the file shown at the end of the line is the actual sql dump.

If you'd like Drush to keep the sql file around, you can specify your own location for it; in this instance, Drush will not delete the file when it exits.  Use the option --target-dump=/path/to/mydump.sql.  It is unclear to me from your pasted output above whether or not your %dump option is being respected (since the path used is different than the one shown in your site alias). If %dump is not working, you could try moving this to your target-command-specific options, although if you do this, the key should be simply dump, not %dump. If your sql dump file is not being deleted, then disregard this advice.

If you want to try to re-import your local dump file, you could do this:

$(drush @hpc.local sql-connect) < /tmp/hpc-drupal-dev_20160302_175129.sql

If you do this, you should get the same 'Query failed' message. $(drush @hpc.local sql-connect -d) might give you more information.

The cause of the 'Query failed' message could be a number of things, but it's most likely a mismatch in the mysql version on your host vs. your local system, or (less likely) an encoding mismatch (e.g. if your dump is in utf-8, and that encoding is not available on your local system).


Drupal 7 on new Linode stack, POST/GETS 404ing but pages still loading?

The reason for this is most likely that clean url's are disabled. Make sure that mod_rewrite is enabled in Apache.

Fetching pages still works, because the 404 triggers Drupal, which is then able to return the correct page. That does, as you found out, not work for form submits, because the submitted data is lost when doing the redirect.


Tell taxonomy links to use route in custom module

In my case, I'm also using a RouteSubscriber to change the default controller responsible for handling taxonomy term entities. I also wanted to use a custom template only for a specific taxonomy (called my_taxonomy in the example below).
Here is the code for the RouteSubscriber:
<?php

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RoutingEvents;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.taxonomy_term.canonical')) {
            $route->setDefaults([
                '_controller' => '\Drupal\my_module\Controller\DefaultController::listAll',
            ]);
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -200];
        return $events;
    }

}

And here is the code for the controller. Note that a custom render array can be returned only for terms of the specific taxonomy my_taxonomy. All other terms fall back to the default controller used by the views module in the original route:
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\Routing\ViewPageController;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends ControllerBase {

    public function listAll(Request $request) {
        $render = [];

        $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
        $term = Term::load($tid);
        $bundle = $term->bundle();
        if ($bundle == 'my_taxonomy') {
            // render array for your custom template
        } else {
            // falls back to the default ViewPageController to handle all other taxonomies
            $viewPageController = new ViewPageController();
            $render = $viewPageController->handle('taxonomy_term', 'page_1', \Drupal::routeMatch());
        }

        // Return render array
        return $render;
    }

}


Views contextual filter pages and duplicate content?

For removing them from Google search, you could use the Metatag module https://www.drupal.org/project/metatag to mark nodes of that Content Type as noindex.

For internal Drupal search I suggest adding the Custom Search module https://www.drupal.org/project/custom_search You can use that to block searching of that Content Type.


This will be little bit lengthy process but can be done. This you can do by Views module which is in core in Drupal 8, BUT before that you have to do some other stuff with the user account. The entire process I am listing out in steps.

Since your question is not complete clear, I am providing the method for Author Info only, if you clarify I will add the second part.

Author Info Block

Adding - Bio field & Social media profile field
Creating Views.
Add created block to appropriate place.
Block visibility setting

1. Adding - Bio field & Social media profile field

Now, the user profile setting do not provide the Bio field by default hence we need to create that one.

1.1 Go to Configuration>Account Setting>Manage field

1.2 Add new field name: Bio, field type: Long text(formatted, long)>save

1.3 Add new field Social Links: Install and enable the Social Profile Field. What this module does, this module provide the field which provide the provision for adding the social media links, The link will automatically converts to ICONS, that is the good part.

Again go to Configuration>Account Setting>Manage field and add new field Social link and for this choose field type: Social profile field. Note: The picture field is by default, which  provides by core.

The final screen shot will be looks as below,

Now, Under the user profile- Bio and Links will be added as new field so you can add this by going under Edit of any user profile.

Now, we add set to go for Views,

2. Creating Views: Author info

2.1 Go to Structure>Views.

2.2 Add new view: Author Info. Select Users in views setting. Select Create a block in Block setting. Set Unformatted list of Filed under  Block display settings. Select 1 under items per block. Click->Save and edit.

2.3 Views setting page:

2.3.1 Now add Relationship: Go under Advanced setting. under relationship click add and from the list select Content Author, give it a name Author node as shown in the following image of 2.3.4.

2.3.2 Now add contextual filter: Same as above step, click add to contextual filter. select ID. And select Provide default value. Under that select Content ID from Url. (as shown in following image)

2.3.3 Come under FIELDS and add following field: Picture(category: User), Bio(category: User), Links(category: User).

2.3.4 Remove anything which is under the FILTER CRITERIA. Save it. Your final views setting page will be looks like this,

3. Add the created block: Go to Structure>Block> and under first sidebar add this block.

4. Block visibility setting: Now, till this step, everything works fine, but these blocks are not visible to Anonymous user, And to set that, Go to Again go to views setting as shown in just above image, under BLOCK SETTING > Access click permission and select none option, and save. Now, this block will be visible to all users.

Output Image: I have reprocessed this above mentioned process in my Drupal 8 trial site and you can see in following image, with all Author info. on only page which has been authored by that author.


Rules data comparison: compare node field with a group

Ok, lets assume that your group name is called "Pokemon"

1) Under Conditions, click on Add Condition.

2) In the drop down, select TEXT COMPARISON

3) Click on the Blue Link that says (DATA SELECTORS)

4) Look for your field, if you named it "group", then look for node:field-group

then highlight it, copy and paste it under Data Selector*

7) Under Matching Text put Pokemon

8) click SAVE

Note: obviously, replace Pokemon with your actual group name.


How exactly does module_load_include() load a file into the calling script?

It sounds like you're getting confused on scope. There's no "file scope" in PHP. The include/require statements are pretty much the equivalent of dropping the code within the scope that it's called.

Per PHP's docs on the include statement:

  When a file is included, the code it contains inherits the variable
  scope of the line on which the include occurs. Any variables available
  at that line in the calling file will be available within the called
  file, from that point forward. However, all functions and classes
  defined in the included file have the global scope.

If definitions in the included file are global. For example:

global $base_url;
define('MYMODULE_CONST', 123);
function mymodule_function() { }

Then they are global until the script execution ends.

If definition is not global (e.g. $var1 = 'var1 value';) then it only remains within the scope of the include statement.


I've been down this route a few times (looking at using LDAP integration module) each time I ended up writing my own LDAP integration.  Everyone implements differently, I just take the pieces I like from the LDAP module out there (6 or 7) and use your own code to do it.  As a general rule, anytime the rubber hits the road with integrating Drupal with user authentication / authorization systems in an organization I brute force them together via a custom / forked module.  You'll always know your own auth system's specific needs, D.O. will not :)


How to add button to a form that calls custom JavaScript when clicked?

In this example, I've added a custom button action to a Drupal 8 Form. When the button is clicked, it prevents the form from being submitted and allows custom JavaScript to do some work.

Here are the 3 pieces:

The form button element, with an #attached library
Your custom module's library declaration
The library's .js file

And here is the example code:

in ExampleForm.php

$form['actions']['clear'] = [
  '#type' => 'button',
  '#value' => $this->t('Clear'),
  '#attributes' => [
    'onclick' => 'return false;'
  ],
  '#attached' => array(
    'library' => array(
      'example/foo',
    ),
  ),
];

example.libraries.yml

foo:
  js:
    js/foo.js: {}

js/foo.js

Drupal.behaviors.example_hello = {
  attach: function (context, settings) {

    // Attach a click listener to the clear button.
    var clearBtn = document.getElementById('edit-clear');
    clearBtn.addEventListener('click', function() {

        // Do something!
        console.log('Clear button clicked!');

    }, false);

  }
};

Don't forget to clear all your caches to ensure your new foo.js library is picked up by Drupal 8.


Solution 1: Without code

Configure a taxonomy vocabulary named Blog category to manage blog categories.
Configure Blog category aliases to /blog/[term:name].
For the Competitions term, override the URL alias to /competitions.
Configure a taxonomy term reference field (preferably single value) on the Article content type. Say, the field name is field_category.
Configure the Article path pattern as /[field_category:entity:url:path]/[node:title].

This is somewhat like what gapple has mentioned above.

Solution 2: With code

Configure a taxonomy vocabulary named Blog category to manage blog categories.
Configure a taxonomy term reference field (preferably single value) on the Article content type. Say, the field name is field_category.
Configure the Article path pattern as /blog/[field_category:entity:name]/[node:title]
Use hook_pathauto_pattern_alter() or hook_pathauto_alias_alter() to change the path pattern depending on the $context.

This is what I did for my problem. This way, you can choose whatever alias you want for your taxonomy term.


Drupal 7 hook_form_alter and submitting the form

There's a typo, change value to values

To get the user id use:

<?php
global $user;
print $user->uid;
?>


No one can login and access denied message

The problem was ip_geoloc module. It was messing up $_SESSION variable, a solution is given on the issue queue (for now!) and the module author agrees with it. It's highly probable that it is happening because of a mis-configuration by me. The user was successfully logged in but immediately their session was invalidated. Somehow disabling it was not enough and it's directory had to be moved out of Drupal root. I am 100% sure not any of it's functions or APIs are used anywhere else. Maybe some cache problem?
Lesson learned:
When having signing-in problem, try to check the $_SESSION variable on the server using devel and it's helper functions (e.g dpm, dsm, dd, ... or as a last resort var_export) and not with you google/firefox developers console.
This is the third time I'm facing this strange behavior and the first time I was able to fix. If you are having this problem, try to follow this checklist:
Ask yourself:

Does truncating the sessions table fix the problem?
Does forcing a change for user password fix the problem?
Have you added any particular configuration to your settings.php? e.g base_url, cookie_domain, ...
Does UID 0 exist in your database (i.e anonymous user)?
Is any redirection module installed? search404, redirect, global_redirect,...
Do you have a custom module enabled?
Is there any problems with your theme?
Do you have any path altering modules, e.g path_alias?
Do you have any module changing the log-in behavior? e.g logintoboggan
Have you enabled any caching module? e.g authcache, memcache, session_cache, boost, varnish, ...
Do you have any access control module enabled? e.g workbench, content_access, acl, og_access, ...
And finally, have you enabled any module which changes the user $_SESSION? e.g session_api, session_cache, ip_geoloc, ...

Places to look / Things to do

Look at drupals watchdog messages. If you can not log-in, use drush watchdog-show --tail to see what's happening.
If running apache and mod-php, look in apache's error log, usually at /var/log/apache/error_log for *nix systems.
If running php-fpm, see the php-fpm log, make sure there is no communication problem with php daemon, such as headers are not lost. if you see no error log try running your site with drush/php internal server. the command is drush rs or drush rs the.ip.goes.here:thePort
make a fullbackup, disable all modules with this command AFTER making a full backup (you can make a backup with drush ard or just database drush sql-dump > db.sql or use backup_migrate module)drush dis -y $(drush pml --nocore --status=enabled --pipe) -> this command only works in *nix systems I don't know the direct translation for windows.
Set your default theme to something... safe! such as seven or garland. If you can not log-in use this drush commands:drush en seven && drush vset theme_default seven;
Monitor $_SESSION variable with any debugging tool, see if it's content are correct, ok, healthy.
For all the processes and daemons involved in serving a request (nginx, php-fpm, apache, varnish...) make sure they all have write access to their tmp directory.

Good luck debugging!


How do I know whether drupal_write_record has done an insert or an update?

Turns out that in order to know if the operation was an UPDATE or an INSERT you need to know whether the record existed or not before committing the transaction. This is not what drupal_write_record() does. This function just checks it's arguments and issues an update or an insert accordingly. So there is really no way to tell if the function did an INSERT or an UPDATE.

The solution is using db_merge() query, it is a relatively new SQL ANSI standard that does exactly what I needed (and in the case of MySQL does it in an atomic transaction).

$return_value = db_merge('mytable')
            ->key(array('id' => $key))
            ->fields($fields)
            ->updateFields(array(
                'updatedon' => $now,
            ))
            ->execute();

The return value is an integer returning 1 for inserts and 2 for updates.


Figured it out ... The hoster I use (uberspace.de) has a timeout for script execution time. Some Simpletest tests do not respond for several minutes, which triggered the timeout.


Why is this if statement not working in twig?

The variable html_attributes is not available in a page template. To make it available copy this code from template_preprocess_html() to your page preprocess hook:
use Drupal\Core\Template\Attribute;

/**
 * Implements hook_preprocess_page().
 */
function mytheme_preprocess_page(&$variables) {

  $variables['html_attributes'] = new Attribute();
  $language_interface = \Drupal::languageManager()->getCurrentLanguage();
  $variables['html_attributes']['lang'] = $language_interface->getId();
  $variables['html_attributes']['dir'] = $language_interface->getDirection();

}


Template conditional based on a list field

My php isn't the best, but I think this should work...

You could try using a foreach loop, and using a condition similar to this:

<?php foreach ($node->field_the_checkbox_field['und'] as $thisfield) {
    if($thisfield['value'] == 'key_of_checkbox'):
   // do stuff
} ?>


Redirect after submitting custom entity form

Probably you need to override EntityFormInterface::save():

  Form submission handler for the 'save' action.

  Normally this method should be overridden to provide specific messages
  to the user and redirect the form after the entity has been saved.

submitForm() is the first submit handler called and should not be used to override submit actions.


How to redirect to a certain page after logout from any link

If i am correct you want the user to to redirect to a certain page say test-page-3 from any page or url after logout.
Enable the Trigger Module. In configuration go to Actions, -- there in Create an advanced action Select Redirect to URL and press Create. Then label it as you want it and in URL add the page URL you want the user to redirect.
Then go to Structures and Select Triggers,  here select USER Tab in Top Right corner.
Then in Trigger: After a user has logged out , Select the action the action u have created.

Hope that helps and tick if u find it useful.


Is it okay to store a $node object as a $_SESSION variable

I think you want the ctools object cache API here, this is what views uses to store edits to a view until they are saved and is what Drupal 8 uses for node preview. In D8 it's called user temp store.


8 - How do I check if a comment is from original poster?

Actually, before you write any code... D8 automatically adds a 'by-[entity-type]-author'(e.g. by-node-author) class to the <article> tag of each comment, if commenter and author are the same.
This is defined at line 73, in comment.html.twig file(at least this is the case in Bartik theme file), so please take advantage of it :)


How to pull the value of a taxonomy term into the html.tpl.php files

You should use the function template_preprocess_html in your template.php.

For example.

function yourtheme_preprocess_html(&$vars){
    // $tid - id of your taxonomy term
    $term = taxonomy_term_load($tid);
    $vars['head_title'] = $term->name;
}

Also, copy the html.tpl.php file to the directory in your theme, where all the template files are located. And clear cache.


print custom image field for taxonomy page (page--taxonomy.html.twig) template

Only entities from type node are loaded in the page template by default. If you want this for other entity types you have to add custom code to page preprocess:

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['term'] = $term;
  }
}

Then you can access the fields from the term in page--taxonomy.html.twig:

{{ file_url(term.field_image.entity.uri.value) }}


I need to bring a site to version control, and set up the continuous Integration environment

Ok, I'll give this a try :) I won't be able to fully answer your question, but maybe give you have few interesting hints. Note that my numbering is not in direct response to yours :)

As I already mentioned in the comment, no project is too small for version control. I personally recommend Git. Reasons are the plain awesome speed of it (wait time in git is measured in milliseconds, not seconds) and the huge amount of features. It can be a bit hard to pick up, because of weird names and arguments but the following documentation explains many of them really good: http://www.eecs.harvard.edu/~cduan/technical/git/. Another reason is that it is now used by drupal.org, so knowing git will help you when you want to contribute back (providing patches, testing patches, release modules, ...)

That said, if you'd like to use SVN for some reason (like integration with services you plan to use), then go for it. SVN works reasonable well too and is much better than no source control. (Unless you ask Linus Torvalds..). Also, there are often ways to migrate from one VCS to another if you change your mind. SVN -> Git works well, for example.

Third, approach this step by step. Don't try to do everything at once. Give you (and your developers) the time to learn the new tools.

Switching from Drupal 6 to Drupal 7 is not a trivial thing. Especially with a lot custom code. Note only are there tons of API changes and new concepts (like the entity/field system), there is also the point that many contributed modules aren't fully ready yet.

Deployment management is one of the weak points of Drupal, that also hasn't changed that much in Drupal 7. We are aware of the problem and people are working hard to resolve this for Drupal 8: http://groups.drupal.org/build-systems-change-management/cmi. Features etc. helps, but it's not a silver bullet. Not everything can be exported as a feature.

There are also a few Drupal-specifc options for deploying staging/production sites. Pantheon (still in beta) and Acquia Dev Cloud might be worth checking out.

Continuous integration, automated testing is important and really useful but also require time to set up, write the tests and so on. Time you might or might not have at this point. But especially automated tests is an area where it is easy to do incremental improvements. Once you have a environment set up to run them, you can write more and more tests as time permits.

So, here is my recommendation for the updated question in the comment:
Finish and release as is, but start using a VCS (version control system) for Drupal 6 now. Create a staging environment for your site. Look at what (contributed) modules you are using and check if a port to Drupal 7 is feasable at that point. Don't underestimate the time that will take. Also start to improve the testing/deployment process, starting with what you think will bring you the most benefits/cost.
You can also create more specific follow-up questions or look those which already exist. As you can see, even only giving a few hints to a question like this can get huge and take quite a bit of time.


Adding a page to a menu with query parameters in the URL

Ah yes, this has plagued me for years.  I cheat and use "Global Redirect Module" https://www.drupal.org/project/globalredirect


There are two thing to do for the date format:

First create a date format (admin/config/regional/date-time/formats/add): this where you define how the date will be display and a simple PHP string date format is all you need something like 'm/d/Y' will show the date as 08/20/2012.

Once the date format is added you can use it on any "Date Type" (admin/config/regional/date-time) or you can create your own date type and assign the date format to it.

To display different date formats depending on what view of node is you have multiple options:

Use panels, views, context or display suite and format the date to your date type or date format
Edit or create a template for your node type (node--CONTENT-TYPE.tpl.php if D7 or node-CONTENT-TYPE.tpl.php if D6) and use the format_date function to format it.

if ($teaser) {
format_date($node->created, 'custom', 'Y-m-d H:i O'));
} else {
format_date($node->created, 'custom', 'H:i O Y-m-d'));
}

OR using your date type:

if ($teaser) {
format_date($node->created, 'DATE-TYPE'));
} else {
format_date($node->created, 'DATE-TYPE'));
}


How to display a block for pages that don't show nodes?

I think you may want to take a look at the context module. That allows you to define multiple conditions for displaying blocks.

However, you should also consider making your module only return content on pages that it makes sense to appear on. So the user doesn't have to worry about complex configuration.


Redirect user to prefered language after login

You can use the hook_user_login which is called after a user successfully log in to the website. This hook passes the user object as an argument that you can use to retrieve the user language.

For the languages, you can make use of the language_list, which returns an array with the defined languages in your Drupal website. And for the redirect, drupal_goto does the job.

Here is some sample code that could help you further:

function YOURMODULE_user_login(&$edit, $account)
{
    // retrieve user language
    $user_language = $account->language;

    // don't do anything if no language is defined
    if (!$user_language) {
        return;
    }

    // verify if language exists
    $languages = language_list();
    if (!isset($languages[$user_language])) {
        return;
    }

    // verify if language is enabled
    if (!$languages[$user_language]->enabled) {
        return;
    }

    // redirect to preferred language homepage
    drupal_goto('<front>', array(
        'language' => $languages[$user_language],
    ));
}


User picture on multi site / multi database setup

What I would do is:

Use hook_form_alter to add non-managed file upload to profile edit page.
Configure Drupal or webserver so that directory for these files was common, or so that all pictures would get uploaded to the "main" site's folder.
To a profile, I would add a link field. Configure it to be shared between sites, too.
In a submit handler (again, added using hook_form_alter) I would populate this field with the URL to uploaded image.


How to remove the size attributes of all fields?

For text fields the size attribute is forcibly added in theme_textfield(), so the only way would be to override that function in your theme and remove that bit of code:

function mytheme_textfield($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'text';

  // 'size' removed from this call
  element_set_attributes($element, array('id', 'name', 'value', 'maxlength'));

  // add the rest of the function...

Exactly the same thing goes for the file element (see theme_file()), and most likely for any other element type you need to do do this for.


Why does the Path Breadcrumb module change URLs?

It was completely my fault. Path Breadcrumb works perfectly. The problem is that I had a path alias which instead of being English, it was All languages, and so the module didn't know what link to choose. I hadn't noticed the error before installing the module, and somehow the module installation made the error to be detectable.


CKEditor filtered HTML body field is not showing for non-administrator users when editing

The commonest reason for this problem (and OP has confirmed it in this case) is as follows.

The field that is inaccessible to some users has a filtered text format
The formats that can be set on that field include one or more that are not permitted to all users (typically "full html")
The content item in question has been edited by a user that has access to the restricted format and they have saved it with the field set to that format.
Now only users that have that privilege can edit the item because that field won't load for those who don't.

The solution is for a privileged user to edit the item and change the format and save it again, though that may result in the HTML changing in a way that's undesirable. If the item needs "special" HTML then it may not be possible for it to be maintained by the less privileged users.


Here's how you could achieve that:

function YOUR_THEME_preprocess_html(&$variables) {
  // The getRoles() method will return us the machine names, so there is no
  // need to process roles names additionally. However, I suggest prefixing
  // the names with "role-", so it's more obvious.
  foreach ($variables['user']->getRoles() as $role) {
    $variables['attributes']['class'][] = 'role-' . $role;
  }
}

Then in your html.html.twig file you can set the attributes this way:

<body{{ attributes }}>

Note: you might want to pass TRUE to the getRoles() method, if you want to exclude the locked roles (anonymous and authenticated). You can read the docs on this method here.


How to insert custom redirect script in index.php without losing it on update

If you want to run code before the Drupal kernel is started use a middleware.
Use the drush code generator drush gen middleware and put your code in handle() of the generated middleware class:
MymoduleMiddleware.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * MymoduleMiddleware middleware.
 */
class MymoduleMiddleware implements HttpKernelInterface {

  use StringTranslationTrait;

  /**
   * The kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * Constructs the MymoduleMiddleware object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
   *   The decorated kernel.
   */
  public function __construct(HttpKernelInterface $http_kernel) {
    $this->httpKernel = $http_kernel;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {

    if ($request->getClientIp() == '127.0.0.10') {
      return new Response($this->t('Bye!'), 403);
    }

    return $this->httpKernel->handle($request, $type, $catch);
  }

}


What might cause duplicate user registrations?

I think that this part of your question is crucial:

  ... there is a rule triggered by a "After updating an existing user account" event. The rule runs some simple PHP code that adds the users details to a CSV file.

I.e. to (a) understand what's happening and (b) to come up with some type of workaround. Read on for more details ...

Understanding what's happening

Your question seems like a variation of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

  some other module code is calling a user_save on hook_user_update triggering the rules event a second time.

If I was to debug this, I'd disable all contributed modules (except "Rules" and "Entity API") to check if it's indeed a contributed module (I don't expect it to be core). And then re-enable the contributed modules one by one until the issue comes back. As soon as it comes back, you pinpointed the contributed module causing the issue, and you can start working on a possible remedy for that.

Workaround 1

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):

Workaround 2

Another workaround to prevent this issue from happening, is to improve your existing rule to make it similar to the rule included in my answer to "How to implement a Rules Condition like [account:last-login] = never?". More specifically:

Add a Rules Condition like: User does NOT (!!!) have a role with role id = "4".
Add a Rules Action like: Grant User the role with role id = "4".

So this improvement of your rule will check if the user does not yet have some (designated) role with role id = "4" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case, then the user is granted that role. With this improvement to your existing rule, this is what will happen:

The 1st time your Rules Actions will still be performed (and grants the designated role).
the 2nd time not ALL of your Rules Conditions will be satisfied (since the designated role was granted before), and therefor your Rules Actions will no longer be performed.


Full Html Text format (and wysiwyg) show only for administrator role

I've got the same issue because of js error 'once is not defined'. To fix an error I've added to my html.tpl.php:

<?php print $scripts; ?>
<script src="/misc/jquery.once.js"></script>


Can we get full count of results from a query that is extended by PagerDefault

With the existing pager class I don't think you can get that data without running the count query again. The total count is queried directly and saved to a local var before being passed off to pager_default_initialize()...it's not saved anywhere.

One option would be to extend the default class and use that for your pager queries. This is un-tested but I think it'll do the trick

class MyPager extends PagerDefault {

  /**
   * Overrides PagerDefault::execute().
   */
  public function execute() {
    // Add convenience tag to mark that this is an extended query. We have to
    // do this in the constructor to ensure that it is set before preExecute()
    // gets called.
    if (!$this->preExecute($this)) {
      return NULL;
    }

    // A NULL limit is the "kill switch" for pager queries.
    if (empty($this->limit)) {
      return;
    }
    $this->ensureElement();

    // Get the total items from our new statically cached function.
    $total_items = $this->getTotalItemCount();

    $current_page = pager_default_initialize($total_items, $this->limit, $this->element);
    $this->range($current_page * $this->limit, $this->limit);

    // Now that we've added our pager-based range instructions, run the query normally.
    return $this->query->execute();
  }

  /**
   * Cache the results of PagerDefault::getCountQuery().
   */
  public function getTotalItemCount() {
    static $total_items = NULL;

    if ($total_items === NULL) {
      $total_items = $this->getCountQuery()->execute()->fetchField();
    }

    return $total_items;
  }

}

You could then construct a query like the following

$query = db_select('table', 't')
  ->fields('t')
  ->condition('foo', 'bar')
  ->extend('MyPager');

$current_items = $query->execute();
$total_items = $query->getTotalItemCount();

There might be an easier way, but I just can't see it.


HybridAuth module can make the block for this icons then you can place that icons block top of the main content block. it will show top of the login form


How can I embed a view in a template when passing view name and parameters are passed as variables?

Try to avoid using {{ content }} this way. The position you have found in the render array in your last comment can change anytime when reconfiguring the paragraph type or when installing/updating code. Render arrays are not APIs and they are only required to have valid renderable child elements at the lowest level, but not a fixed structure.

The Entity API on the other hand, which you would use to access {{ paragraph }} in a paragraph template, does not change, at least not without a transition period while you can still use a deprecated API.

Example:

// field value like string or number
{{ paragraph.field_example.value }}

// target id of a reference field
{{ paragraph.field_reference.target_id }}

See also https://drupal.stackexchange.com/a/263285/47547.


You might considder using the search api module. It allows you to do full text search on the index you setup, it has support for facets integrates with Solr and a lot of other nice things. I can recommend it for some easy and powerful search. It also integrates with Views allowing you to easily customize search results.


How to override thumbnail generation of file type media?

In the media source plugin for this media type you can find the code generating the thumbnail. See the source code of the "File" media type provider.

To summarize the code, you have to put your thumbnails files for each supported MIME type in the folder configured in the "icon_base_uri" configuration (which is stored in the "media.settings.yml" configuration file).

For example, using the default "public://media-icons/generic" folder and inserting a PDF media, you have to store your thumbnail image under the name "public://media-icons/generic/application--pdf.png" for it to be detected and used.


Change site logo for an specific content type

The simplest way would be to create a tpl for the content type to do that you can follow the below steps

First create a preprocess_page function as given below. This would go into the template.php file.

function YOURTHEMENAME_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

now you can create a new page.tpl per content type something like

page__CONTERNTTYPENAME.tpl.php

You can copy the entire content of the existing page.tpl.php into this and replace the logo with the desired logo.

in zen theme the logo is in the page.tpl is printed as follows

<?php if ($logo): ?>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
    <?php endif; ?>

here you can replace the image src with the direct path to your logo.


use theme_menu_link() to modify your menu links on the fly:

style="display:none"
class="invisible"

e.g.

function mytheme_menu_link(array $variables)
{
   if ($variables['element']['#href']=='temp-menu-link') {
       $variables['element']['#attributes']['class'][] = 'invisible';
   }
   return theme_menu_link($variables);
}

Security note: It'll still be possible to access the URL, thus a "state check" must be implemented on the receiving end if temporarily invisible also means 'not permitted to call'.


Giving Add and remove option to select and deselect from one list to another

I think you're probably looking for the Improved Multi Select module.

The Improved Multi Select module replace the default multi-select boxes with two pannel list and search.
The first panel holds the options that are available, and the second panel holds the options that have been selected.
Two panels are separated by "add" and "remove" buttons. You can select an item from the first box, click the "add" button, and add it to the second box. Likewise, you can select an item from the second box, click the "remove" button, and it goes back into the unselected box.

The screenshot from the module page looks pretty similar to the screenshot in your question, except there's no drag-and-drop re-ordering built in (you would need to implement that yourself I think):


how to change node edit path from node/[nid]/edit to node/[nid]/update?

I think this is a legit request as long as you add an additional alias as opposed to overwriting system paths.

I would implement hook_node_insert() and then use path_save() to set your custom edit path on node creation. You will also probably need to make sure that this hook runs after the Pathauto module has set its path, so you can use the alias it sets as part of your additional edit alias.


How can I override or disable a parent theme's CSS file?

Add this to your theme's .info.yml to override it with css/my-menu.css from your theme:

libraries-override:
  classy/base:
    css:
      component:
        css/components/menu.css: css/my-menu.css

To disable it (don't load it when loading the classy/base library):

libraries-override:
  classy/base:
    css:
      component:
        css/components/menu.css: false

To get the classy/base key you need for the override, find the *.libraries.yml file where the CSS is declared. The part before the slash is the * in that file (e.g. classy.libraries.yml), and the part after is the top-level key in that file under which the CSS is declared.

In most cases I find it easiest to actually copy the library declaration from the libraries file that declares the asset to maintain the 'css', 'component', keys and indentation.

Note that you can do the same thing for JavaScript assets as well.

See https://www.drupal.org/node/2216195#override-extend for more information.


How to use views taxonomy contextual filters with menu tabs?

I managed to resolve the above problem with the following configuration:

I created the contextual filter on taxonomy term field and in the filter settings section When the filter value is NOT in the URL I selected Provide default value and Raw value from URL with Path Component 2 and the option Use path alias checked.

In the filter settings section When the filter value IS in the URL or a default is provided I selected the appropriate vocabulary and for Filter value type Term name converted to term ID.