How to create a chart about the number of node views per day (since last week)?

Using the Charts module
Step 1: Create the tabular format of the view
First to address the "if it's possible to list last 7 days date in views at all or not" part of your question, you really need to first work on getting the view created correctly. That's also what's recommended in the Bonus tip within Steps to create charts using the views UI, i.e.:

You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first. ...

Step 2: Add the chart to your view
Do not try to start this step if you didn't first complete the prior step.
There is an issue which might help to answer this question, or at least to understand the challenge here. I.e. Graph node input over time (support date formatting on a continuous axis).
In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.
Using the Quant module
If using the Charts module you can't get it to work (or don't want to consider the suggestions above), then you may want to look at the Quant module as an alternative. Here are some excerpts from its project page:

... provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.
Provided charts:

Content creation
Comment creation
Content creation by type
Aggregate content creation
User creation
Page views (requires Statistics)
User shouts (requires Shoutbox)
User point transactions (requires User Points)
Group creation (requires Organic groups)
Group joins (requires Organic groups)
Invites sent (requires Invite)
Invites accepted (requires Invite)
Statuses shared (requires Facebook-style statuses)
Private messages (requires Private message)

Especially the "Page views* chart that is provided might be close to what you're looking for.
Using the Visitors module
If you're looking for info related to visitors of a website (registered users is a subset of them ...), the Visitors module might be a valid alternative to consider also (and/or addition to the above modules). In this case, all you have to do is to enable the module and review the various out-of-the-box reports (which include charts created with the pChart library).
The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module.
In this specific case, you probably would want to look at the Days of week report (and chart). Note that, as a bonus, you can specify the desired date filter (from / to) also.
Refer to the Visitors community docu for some more details.
Extra reporting features can be enabled via these sub-modules:

The Visitors GeoIP module, to also report about countries and cities.
The Visitors Browscap module, providing statistics on visiting browsers.

Evaluating other charting modules
If none of the above modules would work in your case, then you might want to look at the "Comparison of Charting modules" documentation.
Disclosure: I'm a (co-)maintainer of all modules mentioned above (and original author of the comparison),
I hope this does not violate the site's policy on self-promotion.


Expand children menu items with parent link, without javascript

If I understand you correctly then setting the parent link to "Show as expanded" should get you the desired result. You can see the option when you go to Structure -> Menus -> list links (of the correct menu) -> edit (the parent menu item which should have it's child links always displayed).


I have solved my issue.
Changed the type to view block and then I did views_embed_view()

Works fine


You need to set your nginx config file to rewrite 404 error to index.php

Just added this:

error_page 404 = @rewrite;
location @rewrite {
  rewrite ^ /index.php;
}


What are the steps to create a custom widget based on taxonomy_select?

The taxonomy_term_reference field type uses the core options_select widget and implements hook_options_list() to provide the values, the taxonomy module doesn't implement any of the widget code itself.

The options_select widget is defined in options_field_widget_info() in the code options.module file (inside the field module folder). The form elements themselves are built up in options_field_widget_form() in the same file. They're pretty well commented so you should be able to get a good idea of how they work.

I'd also recommend the Examples module if you haven't already got it, it has a field type/widget example module with good sample code and comments.


Where do i change the settings of the redirected URL after a new user registers on my drupal 7 site?

Hope this will help you,

In Drupal 7 you can achieve it many ways

Using Rules, create a RULE with Event - After saving a new user account and Actions - redirect the page and if you want you can also add Conditions, as per your requirement.

Using hook_form_alter

function HOOK_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_register_form':
      $form['#submit'][] = 'custom_user_register_submit';
    break;
  }
}
function custom_user_register_submit($form, &$form_state) {
 $form_state['redirect'] = 'YOUR_REDIRECT_PATH_HERE';
}

By using destination parameter

More simpler you can also using destination parameter. Just add
the destination parameter in the URL where you want to redirect
it. You can achieve it by using theme_menu_link. You can refer this answer
YOUR_DOMAIN/user/register?destination=YOUR_REDIRECT_PATH_HERE

Note : Instead of writing the code or installing the module you can use  Destination parameter OR RULES .


How do I add a custom button next to the "Add Content" button?

You have to provide mymodule.links.action.yml in your module.

This is an example from core for the Add content action button from your question:

node.links.action.yml

node.add_page:
  route_name: node.add_page
  title: 'Add content'
  appears_on:
    - system.admin_content

Reference: Providing module-defined actions


Adjust weight for menu items in different languages

With Drupal 7 core alone, user-defined menu items are not translatable. The Menu translation module, part of the Internationalization (i18n) package, allows users to select a translation mode for each menu (Figure 1).

The following modes are available:

No Multilingual Options
Translate and Localize
Fixed Language

Translate and Localize Menus

For most use cases, and especially if the structure of your menus is consistent across languages, Translate and Localize is the preferred method of translating menus. You can create one menu for all languages, and translate or localize each menu item. There are two ways that menu items will be translated:

You can set a language when creating a custom menu item so that the
menu item will only show up for that language (Figure 1). Menu items
that link to nodes in a particular language will be treated this way.
You can localize other custom menu items without a language (for
example, menu items linking to Views pages). Use the Translate tab to
translate the menu item title and description (Figure 2). Translators
can also use the 'Translate interface' pages to translate these menu
items (Figure 3).

Figure 2

Figure 3

Fixed Language Menus

If you choose Fixed Language, you'll have to set up a separate menu in each language. This could become tedious if have a lot of languages enabled on your site, but is useful if the content or menu structure is different for each language.

Menu Items Linked to Nodes

Useful modules:

For Entity translation use entity_translation_i18n_menu submodule of
Entity translation.
For content translation use Menu translation - Node.

A menu item linked to a node will be displayed only when the node language matches the page language. This is due to how the menu system works and the 'Language selection' feature in i18n. Therefore, to get translated menus items that link to nodes, you first need translated content: see Translating content to different languages.


"Show as expanded" selected but children menu items not displaying

Bartik theme is not designed by default to show parent items in Primary navigation section as expanded, even if you checked "Show as expanded" for each parent item in the main menu.

In order for you to make Bartik theme to render parent items and their children items; add the following code to template.php themes/bartik/template.php

function bartik_links__system_main_menu($variables) {
  $menu_name = variable_get('menu_main_links_source', 'main-menu');
  $menu_tree = menu_tree($menu_name);
  return drupal_render($menu_tree);
}

Note: make sure to clear Drupal cache once you apply the new changes.


How to configure a module after installation

It's up to the module itself to present configuration options, and in Drupal 6 these can be a bit harder to find. I definitely recommend installing the admin_menu module (http://drupal.org/project/admin_menu), which can provide expanding drop-down menus to easily browse through all of the admin-side links.

With cTools specifically, the base 'Chaos tools' module won't do anything on its own, though it can be required by other contrib modules. If you're looking to use one of the bundled modules such as Stylizer or Page Manager, you'll need to enable and configure those modules separately.


How to enable the php option in Views contextual filters, provide a default value option?

You can php option in the filte using "Views Php" module

For installing this please follow such steps :
1. Download this module using https://www.drupal.org/project/views_php.
2. Install this module.
3. In views filter now you will get PHP option.


Is there a module that would allow me to reorganize the way fields are displayed for a content type form?

The best way to do that is using Display Suite module.

  Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files.


Please follow the link about Creating Tabbed Views.

For quick reference, I am copying important steps here from above link.

Create a view.
Name the path (url) to be what you want the default tab to be, for example, 'document/all'.
Configure your view with sorting, filtering, etc.
Choose 'Default menu tab' in Menu option and name it.
Choose 'Normal menu item' to be the parent, since this tab is linked directly from a menu, i.e. 'document'
Finish this first tab.
Create another display.
Name the path of this one as a tab option, like 'document/homework'.
Configure it.
Choose 'Menu tab' for this one.
Finish this tab.
Repeat (8) - (11) for more tabs.

Note: If you want three tabs on same page with different/same view result, then please install Quick Tabs module.

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*. You can
  create a block on your site containing multiple tabs with
  corresponding content.


Found the answer.

The encoding should be utf8_bin not utf8_general_ci


How to add a 'read more' theme link to a custom view mode?

I took a look here

https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_build_content/7

and here

https://drupal.org/node/1844292

and came up with this

function YOURMODULE_node_view_alter(&$build) {
    if ($build['#view_mode'] == 'YOURVIEWMODE') {
        $node=$build['#node'];
        $links=array();
        // Read more for teas ext
        $node_title_stripped = strip_tags($node->title);
        $links['node-readmore'] = array(
            'title' => t('Read more about @title', array('@title' => $node_title_stripped)),
            'href' => 'node/' . $node->nid,
            'html' => TRUE,
            'attributes' => array('rel' => 'tag', 'title' => $node_title_stripped)
        );
        // Assign links
        $build['links']['node']['#links']=$links;
    }
}


Cannot apply custom CSS via theme settings

I think the problem is that you forget to add a reference statement in your theme's info file.
like this:

stylesheets[all][] = css/layout.css

After that, need to clean the cache.


Why is AJAX pager in Views not recording the history

I have not used but you can take a look

Statehandler module and History.js module


Autopopulate EntityReference field using rules?

You want the Entity Reference Prepopulate module.  It's very similar to the Node Reference URL module but the maintainer of that module is stubborn and sticking to only referencing Nodes and not Entities.

Rules has always had a hard time with prepopulating reference fields so please don't go that route.  You can combine Rules and ERP by using Rules to populate other fields and ERP to handle the referencing.

Everything is URL based so you must setup your links appropriately.  The structure is node/add/article?[field_ref]=[id]
So you could have
node/add/review?field_business_ref=457

your link to the form could look something like l('add review', 'node/add/review?field_business_ref='. $node->id)


entity_load failure: Adding revision capability to entity with existing data and unticking "create new revision" still creates a revision

So I experimented and contrary to what I perceived, saving a node (as an example of an entity) even without "save a new revision" checked, still saves a revision...

So somewhere in the confusing bowels of the entity loading procedure it was diving through Drupal-shaped rabbit holes and trying to load revision information because it noted that the custom entity was revision enabled (where I enabled it in hook_entity_property_info). Because I'd only added the revision capability after using the entity there was none. So I had to do some SQL work.

Firstly I selected all information in the original table into the new table. In doing so, the auto-increment setup on the revision_id column populated the revision_id column in the revision_id with unique incremental values.

Secondly I did a big ol' looping thing to get all the revision_ids from the revision table and one-by-one put them in the original table. Details of that query are here after I had a little bit of trouble, but it might help someone else out.

Now it's working.


Is it possible to append Media's file browser to a certain node type?

It appeared I had been using the wrong form element. My custom form was created as below:

function mymodule_file_upload_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'media',
    '#title' => t('Choose an image'),
    '#description' => t('Choose an image'),
    '#tree' => TRUE,
    '#input' => TRUE,
    '#media_options' => array(
      'global' => array(
        'file_extensions' => 'gif jpg jpeg png',
        'file_directory' => 'conferences',
        'types' => array(
          'image',
        ),
        'schemes' => array(
          'private' => 'private',
        ),
        'enabledPlugins' => array(
          'upload',
          'media_default--media_browser_my_files',
        ),
      ),
    ),
  );

  return $form;
}

And then with some javascript I manged to get the fid of the file

$("form").on("change", "input.upload", function() {
  var val = $(this).val();
  $.ajax({
    url: Drupal.settings.basePath + 'draw/file/' + val,
    success: function(data) {
      src = data
    }
  });
});

That path was registered in hook_menu() to return the path of the private file as per:

function mymodule_menu() {
  $items['draw/file/%file'] = array(
    'page callback' => 'mymodule_page_file',
    'page arguments' => array(2),
    'access arguments' => 'view own private files',
  );
  return $items;
}

function mymodule_page_file($file) {
  global $user;
  if($user->uid == $file->uid) {
    echo file_create_url($file->uri); // Use echo to prevent theme to appear.
  }
}


How to check the success of AJAX request for following chunk of code using Drupal.ajax()

Could you provide more information on why the success function didn't work for you or what code you were using for it? This should work exactly like ajax settings in jquery Ajax since its just a passthrough, so your code would be something like this in your js:

$.ajax({
    url: eventEditFormUrl + '/nojs',
    selector: popContClass + '>div.content',
    wrapper: popContClass + '>div.content',
    event: 'add_event',
    method: 'html',
    progress: {
        type: 'none',
    },
    speed: 'fast',
    effect: 'fade',
    success: function(){
       $(this).html("woot.");
    }
});


Drupal 8 custom type content, getting values for a field of type Taxonomy (hence, Entity Reference), which can have multiple values in the field

I think $node_item->category->referencedEntities() is what you want to use.

You have misspelled the method in your question.

 if ($node_item->category->isEmpty() === FALSE) {
    $vars = [];
    // Get referenced entities and add each to array of terms.
    foreach ($node_item->category->referencedEntities() as $term) {
      $vars[] = [
        'name' => $term->label(),
        'phone' => $term->field_phone_number->value,
        'email' => $term->field_email_address->value,
      ];
    }
  }


Create a form programmatically and display result on template

I recommend adding the results of the query to the form markup-like:

$form['something'] = array(
  '#theme' => 'statistiques_template',
  '#vartest' => $vartest,
);

is equivalent to theme('statistiques_template', array('vartest' => $vartest)) -- the theme system will remove the # from the variable names if #theme is set.

But, of course, you can add the form to the page build as well, see how comment_reply does it:

  $build['comment_node'] = node_view($node);
  $build['comment_form'] = drupal_get_form("comment_node_{$node->type}_form", (object) $edit);

If coding in Drupal 7, forget direct theme calls, strings and the . operator. Work with render arrays instead. It's also a good preparation for Drupal 8 where concatenating strings leads to double escape bugs.


In my checkboxes if i have a 0 value it select this checkbox

That's how the form API handles multiple selections for form elements.

You can easily solve it with standard language features:

$selected = array_filter($form_state['values']['kkkk_security_levels']);


Is it okay to expose .yml or .install files to public?

No.

The web server (e.g. via apache's  directive) needs to be able to read (not write) the index.php file (and occasionally others such as update.php), and also static files such as .css/.js, pdfs and images.

The php interpreter is not limited by  directives and so most other files required by php do not have to be visible.

As Hudri said, leave the .htaccess files as they are, configure the server to notice them (AllowOverrides) and refer to an appropriate guide, such as:
https://www.drupal.org/docs/develop/local-server-setup/linux-development-environments/installing-php-mysql-and-apache-under


Is there any clean way to have the Drupal login form create a session for phpBB also?

If what you want is a clean way to integrate phpBB with Drupal, I think phpBB Forum Integration is want you need.

This module will not only "embed" phpBB within a Drupal site (and synchronize account info, such as user names, roles, passwords, emails, signatures, and avatars, with only one login), but it also let phpBB topics be created from Drupal nodes.

The phpBB forum can be displayed in a full window, in a frame inside Drupal, or in a Drupal page.


You are using using filtered html (Text Format).   [As per your screenshot above]

Filtered HTML only all the following HTML tags

Web page addresses and e-mail addresses turn into links automatically.
Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
Lines and paragraphs break automatically.

  You need to change text format to FULL HTML if you wish to retain all HTML formatting

As a best practice Full HTML use should be limited


I think that your confusion comes from the fact that Drupal 6 and 7 mixes menu and routing. One set of hooks for both purposes, and here you have problems. If this hook was named hook_route_alter(), using it to alter permissions to some routes would be obvious, right? So that's what modules do, using the name they got. Personally I agree it's not most lucky naming, but once you remember that in this context, basically, menu == routing, it all becomes much more intuitive.


For query tracing you can use devel module. Devel module include the Web Profiler module which shows many options. Even you can see the all queries executed for page.

Following are the sample details of web profiler.

UPDATE: So how you can see your view query in web profiler?
Well, follow this steps.

For tracing purpose disable view cache. "Select 'No Cache' from advance section".
Then Clear all drupal cache.
Open views output page.
Click on database link from web profiler.
Now search in page(Ctr+F) your field name.
E.g: Here I added one field in my view, that is field_image. So I search that and I get view query..
Once you found out your query, you will see there is no parameter in query, Well to see which paraters query is taking click on "Info" tab of query. And you will see all parameters of placeholder.


it should work this way:

create the global text field, with the text as the link text -

then rewrite the results, and output as a link using <front> as the path -


How to name multi-sites for different environments (dev and staging)?

I think you may be looking into aliases.

On your sites folder there should be a example.sites.php. It basically allows aliasing sites to different names.

You could create an if and based on some environment condition (maybe the output of hostname? or a file somewhere that contains prod vs dev), enable or disable the aliases.

More documentation:

https://api.drupal.org/api/drupal/sites!example.sites.php/8.2.x
https://api.drupal.org/api/drupal/sites!example.sites.php/7.x


#2013 error when starting the dev desktop

Your first error seems to be related to a problem with port numbers/bind address of the MySQL server; see this post for a bunch of suggestions for a fix.

The second error is a permissions issue; you need to give your web server user write permissions over the "sites/default/files" folder, for example using the following command:

chmod -R 755 /path/to/root/sites/default/files

If you don't know how to do it I'd really advise getting someone who does to help you, that's messing about with POSIX permissions and you need to know what you're doing or things can go horribly wrong.


validating textfield input with ajax on every key entry

The ajax callback in drupal is nearly as slow as a complete page load and this takes between 200 und 1000 ms. So checking every key stroke is no option.

If you don't check against the database, there is no need for an ajax callback. I would check "right" or "left" in javascript. If you need a server side check, you can write a stand-alone php file, that does this check without drupal, then your response time will be between 10 and 20 ms.

To replace the slow ajax with javascript you can start with this script:

val_left_or_right.js:

(function ($) {
  $('#edit-direction').keyup(function(){
    var direction_text = $('#edit-direction').val();
    if (direction_text != 'left' && direction_text != 'right') {
      $('#error_message').html('Please type left or right');
    } else {
      $('#error_message').html('OK');
    }
  });
})(jQuery);

attach the js to the form:

$form['#attached']['js'] = array(
  drupal_get_path('module', 'your_module') . '/js/val_left_or_right.js',
);


How to alter a function in a contributed module?

As far as I know, you can only alter the functionality the module exposes using hooks defined by that module, and you cannot alter just any function defined in the module. For instance, shs_json_term_get_children is just a callback, and you cannot alter it.

The SHS module defines several hooks that are listed in the shs.api.php file. For instance, there is a hook called hook_shs_term_get_children_alter, that allows you to modify the list of terms displayed to the user: http://cgit.drupalcode.org/shs/tree/shs.api.php?h=7.x-1.x#n73

/**
 * Alter the list of terms within a level of the term hierarchy.
 *
 * @param array $terms
 *   List of terms displayed to the user (single hierarchy level).
 * @param array $alter_options
 *   - vid: ID of vocabulary or field name
 *   - parent: ID of parent term
 *   - settings: Additional settings (for example "language", etc.,)
 */
function hook_shs_term_get_children_alter(&$terms, &$alter_options) {
}

In your module, you would need to implement that hook like that:

function YOURMODULENAME_shs_term_get_children_alter(&$terms, &$alter_options) {
  // Your code here.
}


I used

  $output = field_view_field('commerce_customer_profile', $form['customer_profile_shipping']['customer_profile']['#value'], 'commerce_customer_address');
  $form['customer_profile_shipping']['rendered_address'] = array(
    '#prefix' => '
',
    '#markup' => render($output),
    '#suffix' => '
'
  );


After updating I got these error messages

Try on terminal this command

drush entity-updates

Or if you have Devel module installed, you can also use the "Execute PHP Code" page at http;//example.com/devel/php

try {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}
catch (EntityStorageException $e) {
  print_r($e);
}


To your first problem, the menu disappearing on about/faculty-staff/directory:

Check how the menu block is configured.
Check if there is another menu item in another menu that links to this page. It could be that Drupal picks this up and thinks we are in another menu.

(There is a more general solution that I am going to post in another answer)


In the past I used Views Data Export to build a spreadsheet in Views that contain the NID and the plain text field I needed to use as a reference.

Then in Excel, you can use VLOOKUP to join 2 excel files based on a common column (building_id) so  that way you can obtain the entity referenced nid you need for your import.


Added type markup below the submit code in $form_state['storage']['results'] and that does the trick...

  $form['submit'] = array(
    '#value' => 'Search',
    '#type' => 'submit',
  );

if(isset($form_state['storage']['results'])) {
        $form['result'] = array
        (
          '#type' => 'markup',
          '#markup' => t('The results of the form are: !results', array('results' => $form_state['storage']['results'])),
        );
      }


How to get rid of added URLs when printing a Bootstrap-themed page?

Found it: it wasn't jQuery, but CSS3.  Down in bootstrap.css, we find:

@media print {
  ...
  a[href]:after {
    content: " (" attr(href) ")";
  }
  ...
}

Overriding the style with content:none handles the situation fine.  There are some similar :after clauses in there doing similar things, but this is working for now.


How can I add user information to orders administration pages?

As per Andy's advices about Drupal Theming, I used devel_themer, and could find immediately the correct template : commerce_backoffice/theme/commerce-order--backoffice.tpl.php.


Why is the programmatically removed paragraph item still showing after adding a new paragraph to the node?

You have 3 tables doing the job: a table which stores node data, a table which stores paragraphs data, and a table which stores relation about node and paragraphs. Now you emptied the table which stores the paragraphs data, but the node-paragraph relation table is still there. So if you have added 4 paragraphs to a node and deleted that 4 paragraphs, still drupal assumes there should be 4 paragraphs attached to that node.

so if you want to delete them entirely you have to fetch node data which has "paragraph" field value, delete field value from each node and save it.

so here are steps :
you can run a database query on field table, and get all node-paragraph relations. now you have a list of all nodes that have a paragraphs, so having node ids and paragraph ids you can first remove paragraphs from node using a code like this:

$node = Node::load($nid);
$node->FIELD_NAME->setValue(array());
$node->save();

and then delete correspond paragraphs using a code like the one you mentioned. of course you don't need another query as you have paragraph ids.

if you don't mind removing all paragraph values from database and only don't like them to be shown in your node, then you can write an entityquery like this :

$query = \Drupal::entityQuery('node');
$query->exists('field_to_check');//Check A field value is NOT NULL
$ids = $query->execute();

so it gives you all nodes which has value for that field, then you only can run :

foreach($ids as $nid) {
  $node = Node::load($nid);
  $node->FIELD_NAME->setValue(array());
  $node->save();
}


How to remove the form_state, form_id and form_build_id when submitting a form?

In Drupal 7, you can use the form_state_values_clean() function that removes:

form_id
form_token
form_build_id
op

Usage example:

<?php
/**
 * Let's say this is your form.
 */
function your_form($form, &$form_state) {
  // Form items go here.

  // Let's add the form actions element...
  $form['actions'] = array(
    '#type' => 'actions',
  );

  // ...and the form submission button with a function callback that removes
  // 'form_id', 'form_token', 'form_build_id' and 'op' values upon form submit.
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('your_form_submit'),
  );
}

/**
 * And this is the submission handler/callback for your form where
 * 'form_id', 'form_token', 'form_build_id' and 'op' values will be removed.
 */
function your_form_submit($form, &$form_state) {
  // Let's unset 'form_id', 'form_token', 'form_build_id' and 'op'.
  form_state_values_clean($form_state);

  // Now the $form_state['values'] doesn't contain 'form_id', 'form_token',
  // 'form_build_id' and 'op'.
  $form_values = $form_state['values'];

  // Do the rest…
}


How to hide group header in grid style View?

Several options :

hide the relevant elements with CSS.
override the relevant template to prevent the output of the field.
depending on the view, tick the checkbox to not display the field in the field properties.


Configuring Blocks and the use of wild cards

Regular expressions based matching is not yet supported on D8 block visibility patterns and wildcards. The best bet at this point is the following module:
https://www.drupal.org/project/block_visibility_groups

You can add multiple rules to show or hide blocks.


CSS or and JS aggregations all makes site slower!

You're confusing PSI and webpage loading times; they are not the same thing.

PSI is series of benchmarks for optimizing performance. It's a checklist Google provides to give you suggestion for improving performance. It doesn't gauge what your site's actual speed is. Use your browser's network activity inspector if you'd like to analyze site load times against CSS/JS aggregation.


What all contributes to drupal page execution time?

Get a cachegrind of your site. xdebug or xhprof can generate one. This will tell you what functions are taking the longest to run. Until you do this, its a bad guessing game.


Prevent Quick Editing on certain DOM elements

Is there a way to prevent quick edit from applying changes to anything
  within

A quick fix is you can write a small jQuery snippet which gets trigger after QuickEdit apply its DOM changes. For example, suppose I do not want to allow quickedit on any node, i.e. it can be full display or teaser. Below code will find all article tags on page and remove its data-quickedit-entity-id attribute, so quickedit option won't be available for it.

$('article', context).removeAttr('data-quickedit-entity-id');


If you display menu in block.
Select Configure block from the drop down that appears
On the next screen enter <none> in the Block title and then click Save block at the bottom of the page.
Or you can simply display: none via css.


How can I see my drupal site as a anonymous user while logged in as admin?

No that is impossible.

What you could do is give access to devel for all users. You shouldn't be using devel in a live environment anyways, so just make sure you remove devel and revoke permissions before staging to production environment.


Can someone explain the @RestResource annotation for building a Rest resource?

Annotations are used in Drupal 8 to provide meta data in the same location as the class definition. It was borrowed directly from Symfony which is used in the Drupal 8 core to take advantage of an existing framework. The meta data is contained from the lines between @RestResource( and the closing ). Everything else is treated as a normal php block comment. For example I have a custom REST resource for which the annotation is:

/**
 * Provides a resource for database intermed table entries.
 *
 * @RestResource(
 *   id = "intermed",
 *   label = @Translation("Intermed content entity standard methods"),
 *   serialization_class = "Drupal\intermed\Entity\Intermed",
 *   uri_paths = {
 *     "canonical" = "/intermed/{intermed}",
 *     "http://drupal.org/link-relations/create" = "/entity/intermed"
 *   }
 * )
 */

So for this resource intermed is the id and is used in request operations. The canonical form /intermed/{intermed} will be used for operations other than POST which uses /entity/intermed

In the canonical setting the {intermed} denotes a parameter to be passed.

So if I was to send a GET request to site d8beta14.qetm.org as format HAL+JSON for the intermed table entry for which the id was 2:

GET http://d8beta14.qetm.org/intermed/2?_format=hal_json

This GET operation requires three headers: Authorization, Accept, Content-Type


How to add “Quote Request” button on some products?

Have a look at the feature request "Let customers build a 'quote' cart and request a quote instead of checkout". Even though it has status "postponed", it has some interesting comments, such as the very first one, which includes this (I added the bold markup):

You probably don't need any specific module to do a majority of this. All you'd have to do is add $0.00 prices to all your products and then just don't display those prices anywhere. You don't have to show product price fields in your display nodes, and you can edit your cart Views so they don't include prices any more. The only thing you'd really have to change is the text pertaining to the shopping cart. You could do this with a module like String Overrides or just alter the various places directly with a hook in a site customizations module.
When it comes time to submit the quote, I suppose you may want a custom button on the Cart form that changes the status of the order to "Needs quote" or something - if that's true, then that's all your custom module should really be responsible for ...

Also, the comment #7 in that same issue seems worth considering, this is part of what it says (I added the bold markup):

I got this working quite easily! As Ryan said, make all product prices $0. Use String Override module and override a couple of the basic syntaxes. Edit a couple of Views where certain terms/words still creeped through. When you see syntax that needs to be changed on a view and you've already used String Override for it but it's not overriding it, just click on the right corner of the view on the gear to edit view. Then change the wording on there. I also had to remove or change some of the text that were on some views but under the "FOOTER" section (middle section of view). I had to do this a lot for the cart and checkout views.
I added another checkout rule under Store>Configuration>Checkout Settings under "Send Request"-section to email me when the person places a request.

Maybe not a complete solution / answer to your question, but at least a partial answer to think about ...


How can trusted host patterns be set dynamically?

By design you can't access the database from a non trusted host within Drupal. The kernel checks the trusted host patterns when the settings are read from file, but without the settings you don't have the credentials to open the database connection.

There are a lot of ways to work around this. As mentioned in the comment by @NoSssweat you can write the trusted hosts to a file and include the file in settings.php. Or you can access the database from outside of Drupal and invoke this PHP script in settings.php. Or use a wildcard trusted host pattern matching all possible domains and then enhance security by adding a second check against the custom domain names in a kernel event subscriber when the database is available.


Looking at the source code it appears that both date and time have a #size key. I don't have time to test this, but you might be able to access it from the 'time' element of the field.

$form['feld']['start']['time']['#size'] = 10;


Exclude nodes present in panel from view pane

We had the same issue on a page with a lots of news and user customizable Top News - we used the module views_exclude_previous module and it worked fine for this case.


Display comment form without the comment thread

To display comment form without comments list, you need to override field--comment.html.twig template, and remove the following lines:

  {% if comments and not label_hidden %}
    {{ title_prefix }}
    <h2{{ title_attributes.addClass(title_classes) }}>{{ label }}</h2>
    {{ title_suffix }}
  {% endif %}

  {{ comments }}

to override it:

From your theme, just create one of the following twig file in you templates folder, and put in it field--comment.html.twig content without the above section.

   * field--node--comment--article.html.twig
   * field--node--comment.html.twig
   * field--node--article.html.twig
   x field--comment.html.twig
   x field--comment.html.twig
   * field.html.twig

Note: the above suggestions for article content type, you may have different suggestions.

From your module, implement hook_theme for one of the suggestions like the following:

/**
 * Implements hook_theme().
 */
function MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'field__node__comment__article' => [
      'base hook' => 'field'
    ],
  ];
}

And make your changes in MODULENAME/templates/field--node--comment--article.html.twig


Which module can be used to get the number of logged in users per day and supports views?

Couple of options (haven't tested either one):

This sandbox project seems to track login time and provides Views integration: https://drupal.org/sandbox/AshishThakur/1614582
Login History also tracks login time, but does not have Views integration yet. A patch was started for this, but looks like it isn't complete: https://drupal.org/node/1402266


When creating a Panel Page and selecting a layout, the page layout is not overidden

Yes, that's how Panels is designed to work.  It can only take over the content rendered to the main content region.  If you want Panels to take over all regions then you need to use Panels Everywhere which is, incidentally, compatible with Omega 4.


How do I add a description to the node title form field?

In a hook_form_alter() or hook_form_FORM_ID_alter(), add a description attribute to the node form element array:

 //Add a title field description
  $form['title']['#description'] = t('Enter your awesome title field details.');


How to change DB active config storage of an installed site to config file storage?

Here are the steps I followed:

1) Export settings to your current $config_directories['sync'] directory (by default it is defined in settings.php and it is something like 'sites/default/files/config_VerYlonGkEY0123/sync')

$ drush cex

2) Create these directories (should be writable):

config/
  active/
  staging/
  sync/

3) Copy/paste all files from $config_directories['sync'] to config/active/

4) Add the new settings to settings.php

$config_directories = array(
  CONFIG_ACTIVE_DIRECTORY => DRUPAL_ROOT . '/config/active',
  CONFIG_STAGING_DIRECTORY => DRUPAL_ROOT . '/config/staging',
  CONFIG_SYNC_DIRECTORY => DRUPAL_ROOT . '/config/sync',
);

$settings['bootstrap_config_storage'] = array('Drupal\Core\Config\BootstrapConfigStorageFactory', 'getFileStorage');

5) Add this to service.yml (in the same directory as the settings.php):

services:
  config.storage:
    class: Drupal\Core\Config\CachedStorage
    arguments: ['@config.storage.active', '@cache.config']
  config.storage.active:
    class: Drupal\Core\Config\FileStorage
    factory: Drupal\Core\Config\FileStorageFactory::getActive

6) Export the settings to sync:

$ drush cex sync

Than you should have the settings in config/sync :)


Taxonomy term doesn't show up in admin/structure/taxonomy/manage/tags/overview

It sounds like they are missing parent value of 0 in the term hierarchy table. That will do it. That table just needs the tid and parent value of '0'. Try it by adding one of the tag term tids to that table, clear the cache and reload that page. This is easy to miss in migrations.


Instead of a pre-render function, I think the correct spot to modify values is actually hook_views_post_execute().  This is invoked after the query has run, but before the data has been passed to rendering.

  Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.

It has been a while since I've personally played with Views Data Export so I'm not 100% sure why you're seeing only some values change and not others, but I recall the rendering of the export being a little abnormal compared to the usual render process.


How do I exclude the current user from the search?

You could write a simple module using hook_views_pre_view.

Be sure to index the User ID
Under Filter Criteria, add Indexed User: User ID, and set it to NOT EQUAL TO and use 0 (anonymous user, which will never be in this list).
Using MY_MODULE_views_pre_view with the global user value, replace 0 with the UID of the current user.

function MY_MODULE_views_pre_view(&$view) {
  global $user;
  if ($view->name == 'VIEW_NAME') {
    if ($user->uid) {
      $view->display['default']->handler->options['filters']['uid']['value'] = $user->uid;
    }
  }
}


Add Attribute to Textfields in Admin Theme

template_preprocess_field is for field output themeing not input field themeing, you maybe looking for theme_textfield or hook_field_widget_form_alter


Query remaining field names from a database table

There are multiple table locations for Drupal field data: the base User entity
table users_field_data & the user__$FIELD tables that contain the custom fields defined by site builder / developer. If you need field data from a DB query, then you're going to need to build a query with a few joins to put it all together.
If you're only looking for the field names then it's much earlier to use the entity field manager to pull the base & custom fields:
\Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user')


How to filter on taxonomy term in a view?

You need to create a relationship to your taxonomy vocabulary. Think of this like adding a join to a mySQL query.

For more info, take a look at Views relationship using taxonomy


Pre-populate default values into a form to edit a new entity

I think I found what the problem was. From the documentation and Drupal code it became clear that what I did in the form ought to be correct: field_attach_form should properly load all fields.

Which led to the fact that it must be the creation of the entity that is incorrect and not the actual form loading of the entity fields.

While examining the entity class I use, I came to the conclusion that the example code I used to build this entity wasn't complete. Upon first creating an instance of the entity, the code should not only save the entity data itself, but it should also call field_attach_insert. Just as it should call field_attach_update whenever the metadata entity exists already but is saved again (updated).

Upon adding this, the field_attach_form call now "magically" loaded the proper default values into the form.

Eureka.


Overriding File Entity fields when attached to a Node

There's no easy way to do this for files or images, which are essentially reference fields. There's no native way to do this for any type of reference field in Drupal. For example, you can create a reference field to a node, but override what the node's title is in a certain article when you reference it.

Typically what people recommend is using a Field Collection or a Multifield that consists of an image field + whatever field you want to have as the 'use this value only when this image is used here' stuff.

For captions, I know we added a caption filter specifically in Drupal 8 core, but I cannot find if it got back-ported for Drupal 7. That would be handy to have and use now.


How can I add a link to show/hide threaded comments?

You can do something like this:

In your theme's template.php file:

/**
 * Override or insert variables into the comment wrapper templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("comment" in this case.)
 */
function THEMENAME_preprocess_comment_wrapper(&$variables, $hook) {
  // Add jQuery UI accordian to hide the comments in.
  // It is already added in preprocess node but it is safer to also have it here
  // and doens't add much overhead as drupal will only add it once.
  drupal_add_library('system', 'ui.accordion');
  // Add some custom js to collapse comments.
  drupal_add_js(path_to_theme() . '/js/collapsi-comments.js');
}

In collapsi-comments.js (in this case it is in a folder called "js" in your theme.

(function($){
  Drupal.behaviors.collapsiComments = {
    attach: function(context, settings) {
      $('.comment-form-wrapper.accordion').accordion({
        collapsible: true,
        autoHeight: false,
        active: false,
        header: 'h2.title.comment-form'
      });
    }
  };
}(jQuery));

In your comment-wrapper.tpl.php in your theme wrap the comment form in a wrapper div like this (if your theme doesn't have one and you have a base theme that does, copy it from the base theme  and modify it, otherwise copy from the comment module and modify it):

<?php if ($comment_form): ?>

<?php print t('Add new comment'); ?>

    <?php print $comment_form; ?>

<?php endif; ?>


Webform validate 18 years old (GNU Date Input Format)

Here's the solution for this annoying "feature":


Conversion tracking code immediately after body tag?

You can do this in template.php by using theme_preprocess_html()

function mytheme_preprocess_html(&$vars) {
  $arg = arg();
  $vars['checkout_tracking_script'] = '';
  if (count($arg) == 3 && $arg[0] == 'checkout' && $arg[1] == 'complete' && is_numeric($arg[2])) {
    $vars['checkout_tracking_script'] = '<script>myScript</script>';
  }
}

Then in your html.tpl.php you can print your script like this.

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


Popup message showing content from a block

You should not be printing popup_message_show_message(); it just includes all the necessary files and show your message. Just remove the print part and try that way.

function popup_message_show_message($popup_message_parameters) {
  drupal_add_js(array(
      'popup_message' => $popup_message_parameters
    ), 'setting');
  drupal_add_js('misc/jquery.cookie.js');
  drupal_add_js(drupal_get_path('module', 'popup_message') . '/js/popup.js');
  $default_style = drupal_get_path('module', 'popup_message') . '/styles/default/' . POPUP_MESSAGE_CSS_NAME;
  $style = variable_get('popup_message_style', $default_style);
  if (!file_exists($style)) {
    $style = $default_style;
  }
  drupal_add_css($style);
}

Also, never use print_r() directly. Either use this:

drupal_set_message('<pre>' . print_r($variable, TRUE) . '</pre>');

Or install Devel module and call the dpm() function this way: dpm($variable). It will use Krumo to display all attributes / elements, which is times better for debugging and will not cause any errors as print_r().


Add content type to a taxonomy - Drupal 7

if I understand it right, you're trying to reference a "contact"-node...

You can use the module "entity reference" (https://www.drupal.org/project/entityreference) for that.


How can I remove the default value _none in a select list?

First unset the value like below.

unset($form['field_registration_type']['widget']['#options']['_none']);

Then set your drop down value to null, like below.

$form['field_registration_type']['widget']['#options'] = ['' => 'Select'] + $form['field_registration_type']['widget']['#options'];

Now your drop down value is null and your validation will work as expected.


Basic Auth working but simple auth not working for create user

I resolved my problem by giving user creation permission to anonymous user.
"Access POST on User registration resource"


Composer doesn't see that updates are needed

Update:  This is not a good answer.  Leaving it here for reference, but this does not solve the underlying problem, whatever it is.

Fixed by deleting vendor and core directories and composer.lock and then running...

composer update drupal/core --with-dependencies

It seems there must be some circumstances when the 'composer outdated' command doesn't work, but it's still possible to upgrade.


Hide fields in Paragraphs conditionally using Form API #states

I had to do something similar for having localized paragraphs for foreign languages with an option to hide the paragraph (until release date).

The paragraph types I needed this I added a "Display Languages" checkboxes field with the options of All, supported languages, Hide.  For example, you could create a paragraph and tick the DE option and the Hide option. This paragraph was hidden until the Hide tick mark was removed and then it only showed when the language was DE.

Here's an example of the code I used for my announcement_banner paragraph type.  If you need it for more types, just implement the hook code for that type.

/**
 * Implements hook_preprocess_paragraph__announcement_banner().
 *
 * Handles language display for paragraph type.
 *
 * @param array $variables
 */
function MY_MODULE_preprocess_paragraph__announcement_banner(&$variables) {
  $paragraph = $variables['paragraph'];
  if (!MY_MODULE_can_display($paragraph)) {
    $variables['attributes']['style'][] = 'display: none;';
    $variables['content'] = [];
  }
}
/**
 * Checks if a paragraph can be displayed for the current language.
 *
 * @param stdClass $paragraph
 *   The paragraph entity to be tested.
 * @return boolean
 *   True if it can be displayed / False if it can't
 */
function MY_MODULE_can_display( $paragraph ) {
  // Transition check remove once new corporate branding active.
  if (!isset($paragraph->field_display_languages)  || $paragraph->field_display_languages->count() == 0) {
    return TRUE;
  }
  $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $hide = FALSE;
  $allowed = FALSE;
  foreach ($paragraph->field_display_languages as $value ) {
    $langCode = $value->getValue()['value'];
    if ( $langCode == 'hide' ) {
      $hide = TRUE;
    }
    if ( $langCode == 'all'  || $langCode == $lang ) {
      $allowed = TRUE;
    }
  }
  // Hide if hidden option checked.
  if ($hide) {
    return FALSE;
  }
  // Show if nothing is checked or match found.
  return $allowed;
}


Why can't I update my Drupal modules and themes?

1) try to run the updates via drush

2)are you sure that the new module version has a new hook_update_N in it? If not then there will be nothing happening during the update in GUI


Why is the content of existing blocks not editable?

I suspect that the blocks that are doing this are made via hook_block and not with the block UI (ie, admin/build/block/add).  I just checked a Drupal 6 site that I did a while ago, and all of my custom blocks have this behavior.

The Configure link for each custom block should contain the module name that defined it, along with the delta.  For example the "Who's online" block has this for the configure link:

  admin/build/block/configure/user/3

It is defined in user.module and if you look at user_block you will see that the $delta for this is 3.


"contact" SQL table: what is it for and where do I edit it?

Go to admin/structure/contact/edit/1 and change Recipients email address to whatever you want.


Adding token in the views header and footer

The "Use replacement tokens from the first row" checkbox is essential. It works with either the "Global: Text Area" option or "Global: Unfiltered text." Here is a screenshot of both working:


Where is the site running? You mention you can download the file in your browser, but I wonder if the network from the site to google is different than the network from your computer to google.

What's in the error log in general? When the page goes blank like that it usually means some kind of severe error happened and that should show up in the Administer -> Reports -> Recent log entries page for the database log. Or it might show in the php or apache error logs. The location of those logs depends on your system.

How are you running cron? Depending on how you run it you might see different errors. If you have drush maybe try running cron via drush cron.


How to let users mark ( like) other users?

You can use Flag module. It does have integration with Views module. So you can configure and customize.

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.

  Flags may be per-user, meaning that each user can mark an item
  individually, or global, meaning that the item is either marked or it
  is not marked, and any user who changes that changes it for everyone.

  In this way, additional flags (similar to published and sticky) can be
  put on nodes, or other items, and dealt with by the system however the
  administration likes.


How to use hook_form_alter to target a specific drupal commerce form?

To add or alter the pane forms on the checkout page, for maximum compatibility, you should use the Commerce API.

Define new panes in:

hook_commerce_checkout_pane_info

Alter existing panes:

hook_commerce_checkout_pane_info_alter

For example, you could alter the checkout_form callback for a checkout pane to add your customizations.

  checkout_form($form, &$form_state, $checkout_pane, $order): returns form elements for the pane’s checkout form fieldset

You could also add your own custom checkout pane for your custom design there.

You can refer to the existing pane callback to first include or replicate the checkout pane.

Note: I posted a similar answer for adding a custom validate handler to a checkout pane a while ago here: https://drupal.stackexchange.com/a/87061/7153


permissions to allow role to edit the posted date

Updated date is set automatically by the system, if you want to edit that you will need to write some custom code.  Your user should be able to see the 'authored date' though.

Alternatively, if you need a date field that the user can edit (say, a publication date), just create a date field on your content and render it appropriately.

[edit based on additional info]:

I went digging in the code and found this in node.pages.inc:

$form['author'] = array(
  '#type' => 'fieldset',
  '#access' => user_access('administer nodes'),
  '#title' => t('Authoring information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'additional_settings',
  '#attributes' => array(
    'class' => array('node-form-author'),
  ),
  '#attached' => array(
    'js' => array(
      drupal_get_path('module', 'node') . '/node.js',
      array(
        'type' => 'setting',
        'data' => array('anonymous' => variable_get('anonymous', t('Anonymous'))),
      ),
    ),
  ),
  '#weight' => 90,
);

As you can see, access is tied to the 'administer nodes' permission which I'm guessing you haven't, and probably don't want to give to that role.

Luckily this is quite easy to change using hook_form_BASE_FORM_ID_alter(&$form, &$form_state, $form_id), here's the API for that function.

Create a custom module and put this in it:

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

    // You may wish to add some logic here to test for a specific role

    $form['author']['#access'] = TRUE;

    // Otherwise this will simply give everyone who can create nodes the
    // ability to change author and date.

}


Drupal 7.53 pathauto pattern field do not transliterate

I have tested several times and looked all over the internet, in one test I was able to reproduce the problem in dev environment. The problem was that the filed name contained the keyword "url", the problem persisted with the word "path", once I changed the field machine name to field_caminho everything worked fine.


Main Menu link to all newsletters and another for Articles

How much I understand go to structure > menu > main menu and click "add link" for Drupal 7 and structure > menu > main navigation for Drupal 8

 and for this, you need to create two views one is for newsletter content type and second is for article content type. You can make the view by going to structure > views > add new view for both Drupal 7 and 8. The view type must be page not block.

All the pictures are for Drupal 8. If you need more assistance please let me know.


Views: Output field as a link with URL provided by another field?

You can use replacement tokens. URL field first in the list, hide the field, rewrite the image to render with a link, use the replacement token for the URL field as the link.

Example: https://www.youtube.com/watch?v=fuNkaGOwnR0


Why is the old version of the module being used?

When this has happened to me, it's because I have had the module in two locations and forgotten about it. Just search for the module's info file (using for example find - on Linux):

find /path/to/drupal_root -name mymodule.info


Create two views this the same url and different permissions

Make the views as blocks and configure each one to display according to the permissions you're interested in, then place all blocks on a single page and link to it. The system will try to load all blocks, but will not show the ones the user doesn't have access to.

One caveat is a privileged user (such as admin) seeing their AND "lower permission" views, but that can be worked around, too.


You should use the hook_node_access in your custom module.

For Example -

/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account) {

  if ($op == "delete") {
    // If no user object is supplied, the access check is for the current user.
    if (empty($account)) {
      $account = $GLOBALS['user'];
    }
    // You can add your own condition check here...
    return user_access("delete content", $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;
  }

  return NODE_ACCESS_IGNORE;

}


For configuration, like an API server URL, I'd suggest using Drupal variables. There are several ways to set the variable:

In the settings.php:

$conf['api_server'] = 'http://example.com';

With Drush:

drush vset api_server 'http://example.com'

Build an admin screen where you can set the value. (Probably overkill in this case.)

In your code where you need the URL, use variable_get():

$url = variable_get('api_server');

To access the value in JavaScript see: How to pass PHP variables to Javascript/jQuery?


Include theme stylesheets after base theme stylesheets

In Tao's issue queue you will find more info. See Issue #1013440: TAO stylesheet loads last and overrides sub theme styles..

In the readme file:

  Tao does not use the all key for any of its stylesheets and expects
  that you will not either. Be specific - if the stylesheet is for the
  screen, or for print, say so. Any stylesheet overrides your subtheme
  provides should use the same media key as the one in tao.info for
  the stylesheet that is being overridden.


use Drupal\node\Entity\Node;

function custom_autofill_reference_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id =='node_monitoring_report_form'){
    $field_school_information =  \Drupal::request()->query->get('field_school_information');
    $node_details = \Drupal\node\Entity\Node::load($field_school_information);
    $form['field_school_information']['widget'][0]['target_id']['#default_value'] = $node_details;
  }

}

Above code worked finally and it was showing error as I did not clear the cache while trying to check it out.


Set up two exposed filters (exposed filters show on the view itself, with the user able to set their own value) one for the min_size field and another for the max_size field.

When setting up the exposed filters you'll have a choice "expose operator." With that choice you can allow the user to choose the operator (e.g. less than, greater than, greater than or equal to, etc.). The end user can use either of the exposed filters or both.

You'll need to be pay attention to your label choices and the help text you create to make sure what you come up with is easy to use and returns the expected results.


After publish node send email to someone

Why not just use Rules to do this. You'll have to watch a few tutorials to wrap your head around rules, but you won't have to re-invent the wheel or maintain any code.

If you need the custom module solution, check these out.

Check if node is being published:
How can I detect when a node is changed from 'Published' to 'Unpublished'?

Then, use drupal_mail() to send your emails.


How to set the default language in code?

A profile install hook that enables and sets Swedish.

/**
 * Implements hook_install().
 */
function hook_install() {
  // Enable swedish.
  locale_add_language('sv');
  $languages = language_list();
  variable_set('language_default', $languages['sv']);
}

Since language_default is a variable, it could also be Strongarm managed.


How do I load an external class into the Controller?

Drupal 8 uses a autoloader standard called PSR-4: http://www.php-fig.org/psr/psr-4/

Practically means your namespaces should result in the following directory structure

first
  - src
  --- FirstClass.php
  --- Controller
  ----- DefaultController.php
  - first.info.yml


Remove authentication in custom REST API resource

REST module plugins must have an authentication plugin. Try using the cookie plugin, which is the default one that core uses.


How to build select lists for search_api views

In this case I would create a Facet. You'll need to enable Search Facets (shipped with Search API) and Facet API.

Once you have that in place go to Configuration -> Search and metadata -> Search API and click edit on your Search index. In the dropdown there is a new choice called Facets now.

Enable the facet for you field Project Countries. That field also needs to be indexed under your fields settings for your search index. Facet API will provide a block for you with the Facet that you need to place on your search page.

Facets work in a way that they only show options available in your search result. If "Sweden" is not present in the field Project Countries in any of the nodes you have indexed it will neither be available in the Facet. So facets work in a way that they narrow down search results and usually doesn't show options that will result in an empty search. That's the biggest difference I see between a facet and a normal filter in Views.

Facets are normally displayed as checkboxes or links (see display settings for your Facet). You mentioned in your question that you have it now in the View as a dropdown. You you want to keep it as a dropdown instead of checkboxes / links you could checkout Facetapi select


Join a user field to a profile2 field in a view

If you have to the display profile fields using the Views module, then follow these steps:

Add "User:profile" under "RELATIONSHIPS".
Select "Profile types" in which type you have your fields to be display (teacher name, teacher date), as you may have more than one profile types.
You can add the selected profile fields under "Fields".


How to add a field to be displayed alongside the title?

Your question may lead to different opinion-based answers. Some might say: Display Suite. Others might say: do it in templates. And you could also: hide this certain field to then preprocess it back as suffix of the title (hook_preprocess_page_title).

All of them are no ideal solutions, IMHO. Display Suite is too heavy. Templates get too fiddly too fast (and I don't like how they can make the Field UI needless). Same for the preprocess function. Although if I would be forced to choose one of the named options I'd rather take the preprocess approach.

What I'd recommend instead is to solve your problem the other way around: Make the title a field, a pseudo field to be precise, that can be placed like any other field in the "Manage display" settings of any content type. Then you simply can drag this title field next to your other field and style them with some basic CSS to be displayed inline.

If you are interested in making the title a pseudo field to solve your problem just implement the code snippets I documented in my other answer on that topic: https://drupal.stackexchange.com/a/263740/15055

Still, if doing it that way you need to edit node.html.twig to remove the default (hard-coded) title output from it, to prevent getting printed twice when viewing this node not as page. Your node title now will be printed like any other field. And of course you also may need to prevent the title block from being printed on your node pages. This can be done per content type in the block settings if I remember it right.


How do you modify modules/templates without waiting for the cache?

This most likely is a server-side-cache related issue. I have also experienced this with my hosting. Try contacting your hosting provider about this issue or try to find a setting to turn off the server cache in your hosting's admin panel.


How to show a menu link that is hidden because the role has no permission to see the linked page?

In your case you can use two menu entries in the same menu:

One pointing to /node/add/article.
Another one pointing to /user/login.

First link is only visible to registered users, because anonymous users don't have permissions to add articles.

Second link is only visible to anonymous users because registered users don't have permissions to see the user login page (because they are already logged in).

The result is a menu with only one menu entry. Registered users see first link, anonymous see only second one.


Is there a function for drupal that can identity if a certain page and its children are being viewed?

You could use Menu Trail By Path module.

  Menu Trail By Path sets the active-trail on menu items according to
  the current url.

For example if you are at yoursite.com/blog/category1/article1
Menu Items with these paths will get the active-trail class on them and expand accordingly.


I was able to get to the bottom of this problem.  When I ran drush in debug mode, for example "drush status --debug" it outputted an error that it could not connect to the database.

After hours of digging for some reason on this particular cPanel server there were .my.cnf files in each user's home directory which contained mysql authentication details.  Drush was taking precedence on these credentials and in turn not able to connect to the particular Drupal install's database.  I simply did "rm -rf /home/username/.my.cnf to delete each of these hidden files, then running drush works!


drush sqlc import causing Mysql 1045 (28000) Error Acces. How to resolve it?

To reduce the possibility that the size of your database is what is causing your problem, I would try to use the Backup and Migrate module.

In doing so, you can exclude all sorts of tables (which might reduce the size tremendously), similar to what I described in my answer to the question about "How to get an import of a very large Drupal database working?".

PS: my answer to your 2nd question (= Should I update the live site to 7.41 before migrating it?) is No, because you should not have to update a live site to create a development environment. If you have a need for them to be at the same level (to start from), then rather do the opposite: have your local site start from 7.39, then sync your database, and if needed (only) then upgrade your local site to 7.41. You'd get the same result, without touching your live site, right?


Create Nodes for multiple languages in webform?

I think maybe your problem is because mistake configuration of translation

Enable translation support for a content type

Navigate to the Content types administration page (Administration >
Content > Types in Drupal 6, or Administration > Structure > Content
types in Drupal 7).
Select a content type you want translated, and select "edit", then "Workflow settings" for Drupal 6 or "Publishing options" for
Drupal 7.
At the "Multilingual support" section, select "Enabled, with translation".
   Be sure to save each content type after enabling multilingual support.


Passing a node variable into views filtering

Yes, this is possible.  You are wanting a context filter.

More details about your situation will let me give a better answer.


Add html to taxonomy_menu_block taxonomy terms

Looking at this module it does not employ a theme template file so overriding with your own template file is not a possibility; therefore, you will need to use Drupals theming later and processing hooks in your theme to alter the HTML output of the module without hacking the module. A start would be to look at hook_block_view_alter


How to override the core function format_xml_elements()?

You cannot directly make Drupal use a different function instead of format_xml_elements(), but you can replace those functions that (directly or not) calls format_xml_elements().
For example, to alter how the RSS page for a feed is printed, you just need to replace theme_aggregator_page_rss() with a function implemented from your module using hook_theme_registry_alter(); to alter the output for the 'blog/%user/feed, or the blog/feed, or the taxonomy/term/%taxonomy_term/feed, you implement hook_menu_alter() to replace the page callback Drupal uses with your own page callback.

What changes is the code you need to write in each case.
For example, taxonomy_term_feed(), the page callback for taxonomy/term/%taxonomy_term/feed, calls node_feed(), which calls format_rss_item(), which calls format_xml_elements(). In this case, you can use the same code taxonomy_term_feed() uses, except it calls another function (e.g. mymodule_node_fee()) instead of node_feed(), which has the same code, except it doesn't call format_rss_item() nor format_rss_channel(), but your own functions. For the latter two functions, you can use the same code they use, except your code will code your replacement for format_xml_elements() instead of format_xml_elements().

In the case of replacing theme_aggregator_page_rss(), you write less code.


Pass query parameters through local response

Receive the query parameters through the request you've added as parameter to the controller and pass them via the URL of the redirect.
Caching is a bit tricky because generating an absolute local URL bubbles up cacheable metadata which you need to collect by Url::toString(TRUE):
public function view(Request $request) {

  $url = Url::fromRoute(
    '<front>',
    [],
    [
      'query' => $request->query->all(),
      'absolute' => TRUE,
    ]
  )->toString(TRUE);

  $redirect = new LocalRedirectResponse($url->getGeneratedUrl());
  $redirect->addCacheableDependency($url);
  $redirect->getCacheableMetadata()->addCacheContexts(['url.query_args']);

  return $redirect;
}


I would suggest you use the views template for your view (views-view--page-intro.html.twig, and put the wrapping markup in there, rather than in the page template.

{% if rows %}

                    {{ rows }}

  {% endif %}

turn on twig debugging to see the template suggestions in your page markup.  this will be the default.services.yml file in your config directory where you have settings.php

 twig.config:
    debug: true


How to hook into "visiting the website"?

Using Rules Event "Drupal is initializing" (within "System") for sure will do the job:

It doesn't depend on login (can be used for any role).
It applies to any path (a node, a view, etc).

Should you want to do so, you can also add any desired Rules Conditions (eg to only consider selected paths, eventually using RegEx expression also).

Make it right before you make it better

I'm not sure this is the only way your question can be answered, but I do know that this Rules Event (Drupal is initializing) will do what you're asking for, which is to hook into "visiting the website" (i.e. visiting any page) (as in your question).

But, using this Rules Event also comes with a price: it will case this rule to be triggered on every page request (which is a pretty similar to your visiting any page). However, if this price is too high, maybe you want to consider any (or all?) of these compromises:

Add Rules Conditions such as "only for users with selected roles" (eg: authenticated, so that for Anonymous users the Rules Actions are not triggered).
Instead of any page, you only take into consideration something like "viewing content" (for which you know there are less expensive Rules Events available).


Why this specific string is untranslatable

There are two different aspects. The first one is how Drupal compiles the core translation list. This is based on the (not running) PHP code using the Translation template extractor (POTX).

You find only the first of the four messages on localize.drupal.org because of a naming issue in this particular constraint. Drupal searches for translation strings in certain locations and $messageParent doesn't match:

/**
 * Detect validation constraint messages. Drupal 8+.
 *
 * This sequences is searched for:
 *   T_POTX_CONSTRAINT = T_CONSTANT_ENCAPSED_STRING.
 *
 * note: T_POTX_CONSTRAINT is marked for T_VARIABLE tokens inside .php files
 *   with the "Constraint" suffix, where the token is "$message", or ends
 *   with "Message"
 *
 * @param string $file_name
 *   Name of file parsed.
 * @param string $save_callback
 *   Callback function used to save strings.
 */
function _potx_find_constraint_messages($file_name, $save_callback) {

See https://www.drupal.org/project/potx/issues/2884361#comment-13052396

The second aspect is about the run-time behavior. Symfony contraints are integrated into the Drupal translation system, so that messages are wrapped in a Drupal translatable markup object.

So a quick fix would be to visit the site in a non english language and trigger the error, then the string will be added to the translation list of your local site.


That setting is part of the theme settings variable; each setting is put in an array and that array is serialised as the value of the main theme settings variable.

You can set this value programmatically like so:

$theme_name = 'garland';
$var_name = 'theme_' . $theme_name . '_settings';

$settings = variable_get($var_name, array());

$settings['logo_path'] = $new_path;

variable_set($var_name, $settings);


Copy data of Email in registration to the username not showing in the registration page

The Email Registration module will allow for using the email address as the username.

The LoginToboggan module will allow the user to create a username, and allow them to login with either the username OR email address.

Email Registration also provides a hook which will allow a custom module to set the account name to whatever you want it to be.  That does require writing a module, however, it doesn't have to be very complicated.

The only thing you would need to include in your module file is the hook.
Example adapted from http://www.grasmash.com/article/using-your-email-address-your-drupal-username#sthash.uZkOo6j6.dpuf

<?php
/*
* Implements hook_email_registration_name().
*/
function grasmash_email_registration_name($edit, $account) {
  return $account->mail;
}


You don't actually "Delete" the extra values, you can simply leave the extra boxes empty and they will be ignored when you save the content.


Yes, you can do that with a variant. I've used that methodology on a personal project. Here are screenshots of the configuration.

The first variant (which returns a 404) checks, the node type (I have a content type called 'person'), the taxonomy terms applied to the node, and the role of the user.


How to check for product taxonomy term in Rules actions (Ubercart)

Have a look at this, rather basic, rule (in Rules export format):

{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_tags" } },
      { "list_contains" : { "list" : [ "node:field-tags" ], "item" : "21" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_tags] just got created or updated." } }
    ]
  }
}

Here is what this rule does:

Rules Event: After saving new content, After updating existing content
Rules Conditions:

Entity has field "field_tags", which is the machine name of the term reference field I want to check for.
List contains item "node:field-tags" and with Taxonomy term identifier value "21" (which is the term id of the term I want to check in this Rules Condition).

Rules Action: Show a message on the site (which is "A node containing the tag [node:field_tags] just got created or updated." (with [node:field_tags] the actual term with term id = 21).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions.

Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

Replace the Rules Event with an event that matches your "when customer makes a purchase of a product".
Within the Rules Conditions, perform these changes:

replace the "node" entity with your entity.
replace the machine name of term reference "field_tags", and adapt the "term id" to fit your case.

Replace the Rules Action by "send an appropriate eMail".


How to check that an attribute not exists in an element with PHPUnit?

You can check if there is a matching element for #edit-pass which has the attribute. Because #edit-pass targets only one element this has the same result when you know that this element exists:

$this->assertSession()->elementNotExists('css', '#edit-pass[autocomplete]');


How to put a site in maintenance mode by non-admin

There is a module for that!

Maintenance Mode Permissions

  Placing a site in or removing it from maintenance mode is allowed
  under a permission that has wide spread administrative access
  (administer site configuration). Sometimes you'd like to give
  permission to put the site in maintenance mode to someone but not give
  them complete access. This modules enables this case.


How do I display an entire node content on the front page?

The easiest way is to create a view.

Follow these steps:

Download, extract the Views module
Enable the Views UI module and accept enable the modules that provide the dependencies
Go to the views admin page (admin/structure/views)
Enable the frontpage view (click the link)
Edit the frontpage view (click the link)
Under the format heading, there is an option "show" click the teaser link
Change the view mode option to full and untick the show links checkbox
Click the Apply (all displays) button
Click the save button
Visit the site information page (admin/config/system/site-information)
Change the default front page URL to "frontpage" (without the quotes)
Click Save configuration

It show now just work.


set default timezone, date first day and date format medium via drush

There is no specific command to set default value. You need to set those variables using drushcommands.

For Drupal 7 version you can use below commands.

To set default timezone you can use

drush vset date_default_timezone 'Europe/London' -y

To set date first day you can use

drush vset date_first_day 1 -y

I hope this helps..  :)


hook_mail is supposed to take message by reference. The way you do it, you are modifying a local copy, and your modifications cannot ever leave the function's body. It should look like this:

function MYMODULE_mail($key, &$message, $params){
    switch ($key){
        case 'some_mail_key':
            $message['subject'] = 'test subject';
            $message['body'] = 'test body message';
            break;
    }
}

This little ampersand is what makes all the difference. You cannot omit them. If API defined hook with reference argument, keep it a reference argument, or expect problems.


Accessing Leaflet maps from custom module

I managed to solve the problem in the following way, I hope it save someone time:

(function($) {

var lMap = Drupal.settings.leaflet[0].lMap;

    Drupal.behaviors.test_module = {
        attach: function (context, settings) {
            latlon = settings.test_module.marker;
            //alert(latlon);
            lMap.setView(latlon, 14);
        }
    };

})(jQuery);


How to create a suggested content view using Flag and Flag Terms modules?

I just tried it out. I need to add it to my site too and the 50 points bounty was enough incentive to move it up on my list ;-)

After installing flag and flag_terms you create a new flag and select "Taxonomy terms" as the "Flag Type". Configure the text options, select a vocabulary (or many),  permissions and select the "Display link on taxonomy term pages" checkbox.

Then view a few terms on the standard term page and flag them using the new link.

Then create your view for content from your selected "vocabulary". The trick is that you have to add the "Content: Taxonomy terms on node" relationship first. Only then can you add the "(term) Flags: termflag (by current user)" relationship and select your "term flag" you entered previously. If you "require this relationship" it will only show you nodes where the term has been flagged.


title_callback not working for certain user in hook_menu

I get it !

In my configuration, the path intranet/hr is a view which is not accessible to every user, that's why the children element is not accessible and I have "Home" as the menu title.

Even if I don't know how to change this behaviour, at least I know why it is happening :-)


Escaping special characters in custom submit handler redirect URL?

If you use an array as the value for $form_state['redirect'], it will eventually be passed to url(). So you can use the same options as for that function to build up a structured query string:

$path = 'node/' . $nid . '/edit';
$query = array('step' => 'step_2');
$form_state['redirect'] = array($path, array('query' => $query));

There's more explanation in the documentation for the drupal_redirect_form() function.


Save and Retrieve Admin Settings from the database

I don't know how system_settings_form will handle form elements of which the parent element has the tree property set. So it is best to go with a submit handler and do it yourself.

function read_more_news_admin_form($form, &$form_state) {
  $form = array();
  $form['link_container'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('some-class')),
    '#tree' => TRUE,
  );
  $form['link_container']['link'] = array(
    '#type' => 'link_field',
    '#field_name' => 'link_field',
    '#language' => 'und',
    '#field_parents' => array(),
    '#delta' => 0,
    '#default_value' => array(
      'title' => variable_get('link_title', ''),
      'url' => variable_get('link_url', ''),
    ),
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
  return $form;
}

function read_more_news_admin_form_submit(&$form, &$form_state) {
  variable_set('link_title', $form_state['values']['link_container']['link']['title']);
  variable_set('link_url', $form_state['values']['link_container']['link']['url']);
  //drupal_write_record('readmorelink', $form_state['values']);
}


The answer to this was that the dev site was being redirected to the live site, where the "https" was then crossed out, but the domain name remains, confusingly, the same.


Provide a default image for image field programmatically at theme level

use hook_node_view_alter. Check over there that if images is empty then fetch image from your whatever custom directory and print it. For printing an image use theme_image.


How to use different fields for different content types in a view

Have you tried anything so far?

Try creating your view and select unformatted list as your style.
Add your fields as you would normally.
Under format, select settings and make sure that "Hide empty fields" is clicked.

If you fetch lets say the first five nodes from content types Images, Videos, Statuses then each row of the view should look like this:

==row 1==
John shared a new image: IMAGE
John is watching a video now: VIDEO
John is thinking "this day is sunny".

==row 2==
Jane shared a new image: IMAGE
Jane is watching a video now: VIDEO
Jane is thinking "this day is sunny".

==row 3==
...

but if row 1 is a result from the Video content type then the fields image and status should be empty and will be hidden since you clicked that format option before.
Try it and see if it works for you.


Global Variable with a dynamic value set by variable_get() in multisite

If you are running true multisite, then your sites are sharing the same code, but not the same database catalogs.

If you are in a situation where you only have access to a single database catalog, then you can use prefixes to keep all of your instances separate.

It is also possible to share tables in the same database catalog between multiple sites.  This is primarily meant for the {users} table, and cousins.  Sharing anything else, is likely a recipe for disaster.

So, to answer your question, the {variables} tables in a true multisite instance will be distinct unless you went out of your way to share them.

If you are using the Domain Access module to share some content between sites, then everything is really in the same database, and you will have a single {variables} table.

Now, you have the sample code

define('GLOBAL_VARIABLE', variable_get('myvar'));

This is not really a good idea; just use variable_get('myvar') wherever you need it.  If you have a lot of settings, then I would consider wrapping everything up in a singleton with a getter function that uses drupal_static().


How to use t() function for a text with anchor links?

You're absolutely correct; you should never concatenate strings with t(), the whole point is that it uses placeholders so you don't have to. Specifically:

// DO NOT DO THESE THINGS
$BAD_EXTERNAL_LINK = t('Look at Drupal documentation at !handbook.', array('!handbook' => ''. t('the Drupal Handbooks') .''));

$ANOTHER_BAD_EXTERNAL_LINK = t('Look at Drupal documentation at the Drupal Handbooks.');

$BAD_INTERNAL_LINK = t('To get an overview of your administration options, go to !administer in the main menu.', array('!administer' => l(t('the Administer screen'), 'admin'));

Instead of those you should use the following:

// Do this instead.
$external_link = t('Look at Drupal documentation at the Drupal Handbooks.', array('@drupal-handbook' => 'http://drupal.org/handbooks'));

$internal_link = t('To get an overview of your administration options, go to the Administer screen in the main menu.', array('@administer-page' => url('admin')));

See Dynamic or static links and HTML in translatable strings for full details.


Reference node inherits taxonomy terms of referenced node

First you would create a form alter function and make the taxonomy field as hidden and add ajax functionality to the node reference field. I am assuming that then node reference field widget is a select list.

For the following example I am assuming your fields are in the Basic Page. you can change the function name to suite your requirement by changing the mymodulename and page.

I am assuming the field name of the term reference field is field_vote and the node reference field is field_debate

function mymodulename_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  // We add the ajax functionality to the node reference field.
  $form['field_debate']['#ajax'] = array(
    // #ajax has two required keys: callback and wrapper.
    // 'callback' is a function that will be called when this element changes.
    'callback' => 'vote_field_return',
    // 'wrapper' is the HTML id of the page element that will be replaced.
    'wrapper' => 'replace_vote_div',
  );

  // Add a wrapper around the taxonomy field.
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  // Check the form state to see if the debate field is filled.
  if (!empty($form_state['values']['field_debate'])) {
    // Load the debate node.
    $debate = node_load($form_state['values']['field_debate']);

    $form['field_vote']['#type'] = 'select';

    // Assuming the taxonomy field in debate content type is field_vote_debate
    // Some times the language for the field might be different from the language of
    // the node itself in this case you might want to look at a dump of the $date
    // field and make the required changes.
    foreach($debate->field_vote_debate['$debate->language'] as $vote_term) {
      $form['field_vote']['#options'][$vote_term['taxonomy_term']->tid] = $vote_term['taxonomy_term']->name;
    }
  }
  else {
    // Hide the taxonomy field to start of with.
    $form['field_vote']['#type'] = 'hidden';
  }
}

The call back function is pretty straight forward we simply return the field_vote so that it can be rendered again in the form

function vote_field_return($form, $form_state) {
  // The form has already been submitted and updated. We can return the replaced
  // item as it is.
  return $form['field_vote'];
}

Note: As per the comment Please find below the updated code if the node ID is coming from url

I am assuming that the url to add the vote node is as follows

http://example.com/node/add/vote/23

where 23 is the node ID of the debate content type.

function mymodulename_form_vote_node_form_alter(&$form, &$form_state, $form_id) {
  // We use the arg() function to get the argument from the url. The numbering
  // starts from 0 and the one we need would be at 3.
  $debate = node_load(arg(3));

  // Assuming the taxonomy field in debate content type is field_vote_debate.
  // Some times the language for the field might be different from the language of
  // the node itself in this case you might want to look at a dump of the $date
  // field and make the required changes.

  foreach($debate->field_please_vote['$debate->language'] as $vote_term) {
    $term = taxonomy_term_load($vote_term['tid']);
    $form['field_vote']['und']['#options'][$vote_term['tid']] = $term->name;
  }
}


Views Long query execution time serious problem

There is no one line answer for you question as there are multiple things that can affect a query running slowly.

What you should do is enable slow query log in MySQL and try to debug from that point why your query is taking so long to execute. Things you can do are,

Tune your MYSQL.
Turn on slow query log.
Use the Explain command to find more info on how your query is executing, http://dev.mysql.com/doc/refman/5.7/en/using-explain.html.
Watch out if the tables are correctly indexed.
Last but not least, you can use hook_views_query_alter if you feel views is not creating the query optimally.


One time login redirect to password change page

hook_form_alter can be used to add a custom redirect rule. Do it in your custom module.

function MODULE_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'user_pass_reset'){
        $form_state['redirect'] = array('path/to/redirect', array('param' => 'val'));
    }
}


How to get newly created node ID after Feeds importing?

I found the solution. Use $entity NOT $entity_id in hook_feeds_after_save.


When you go to /admin/config/search/search-api and then click to edit your index, there is a checkbox for "Index items immediately" under the "Index Options" section. That is the only way I've found to get Solr Views to output new content immediately after it's created.


How do I customise the header and footer using a page template for a particular content type?

You can have page templates based on a content type, you just have to add some code so Drupal will recognise the template file: This link shows how to do this.

It depends on your Drupal version. You would think this would be default but for some reason, probably performance related, it is not.

For D7 add this to the template.php file in your theme directory.

<?php
function themeName_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    // If the content type's machine name is "my_machine_name" the file
    // name will be "page--my-machine-name.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}
?>

End now you can customize your footer header etc.


How to get the File Description on a custom field formatter?

That's right, normally you find the values from the field in $items[$delta].

To make this easier for field formatters getEntitiesToView() puts the item in the returned array. You find the item in _referringItem:

$item = $file->_referringItem;
$description =  $item->description;


I don't believe that is possible with filedepot without patching the module. However it is readily available within the IMCE module if you are able to change modules.  From the project page:

  Basic file operations: upload, delete
  Image(jpg, png, gif) operations: resize, create thumbnails, preview
  Support for private file system
  Configurable limits for user roles: file size per upload, directory
  quota, file extensions, and image dimensions
  Personal or shared folders for users
  Permissions per directory
  Ftp-like directory navigation
  File sorting by name, size, dimensions, date
  Tabbed interface for file operations
  Keyboard shortcuts(up, down, insert(or enter), delete, home, end,
  ctrl+A, R(esize), T(humbnails), U(pload)).
  Built-in support for inline image/file insertion into textareas
  Multiple file selection(using ctrl or shift)
  Ajax file operations
  Themable layout using tpl files

For a better idea of what you are looking at, take a look at a screenshot of filedepot.

Everything you need is already built in to IMCE.


Try creating a reference to the file.

Under Advanced in your View, and add a relationship (select File Usage: File).  If you now go to add a new field in your view, you should see a few more options under File, one of them being File: Size.


To change the content title (defaults to the username) you can use this snippet in a custom module:

<?php
function MYMODULE_custom_menu_alter(&$items) {
 $items['user/%user']['title callback'] = MYMODULE_user_page_title;
}

function MYMODULE_user_page_title() {

if(arg(0) == 'user') {
// Load uid from url
$user = user_load(arg(1));
// Load profile2 entity
$profile2 = profile2_load_by_user($user->uid);
// Load fields
$myfield = field_get_items('profile2', $profile2['main'], 'field_myfield');
$output = $myfield[0]['safe_value'];
}

// Fallback to username if no fields are present
if(empty($output)) {
   $output = $user->name;
 }

return $output;

}
?>

Reference : http://drupal.org/node/1262070, Change page title on user-profile using a field value from Profile2


It's the best to clone the module, rename it to let's say "custom_tracker" and there do the modifications you need.

As I did this few times with other modules, here are some tips:

Rename with "custom" prefix/suffix to avoid name clashes. Don't forget to rename all function and variable (I mean the stored ones) names as well as all the files (tracker.module => custom_tracker.module)
Test the module in local before using it on the live site.
As the module isn't too big, I suggest reading all code and do the renaming manually. It's better than simple replace as it might remove/screw wrong parts and also you can better understand the module.
If you would like to be able to improve the module later on, mark the changes/additions you made so later on if the module gets updated you can merge/add those improvements to your module as well.


Displaying top visited links from other content types in one (filtering)

If you want to use views check this answer.

There is Drupal Most Popular module

  Showcase the most popular content across your Drupal website and
  engage your audience.

Documentation

Also there is Radioactivity module.

  This module provides a field type which can be used as a hotness
  metric or a regular view counter for entities and for much much more.
  In essense, entities receiving attention (views or actions defined by
  Rules) are heated while inactive ones slowly cool down.


How do I parse application/vnd.surveymonkey.response.v1+json?

So the answer is to use hook_rest_server_request_parsers_alter(). This way, the application/vnd.surveymonkey.response.v1 Content-Type can be mapped to the standard JSON parser.

function MY_MODULE_rest_server_request_parsers_alter(&$parsers) {
  $parsers['application/vnd.surveymonkey.response.v1+json'] =  'ServicesParserJSON';
}


Assuming you're using Drupal 7.

Using hook_form_FORM_ID_alter and a custom module you can achieve it. Like below,

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['links'] = array(
    '#type' => 'item',
    '#markup' => l('some links','http://www.example.com'),
  );
  $form['additional_markup'] = array(
    '#type' => 'item',
    '#markup' => '

',
  );
}