Custom 'required' field message ignored for file uploads

The error message for managed_file fields is added by  ManagedFile::validateManagedFile - it does not support #required_error - the 'file missing' message (and others) are hardcoded:

  $form_state
      ->setError($element, t('@name field is required.', [
      '@name' => $element['#title'],
    ]));

This is presumably because of the multiple types of error possible:

file does not exist
file is "not referenced" (it exists but is "unmanaged" - i.e. orphaned as far as DB concerned - see function docs linked above)
or, in our case, a file has not been uploaded at all

Workaround:

I bypassed this by adding my own validation to the form.

The Webform module has hook_webform_submission_form_alter - you can use this to append your own validation method:

function mymodule_webform_submission_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ( $form['#webform_id'] != 'application' ) {
        // only do this for the specified form
        return;
    }

    $form['#validate'][] = 'mymodule_fix_webform_validation';
}

function mymodule_fix_webform_validation($form, &$form_state) {

    // grab all the existing errors
    $errors = $form_state->getErrors();

    if ( isset( $errors['cv'] ) &&
         $errors['cv']->getUntranslatedString() == '@name field is required.' ) {
         // if (a) there's an error for this field, and
         // (b) it's the correct TYPE of error

         // reconstruct the error message
         // (you might add translatable strings if you need them)
         $errors['cv']->__construct( 'Please upload a copy of your CV.' );
    }

}

(Decided to use the constructor from reading this answer to a similar question.)

Things I tried first:

The standard approach is to use $form_state->setError() or setErrorByName() - but neither appeared to have any effect on the error array - don't understand why.

On the actual form, the field was nested in a Webform "section"…

$form['elements']['uploads_section']['cv']

…so assumed I should supply the full array to setError(), for it to pull out the value of #parents and use that to construct the key.  Except the error is actually stored as a flat 'cv' key, without the parent.  Trying to set the 'cv' error using ByName didn't work either.

Overriding strings:

An alternative would be override the string (at time of writing, needs to be done programmatically: the string overrides module is not yet ready for D8). Add the following to settings.php:

$settings['locale_custom_strings_en'][''] = array(
    '@name field is required.' => 'Hello world!',
);

But this is a very broad brush and will apply to every file input on every form (plus anywhere else the phrase "@name field is required." is used - you can't specify the @name placeholder).


What happens if you replace:

requirements:
  _method: 'POST'
  _custom_access_check: 'TRUE'

With:

requirements:
  _method: 'POST'
  _permission: 'access content'

Any then remove your CustomAccessCheck code


How can I print a views exposed form into a custom block?

Hours and hours of searching and nothing was working.  Several minutes after posting this question, I figured it out.  The following code can be used in template files or blocks.

<?php
  $block = module_invoke('views', 'block_view', '-exp-VIEW_NAME-DISPLAY_NAME');
  print render($block['content']);
?>


how to block internal Drupal paths for anonymous users?

If you have clean URLs enabled, and are using the Global Redirect module, the users should never actually see the default paths (sometimes also called the internal path).

If a user goes to node/123 or taxonomy/term/456, and a path alias exist, then they will get an HTTP 301 and then redirect the the path alias.  Google and won't index the paths that 301.

In addition, Drupal will add a rel='canonical' to the header, to notify the world about the offical URL.

However, if you ever had you site without Global Redirect enabled, then you could at one point access pages from multiple paths.  Once Google starts seeing 301 responses for paths, it will eventually delist the page.  You can speed up the process by also disallowing the paths in your robots.txt and/or submitting page/directory removal requests.  Just remember to backup your robot.txt (or better yet put it in your VCS) because it will get nuked during core updates.


Popup module allow you to display the access denied page in popup box.

  The popup suite allows builders to popup tooltip-like text, nodes,
  blocks, menus, forms, views and php-generated content.

or

Better Messages intends to let you control where and how you want to see your Drupal messages! Combine different animations and override

  Enable or disable popup messages at specific pages.


adding data attribute to option value in Drupal 6

This has been asked previously for Drupal 7 and there is no great answer so it's unlikely to be possible in Drupal 6 the answer seems to be implementing a custom theme_select


If I am not mistaken, it seems you want to have something like "private comments" on a node. You can find some information in the following question: How to have separate private comments for nodes apart from the general comments?

It mentions the Reply module, which is still in alpha. There might be other similar modules.

Hope it helps,


I think you might want to read this: http://drupaleasy.com/blogs/ultimike/2009/03/event-registration-ubercart

It's a walk through of setting up an "event registration" system in Drupal - however, that is really just a web site that:

1) presents introduction information about a product or service
2) After a customer clicks "Add to cart", presents the customer with a form to complete of
   needed info for that product/service
3) if the customer's credit/debit transaction is successful, the customer's purchase is
   identified as "valid" and your web site does whatever you offered in the way of
   product/service for your customer.

This is achieved with Ubercart, Ubercart's Conditional Actions, and some minor tweaking fully explained in the link above.


How to get nodes by custom field value using EntityFieldQuery?

The correct code is the following one.

$entities = $nodeQuery->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->fieldCondition('field_archived','value', '1', '=')
  ->pager(10)
  ->execute();

Instead of 'field_archived_value' you need to use 'value'.


how to create a link field which validates to a set of nodes?

try the advanced link module:

Provides autocomplete widget for CCK Link field and additional
functionality over standard field:
Variants of URL filtering (external or internal).
Additional filter options by using URL patterns.
Autocomplete link field for internal mode - displays suggestions from existing url aliases and menu items
Option to allow users select url title from predefined list of values
Use cases
You want allow users specify link only to several sites (i.e. specify link only to facebook or twitter)
You want restrict users to specify only internal or external links
You want to use autocomplete suggestion when specifying internal links


The code is incorrect, it should be:

function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'register_node_form' || $form_id == 'session_node_form') {
    // code here that alters forms for both content types
  }
}

The if statement is missing the second $form_id.

Also, I wouldn't name the module custom. If you are doing that as a demonstration purpose, a typical convention is to use mymodule_ in posts.

A more readable way:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $content_type_forms = array('register_node_form', 'session_node_form');

  if (in_array($form_id, $content_type_forms)) {
    // code here that alters forms for certain content types
  }
}


How to send an email that always contains all fields of entityform, without manually updating when fields are changed?

This is already handled in the Entityforms Notifications sub-module the way you are describing.

There is a view mode called "Email".  That view mode controls which fields show up in the email. This is done via a token in Rules.

In Entityform 1.x this token is controlled via the Entityform module itself.  In Entityform 2.x this is controlled via the Entity to Text Module.

I think there is some problem in Entityform 1.x with showing fields with multiple values. But this should work in Entity To Text.  You could also just use Entity To Text with Entityform 1.x.  Just replace Entityform 1.x token with the Entity To Text token in the Rule.

If you are interested this handbook page should probably updated with this information: https://drupal.org/node/1679794


How do I theme a link with twig for a specific content type?

There are a number of things you would need to do to accomplish this.

Enable Twig debugging
Create a hook theme suggestions preprocess function
Get the node object within your theme hook.
Craft the theme hook suggestion to get a template name with the node type in it.

Once you have Twig debugging enabled, you can inspect your file link. As a default for file_link, I see:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'file_link' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/field/file-link.html.twig' -->

In my case, I use Classy as a base theme for my sub-theme, thus the classy path above. but what is missing here is any useful theme hook suggestions out of the box. Next we will remedy that.

Since we are given the theme hook name above, I can craft the theme hook suggestion based on that and by getting the node type and incorporating it into the theme hook suggestion. (see function hook_theme_suggestions_HOOK_alter)

My theme hook alter then would be:

  function MYTHEME_theme_suggestions_file_link_alter(&$suggestions, $vars, $hook) {

  // Get the node type.
  $node = \Drupal::routeMatch()->getParameter('node');
  $type = $node->getType();

  // Create the theme hook suggestion.
  $suggestions[] = 'file__link__' . 'type_' . $type;

}

Once I do this and drush cr, I will see my new theme hook template suggestion as such:

<!-- THEME DEBUG -->
    <!-- THEME HOOK: 'file_link' -->
<!-- FILE NAME SUGGESTIONS:
   * file--link--type-news.html.twig
   x file-link.html.twig
-->

In my case, my node type is "News" and you can see that in the template suggestion name:

file--link--type-news.html.twig

Now you can create that file and theme away! For more insight on this, I just wrote a blog post about this: Drupal 8 Theming Tutorial: How to Craft Custom Theme Hook Suggestions and Templates


Is the Drupal Multisite something automated once its setup?

I build a system for a client where the client would deploy sites for his clients.  It was pretty easy with the Aegir system.  Aegir is a drupal site that manages drupal sites and different module configurations as "platforms" for those sites.

Need to depoly security updates?  Make a new platform with the updated modules, and migrate the sites from the existing platform to the new one with the built in migration managment.

A manual multisite install is similar to this, where the /sites/all folder is your platform common to all the sites, and each one has a separate database.

The disadvantage is each site residing on aegir is its own site, with its own database.  If you want nodes or pages common to each site you have to hardcode them into the platform's installation profile.(or make them manually for each new site)  Also, the steps in your question would have to be done in the Aegir level and not in the drupal site.

With the domain module you have multiple sites using the same database, so you can more easily share nodes and content across them.  Also, since it is one site holding different pieces under different subdomains, the ability to add new subdomains is in the drupal menu on the site.

Disadvantage: what affects one site affects them all, since they are all different faces of the same site.  Also, I have had bad experiences with the domain module (especially in conjunction with the commerce modules) and trust it less than other solutions.  Since (sub)domains are content types made by users, it is possible to delete an entire domain and lose all its content when you delete the user account that made it.  I saw a guy get fired for doing that by mistake.


Display only the value of a field in a content-type template

I was able to print the value by using

{{ content.field_video[0] }}


How get Drupal Alias from given node NID inside a module function?

It looks like you are debugging through watch dog table, you should better use devel module it provides you several debugging options few are

dpm()
example in your case : dpm(drupal_get_normal_path('node/866'));
devel/php path
which allows you to test your php codes.
example in your case : simply log in as admin visit sitename/devel/php and execute  dpm(drupal_get_normal_path('node/866')); and see what it shows

About the problem

Make sure node/866 exists
If node exists make sure when you are able to access the node-866 by node/866 and alias which you have configured.
As as an option you can delete the existing alias and create the same alias again. And check again.


Drupal core provides the statistics module which does basically this. It just maintains a counter and not a record per visit, but that's the basic idea.

And it does that with JS that triggers a callback. The reason it does it like that is that nothing on the server side can reliably do this in many situations. You might have something like varnish in front of your site, then most requests will not even reach your webserver.


Drupal Twitter widget not showing tweets

You did not provide enough information. Which module? Which version of Drupal? If you're on Drupal 7 and you're using the Twitter module, you must carefully follow the documented installation procedure, documented here.


To be able to add your custom contextual link, you first need to check the Contextual links module is enabled. Even though you define everything correctly, it would not show, if it is disabled. Also, you need to set context to MENU_CONTEXT_INLINE in your menu items.

/**
 * Implements hook_block_view().
 */
function example_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_custom_block':
      $block['subject'] = t('Example Block');
      $block['content'] = array(
      '#markup' => _get_markup(),
      '#contextual_links' => array(
          'add content' => array('add', array('node')),
      ));
      break;
    default:
      break;
  }

  return $block;
}

/**
 * Implements hook_menu().
 */
function example_menu() {
    $items['add/%/content'] = array(
        'title' => 'Add Content',
        'type' => MENU_LOCAL_ACTION,
        'context' => MENU_CONTEXT_INLINE,
        'page callback' => 'contextual_node_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );

    // To use local task menu items, there must be a parent page.
    $items['add'] = array(
        'title' => 'Contextual Link Page',
        'page callback' => 'contextual_node_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );
    return $items;
}

Additional resources

https://www.drupal.org/docs/7/administering-drupal-7-site/working-with-contextual-links
http://dominiquedecooman.com/blog/drupal-7-tip-add-contextual-links-anything


How to programmatically print node from a specific author

With the  Views module I think you can add a filter on the user name.
I don't know if you are aware of this module, but for short you have to create a view with some settings like :

Row Style : Node (or fields but then you have to add some fields)
Filters : User-> Name (or ID)

To finish you have to add a display, for example "Page" and then edit the path. With this you can create a menu with the View Page.

See the documentation for more.

If it's not a good answer, can you explain more your problem ? (D6 or D7, how do you want to display the nodes...)

(Hope my english is not too bad)


The user account form stuff is one level up in the account container. For the name and email you can use:

$form['account']['name']['#attributes']['placeholder'] = t( 'Username' );
$form['account']['mail']['#attributes']['placeholder'] = t( 'Email Address' );

The password is slightly more complicated, as the 2 inputs are created in a process function. You'll need something like:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  ...
  if ($form_id == 'user_account_form') {
    ...
    $form['account']['pass']['#process'][] = 'MYMODULE_process_password_confirm';
  }
  ...
}

function MYMODULE_process_password_confirm($element) {
  $element['pass1']['#attributes']['placeholder'] = t( 'Password' );
  $element['pass2']['#attributes']['placeholder'] = t( 'Confirm Password' );
  return $element;
}

See form_process_password_confirm() if you're wondering where 'pass1' and 'pass2' come from (it's one of the default process functions for a password_confirm element as set in system_element_info()).

It'll be the same sort of thing for the slider, but without knowing where that slider comes from (module, custom code, etc) it's difficult to say what the code should be. At a guess based on the input name's you're trying to target:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  ...
  if ($form_id == 'views_exposed_form') {
    ...
    $form['commerce_price_amount']['#process'][] = 'MYMODULE_process_commerce_price_amount';
  }
  ...
}

function MYMODULE_process_commerce_price_amount($element) {
  $element['min']['#attributes']['placeholder'] = t( 'Min price' );
  $element['max']['#attributes']['placeholder'] = t( 'Max price' );
  return $element;
}


FYI it's a REALLY bad idea to hack core.  Firstly, God knows what could break, and secondly..whatever changes you make will likely be over-written if/when you update core.

To answer your question, you're calling the $custom_theme as you should, but then assigning a Garland to $theme, which isn't used.

Try the following:

function mytheme_init() {
  // Hardcode the administration theme onto the blocks page
  if ($_GET['q'] == 'admin/build/block') {
    global $custom_theme;
    $custom_theme = 'garland';
  }
}

In your custom theme's template.php instead of in block.admin.inc.  Make sure you change mytheme to whatever your custom theme's name is (e.g. my_custom_theme_init or custom_init).

You might also want to look at the Administration Theme module or the Themekey module for admin theme options/theme switching.

Themekey sounds like a pretty good bet for ease of use:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules.

EDIT

I forgot, the Admin module also comes with an admin theme option, and a pretty decent admin menu for end users (clients etc.).


How to disable specific message displayed by contrib/core?

Once a user has been deleted, The User relationships module have to delete all relationships associated to deleted user but it doesn't work correctly. I implemented hook_user_delete() in a custom module and delete non-approved relationships associated to the deleted user. like this:

/**
 * Implements hook_user_delete().
 */

function YOUR_MODULE_NAME_user_delete($account) {
  //user_relationships_delete_relationship($relationship, $user);
  db_delete('user_relationships')->condition('approved', 0 , '=')->condition(db_or()->condition('requester_id', $account->uid)->condition('requestee_id', $account->uid))->execute();
}


Those messages are shown as the result of enabling logging in the SMTP module. It's only set once from the smtp_debugging variable. If it's still logging after disabling it, you to debug the issue as there's no one cause (e.g. caching, forcing the setting in settings.php/settings.local.php, code base hack, etc.) and is out of scope of Q&A.

As for altering the "Further instructions have..." message, there are many ways to do this (e.g. form alter, translation files), but the simplest is probably utilizing the String Overrides module which will let you override any message wrapped in a t() function.


Get context of overlay (get parent page information)

Unfortunately the PHP that's rendering the child page knows nothing about the parent page over which it's going to be placed. You could write an AJAX callback that checks window.location and reports back to the server, but that would have to run after the page was fully rendered.


How to soley wrap the -field in a custom -wrapper in Webform 4.x?

Use hook_form_alter and add "'#title_display'    => 'none'," and use label in prefix. e.g.

if($form_id == "content_type_node_form"){
   $form['field_name']['#prefix'] = 'name
';
   $form['field_name']['#suffix'] = '
';
}

I have not tested it but this can work.


Automatic Node titles to generate a title based on taxonomy

I suppose that one of the simplest things to check would be that you're calling the correct taxonomy id at this step: array_values($node->taxonomy[1]). If the taxonomy id of the make and model vocabulary you created isn't 1, this won't work as you expected.

The Devel module is very helpful for this. If you have it installed, you can open the node in question, click on the "Devel" tab and scroll down until you find taxonomy. It'll list the ids currently in use on the node.

Another way, if you don't have or want Devel, is to go to your taxonomy listing at 'admin/content/taxonomy'. When you click on "list terms" for your make and model vocabulary its id will be displayed in the URL.

That is the id you want to have in your first line: array_values($node->taxonomy[1])

-------------[edit]---------------

As per your comment below, I would suggest using something like this:

$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid');

Where $node is the node object, $vid is the id of the vocabulary you want to limit the term search to.

Then you can loop through the terms using:

foreach($terms as $term) {
  print $term. " ";
}

------------[update]--------------

Use the standard PHP function implode to put in your spaces:

implode(" ", $terms);

The added space will put spaces between the terms in the array. This is, of course, assuming the terms will be returned in an order that makes sense for what you're doing.


How to disallow users from changing their emails?

You can either force users to confirm email change or protect the email field from changes.
Both modules have D6/7 versions. Second module can lock password and some other fields as well.


How to enable contextual links for views content panes?

For contextual links to show, you need to create a content pane in your view. +Add > Content Pane. There will be a new panels category automatically created called "View Panes".


Bilingual site - when adding translations to Organic Group, prevent creating a separate group/content node

Basically the answer is to use Entity Translation. See here https://www.drupal.org/node/371181


Display the title of related nodes from taxonomy in block

If I understand your question correctly, you can just use Views to accomplish this.

To display a block that lists other node titles with related taxonomy terms:

Create a Block View
Add the field Node:Title (make it link to its node)
Add the argument Taxonomy: Term ID
Configure this argument as follows:

  Check Provide default argument
  Select PHP Code
  Add the following code:

$node = node_load(arg(1));
  if($node) {
    if ($node->taxonomy) {
      foreach($node->taxonomy as $term) { $terms[] = $term->tid; }
      return implode('+',$terms);
    }
    else {
      return;
    }
  }
  else {
      return;
  }

  Check Allow multiple terms per argument
  Check Reduce duplicates

Now you need to add the second argument in order to exclude the current node from the list. Click [+] button of the arguments section.
Select Node:Nid
Set the "Action to take if argument is not present" to Provide default argument
Set the "Default argument type" to Node ID from URL
Check Exclude the argument
Save your view

You can customize this however you like, such as filtering to a specific content type (ie "News"), can filter by post date, sort by: post date, random, etc.

For a whole discussion on this see http://drupal.org/node/65375

(Sorry for the poor code formatting, not sure how to format code inside a blockquote and list)


Views Configure contextual filter by user's country

Found the problem!

All I did was correct, except one thing; I choose wrong View type during creation.

wrong: selected Show "Product display"

working: choose Show "Content" of type "Product display"

Don't know the difference, but it's working


How do I fetch the ID of the current entity?

I ended up using panels and used %node:ID context token.


How do I exclude a single menu item from the sitemap?

Maybe you want to consider the approach described in comment # 1 in issue # 985138 (for D7), which is like so:

/**
* Override site_map function
*/
function hide_in_sitemap_preprocess_site_map(&$variables) {
  $mids = variable_get('site_map_show_menus', array());
  $output = '';
  if ($mids) {
    foreach ($mids as $mid) {
      $menu = menu_load($mid);
      // Use menu_tree_all_data to retrieve the expanded tree.
      $tree = menu_tree_all_data($mid);
        foreach ($tree as $branch => $value) {
          if ($value["link"]["options"]["hide_in_sitemap"]) {
            unset($tree[$branch]);
        }
      }

      if (module_exists('i18nmenu')) {
        i18nmenu_localize_tree($tree);
      }
      $menu_display = _site_map_menu_tree_output($tree);
      $rendered = drupal_render($menu_display);

      if (!empty($menu_display)) {
        $title = $menu['title'];
          $vars = array( 'title' => $title,
                        'content' => $rendered);
        $output .= theme('site_map_box', $vars);
      }
    }
  }
  $variables["menus"] = $output;
}


Passing Timestamp in the SQL Query to filter results

I don't have a copy of D7 handy, but this seems to work on D6 for me. There's at least two problems with your code. I'm going to pare your query into a short bit of SQL, then transform it into drupal code.

Use JOINs

Whenever you're using multiple tables in SQL, you'll almost always have to use the JOIN ... ON ... syntax. Using JOIN tells MySQL that you want to connect certain rows on the two tables if a given field from those tables matches. This is a very basic SQL concept, so you'll need to master this if you want to write your own SQL or troubleshoot it. Try W3Schools tutorial for a better explanation.

Here's a simplified, pure SQL query that works for me using a JOIN:

SELECT
  n.title, n.nid, COUNT(*) as times
FROM
  node n
JOIN
  node_view_count a
ON
    a.nid = n.nid
GROUP BY
    n.title
ORDER BY times DESC;

In my D6 installation, I have a table called node_counter, but you probably have node_view_count instead on D7. JOIN node_view_count tells MySQl that we're connecting the node table to the node_view_count table. The ON a.nid = n.nid tells MySQL to only connect rows from these two tables when the nid field matches.

WHERE Clause

Next, let's add in a simplified WHERE clause. On my D6 database, the node_counter table's timestamp field is an unix timestamp (an integer). We can do the conversion from unix timestamp to datetime using pure SQL as well (no need to use a parameter to db_query()):

...
ON
    a.nid = n.nid
WHERE
    DATE(from_unixtime(a.timestamp)) = "2012-12-21"
GROUP BY
...

Add a Paramater to db_query()

We can change "2012-12-21" to whatever date we want to search on. So, next let's make this changeable part of our query into a parameter that gets passed to db_query():

<?php
$query = <<<SQL
SELECT
  n.title, n.nid, COUNT(*) as times
FROM
  {node} n
JOIN
  {node_view_count} a
ON
    a.nid = n.nid
WHERE
    DATE(from_unixtime(a.timestamp)) = :mydate
GROUP BY
    n.title
ORDER BY times DESC
SQL;

I've put { and } around the table names so that you use this query inside db_query(). By adding :mydate, you can now add in parameter called ':mydate' with a date string to your db_query() call:

$result = db_query($query, array(':mydate' => '2012-12-21'));

Hopefully, this gets you 90% of the way there.


Simplenews - how pass values from own input

function my_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'YOUR_FORM_ID') {
    $form['field_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['field_name_submit'] = array(
      '#type' => 'submit',
      '#value' => t('SAVE'),
      '#submit' => array('my_module_name_submit'),
    );
  return $form;
  }
}

function my_module_name_submit($form,&$form_state) {
  if ($form_state['values']['field_name']) {
    variable_set('Name', $form_state['values']['field_name']);
  }
}

variable_set stores textfield value in variable table. You can access/get this value using variable_get as mentioned below

  variable_get('Name')


Inserting html just before body of all pages (drupal 7)

You should be editing the template file with in the theme. By default stark does not have any template files. You should copy the required template file to the theme you are using and then edit the same there.


Redirect user from a custom access callback

For the second condition an access denied doesn't seem to be the right answer because permissions are not the reason. It is to control the business logic and for this I think it is a good idea to use buildForm(), which acts in a form route as a controller from which you can return a redirect response:

  public function buildForm(array $form, FormStateInterface $form_state) {
    if (...) {
      $this->messenger()->addMessage('Fee already paid or no fee to pay.');
      return $this->redirect('<front>');
    }

    // build form if fee is not paid already

  }


how to change the widget of view's exposed filter form?

i tested this kind of thing and found that when you try to switch a exposed widget field you need to provide an array with the empty first key, if it is checkboxes or radios; if new widget will be a select then you need to provide an array with the 'All' first key. E.g.:

//Suppose that you have a default input widget which you want to change to select widget.
//We will get the values which we want our new select widget will get as options:
$opts = array(
  'first_key' => 'First value',
  'sec_key' => 'Second value',
);

// Then we will add required 'All' first key:
$options = array('All' => 'Choose a value') + $opts;

// Then we will create our new select widget
$form['YOUR_FIELD_NAME'] = array(
     '#type' => 'select',
     '#title' => t('MY TITLE'),
     '#options' => $options,
   );


Setting up regex-style rewrite rules within Drupal?

Well if you are familiar with PHP and preg_match, you could theoretically install Drupal rules module and write custom rules using PHP to redirect pages inside Drupal without touching .htaccess file.


Error message - Trying to get property of non-object

You need to check what node_get_object() returns since it could not return an object. This is particularly true when the user is not watching a node page, but even in the case the viewed page is a node one, the function could not return an object. This is why Drupal code always check the returned value.

function book_page_alter(&$page) {
  if (($node = menu_get_object()) && !empty($node->book['bid'])) {
    $active_menus = menu_get_active_menu_names();
    $active_menus[] = $node->book['menu_name'];
    menu_set_active_menu_names($active_menus);
  }
}

// template_preprocess_page()
if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

// template_preprocess_html()
// If on an individual node page, add the node type to body classes.
if ($node = menu_get_object()) {
  $variables['classes_array'][] = drupal_html_class('node-type-' . $node->type);
}


Automatically block user that access /wp-login.php

You can use autoban ip
You have to at least enable Autoban and Autoban Core Ban Provider modules from this package.
Then go to configuration > people > automatic ip address bans
and add a rule with this settings

type page not found
Message pattern wp-login.php|/otherURL|anotherURL
pattern (can be left blank)
Threshold 1 (after how many attempts to ban them)
IP Ban Provider Core Ban

NOTE: above I have added multiple patterns delimited with | just to demonstrate the possibility
After setting this everytime your cron runs this module will run and it will look through the watchdog messages and ban the IPs that match the above rule.


Enable field inside Manage Display from a .yml file

There is a single config entity per entity_type, bundle and view/form mode. If you fully control that, then you can provide those config entities, if you just add a single field to something existing, you need to use the API to add your fields configuration to it.

See core.entity_form_display.node.article.default.yml in standard.profile and various others for examples.


Contextual Filters with multiple arguments

Okay- I figured out what was going on.  I'm going to answer my own question in case anyone runs into the same problem I had.

Previously I had specified some PHP Validation code to the Type and State filters.  Thinking they might be causing the problem I turned off the validation for both of them, but the problem persisted and that's why I posted my question above.  To solve this you need to overwrite the previous validation you set by setting it to something like Basic validation, thus clearing out the old code.  Now it works like it should but it seems like there is a bug in Views though that doesn't properly unset validation code.  Good luck!


HybridAuth hide additional information form for twitter

The reason it prompts for that information is the Twitter API doesn't provide it; you can't retrieve user emails through the API; it only provides a single field for a user's real name (thus the prompt for the last name); and it doesn't collect information on a user's gender.


Log profile 2 user info a separate log file

The profiles2 docs state:

Thanks to the foundational entity API the module integrates well with Rules as well as Features.

Install the rules module (http://drupal.org/project/rules) and you should be able to access the profile data after he user login event. To log to the system watchdog with rules you need this patch: http://drupal.org/node/1349882#comment-6190164

This does not write to a separate file, but it would be trivial to extract your entries from the watchdog db table using phpMyAdmin.

And finally it does not require any coding.


What's the correct way to pass variables to the JavaScript of a custom CKEditor plugin?

You can pass options via getConfig option of the class that creates the plugin. See how the module "Color Button" does it:

https://cgit.drupalcode.org/colorbutton/tree/src/Plugin/CKEditorPlugin/ColorButton.php?h=8.x-1.x

This is passed along to the defined plugin when it is loaded up (the one defined in getFile.)

See: https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginBase.php/class/CKEditorPluginBase/8.6.x

and:

https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginInterface.php/function/CKEditorPluginInterface%3A%3AgetConfig/8.6.x

The variable names passed or modified in getConfig need to be the same names as the ones in the plugin to be overwritten.


Try to use Add to Cal module. I hope this module solve your query.

  A field formatter providing a widget for exporting events to:

  Google Calendar
  Yahoo! Calendar
  iCal
  Outlook

  The field formatter provides a button next to the field that shows a drop-down menu. This
  menu contains links to the supported formats, and includes basic
  styling that can be easily modified through CSS.


Add headers to each grouped section in a view

You certainly can, if you use a Views relationship to load in those other Department nodes, add a field using that relationship showing the Department node body, set it to "exclude from display" (so it doesn't appear twice) and in Format: Settings set Grouping to use that specific field.

The key question then is - how does each Employee node know which is the Department node that corresponds to it? I'd suggest you use one of the node relationship/reference modules to link them together - I can vouch for relation which is good, powerful and (since a few months ago) works well with views. It isn't so easy to use and doesn't have a great interface yet, but learning to use it is time well spent, especially for the sort of site you seem to describe. If you think Relation is overkill (it is for many very simple sites), here's a guide which covers the many simpler alternatives.

With Relation, a step-by-step could be:

Create the relation type (say, "is in department" source>target, "has employee" target>source, valid source: employee, valid target: department)
Create a relation for each employee, linking it to its department
In the view, create a node-node Relation relationship using "is in department" from the 'source' endpoint
Add a content:body field, using this relationship. Set it to exclude from view
In View Format: Settings, choose this body field  to group the view


Here is how its done:

First create a new rule then,

**Events**
-User has logged in

**Condition**
-Data Value is empty

you have to enter the value u want to check, something like
site:current-user:field-skills
make sure to change field-skills to the field name you want to check.

**Actions**
-Show a message on the site
"enter the message you want"
-page redirect
"enter uri to redirect to"

here is an export of the rule:

{ "rules_check_required_fields" : {
"LABEL" : "Check required fields",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_login" ],
"IF" : [
  { "data_is_empty" : { "data" : [ "site:current-user:field-skills" ] } }
],
"DO" : [
  { "drupal_message" : { "message" : "Field skills is empty", "type" : "warning" } },
  { "redirect" : { "url" : "\u003Cfront\u003E" } }
]

}
}


Views Data Export Module not including the custom added rows in a view

Views Data Export does not render your results in a traditional way, so render hooks are not executed. But you should be able to alter results using hook_views_post_execute:

This hook is called right after the execute process. The query has been executed, but the pre_render() phase has not yet happened for handlers.
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.

Emphasis mine - that's what you should to to alter content not only for display purposes, but in generic, usage-independent way.


The Rule will react on event "After updating existing content of type Content1".

The Rule will have to utilize a component in order to reach the email field in Content3.

In short: Rule loops through Content1 reference field (may contain multiple references) and then component will process each referenced node of type Content2 and return a variable back to the Rule. Returned variable contains an email that is taken from the field of the node of type Content3.

STEP 1 - Create Rules Component (export below)

{ "rules_process_content2_return_email" : {
    "LABEL" : "Process Referenced Content2 Entity and Return Email",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "content2" : { "label" : "Content2", "type" : "node" },
      "email_address" : { "label" : "Email Address", "type" : "text", "parameter" : false }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "content2" ], "field" : "field_content_reference_2" } },
      { "entity_has_field" : {
          "entity" : [ "content2:field-content-reference-2" ],
          "field" : "field_email"
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : [ "content2:field-content-reference-2:field-email" ]
          },
          "PROVIDE" : { "variable_added" : { "email_address" : "Email Address" } }
        }
      },
      { "data_set" : {
          "data" : [ "email-address" ],
          "value" : [ "content2:field-content-reference-2:field-email" ]
        }
      }
    ],
    "PROVIDES VARIABLES" : [ "email_address" ]
  }
}

STEP 2 - Create the Rule that uses Component above (export below)

{ "rules_send_email" : {
    "LABEL" : "Send Email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update--content1" : { "bundle" : "content1" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-content-reference" ] },
          "ITEM" : { "content2_item" : "Content2 item" },
          "DO" : [
            { "component_rules_process_content2_return_email" : {
                "USING" : { "content2" : [ "content2-item" ] },
                "PROVIDE" : { "email_address" : { "email_address" : "Email Address" } }
              }
            },
            { "mail" : {
                "to" : "[email-address:value]",
                "subject" : "Test Email on Content1 Update",
                "message" : "[node:title] was updated",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Replace "content1", "content2" and machine names of fields with your own content/fields machine names before importing. Modify to your liking.


Use data from one textfield to populate other textfields in drupal 7 form

Computed Field

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed
  fields are populated with values that you define via PHP code. You
  may draw on anything available to Drupal, including other fields, the
  current user, database tables, you name it. (Feeling the power yet? :)
  ) You can also choose whether to store your computed field values in
  the database with other content fields, or have them "calculated" on
  the fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!

OR

You can do it by using hook_form_alter then define copy_field_value.js create behavior:

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

      // Repeat this for all fields as needed
      $('#source', context).on('blur', function () {
        // above you can use change instead of blur if element is not changed by another js
        if (!$('#destination').val() || 0 === $('#destination').val().length) {
          $('#destination').val($(this).val());
          // wrap line above in "if no value" like I did, or other condition you like
        }
      });
      // end of "repeat this"
    }
  };
})(jQuery);


How to know if a site is Multilingual programmatically?

Searching I found in drupalcontrib a reference to the language_multilingual() function that show the following code:

function language_multilingual() {
  return Drupal::languageManager()->isMultilingual();
}

So I used Drupal::languageManager()->isMultilingual(); and it seems that returns the good value.

I'll do tomorrow a test in a not multilingual site to confirm.


Avoid hard crash if user searches when Solr stopped

Based on the comment by @4k4 and post at https://drupal.stackexchange.com/a/235942/70681 and further reading, I used my existing custom module (rsc) to solve the problem as follows:

In modules/custom/rsc/rsc.services.yml

services:
  rsc.event.SolrException:
    class: Drupal\rsc\EventSubscriber\rscSolrException
    tags:
      - { name: event_subscriber }

In modules/custom/rsc/src/EventSubscriber/rscSolrException.php

<?php
namespace Drupal\rsc\EventSubscriber;

use Drupal\search_api_solr\SearchApiSolrException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;

class rscSolrException implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::EXCEPTION][] = ['onException', 60];
    return $events;
  }

  public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof SearchApiSolrException) {
      $event->setResponse(new RedirectResponse('/search-not-working'));
    }
  }
}

When a Solr exception occurs, users are redirected to the search-not-working page instead of to "The website encountered an unexpected error." Much nicer.


How can I get user_save() to update the nid instead of creating a vid?

Instead of creating a new object, you should simply update the node object you already seem to have (or load it first with node_load()), update it's properies and then save it.

Trying to save a node object that doesn't have all properties set will result in loosing those that aren't set and other issues like the one you're experiencing.


Import data with feeds that is not in the source file

To get the importer's machine name from the source, instead of doing $source->id, this should be $source->importer->id.

I don't know what you are trying to do with $mapping['_ad_area'] exactly. $mapping contains target configuration (aka mapping settings). I don't see form_callbacks on your target code. The default taxonomy reference field also doesn't have an option called '_ad_area'. If you added mapping for the 'field_ad_area' target, values coming from the source should exist in $values.

You say you want to provide a value that is not in your original source. If this is a fixed value, you can use the Tamper plugin "Set default value" from the Feeds Tamper module. If you are using the CSV parser, on the mapping form you can just enter a source column name that does not exist in your CSV file. Otherwise, select "Blank source".
If you programmatically want to set a value, you can implement the hook hook_feeds_after_parse() in a custom module:

/**
 * Implements hook_feeds_after_parse().
 */
function mymodule_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  if ($source->importer->id != 'qc_data_generic_import') {
    return;
  }

  foreach ($result->items as &$item) {
    $item['Blank source 1'] = 'My value';
  }
}


Issues with custom redirect url using tokens when form field is empty

I ended up writing a custom module to do the post using the following code as a starting point
http://www.midwesternmac.com/blogs/jeff-geerling/integrate-webform-3x-paypal


Drupal Remove jQuery, and jQuery UI and add migrate plugin with Updated jQuery and UI

Ok, there was no 1 step solution to this problem.  So here's what I did in case anyone else wants to know.

This is a 3 STEP solution to adding jQuery 1.9 and jQuery UI 1.10 functionality to Drupal 7.  Not sure about other versions of Drupal.

1 - Needed to remove Drupals old jQuery library of version 1.4 and replace with version 1.9, so in my theme, I added the following function:

In template.php

function MYTHEME_js_alter(&$js) {

    $js['misc/jquery.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';

    // Adding this ensures that the UI functionality gets added at all times!  Even when logged out of the site, since we have functionality on the site that requires this when logged out!
    if (!isset($js['misc/ui/jquery.ui.core.min.js']))
    {
        drupal_add_js('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js');
    }
    else
        $js['misc/ui/jquery.ui.core.min.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js';
}

2 - Now that this is done, before we can really take advantage of Drupal with any other jquery library that is greater than 1.8 (which sucks), we need to add in the migrate plugin found here:  http://blog.jquery.com/2013/05/08/jquery-migrate-1-2-1-released/

I have the Libraries Module installed, so I just put the JS in my Libraries folder called: jquery.migrate

3 - Than I added this to template.php file for my theme:

function MYTHEME_page_alter($page) {
    drupal_add_js(libraries_get_path('jquery.migrate') . '/jquery-migrate-1.2.1.min.js');
}

Now I can use all of the greatest and newest technologies in jQuery 1.9 and beyond while still being able to have Drupal 7 not crash on me!  AMEN!  HALLELUJAH!!!!


Full HTML Formatter / WYSIWYG Not Working In Views 3?

I believe it's a lazy-load editor problem. The WYSIWYG libraries aren't being loaded on the parent page, so they are not available to the modal window. If you're using the WYSIWYG module with CKEditor, something like this should alleviate your issue.

<?php
  // Views support.
  if (module_exists('views') && $form_id == 'views_ui_edi') {
    // Load potential editor.
    foreach (filter_formats() as $format => $object) {
      if ($profile = wysiwyg_get_profile($format)) {
        wysiwyg_load_editor($profile);
        wysiwyg_add_plugin_settings($profile);
        wysiwyg_add_editor_settings($profile, 'advanced');
      }
    }
  }
?>

from http://drupal.org/node/356480#comment-1190907

and the patch located in -

http://drupal.org/node/356480#comment-4256204


Is there a way to make node titles longer?

A simple "I'm feeling lucky" on a google search for "drupal node title length" gives:

Title Length

  This module increases maximum length of node titles to 8000
  characters.


What are the tables that once were term_node & term_data?

All tables by the taxonomy module are prefixed with taxonomy_ since Drupal 7.

term_data is now taxonomy_term_data but also taxonomy_term_field_data, as it is a translatable entity. Never interact with those tables directly, use the entity API.

term_node is taxonomy_index, but it is only a secondary index you can read from there, but the primary storage are the entity_reference fields that point from nodes or any other entity type to taxonomy_term. So if you want to change values, you need use the entity API as well.

Taxonomy works very different than in Drupal 6, where you had to enable a vocabulary per-node type. Now terms work exactly the same as any other refeence, between nodes and other nodes, nodes and users and so on. The only left-over of the old system is that an index table is maintained specifically for node -> taxonomy references.


how to display a custom entity in a view

Include this in your hook_entity_info

MyModule_entity_info() {
...
'views controller class' => 'EntityDefaultViewsController',
...
}

For more details check this link : http://www.sitepoint.com/build-custom-drupal-entities/


How to append options and classes into a custom attribute in Twig?

According to the syntax your declaration is a little off. The function is also create_attribute, not create_attributes.

The {{ attributes }} variable in a node twig template won't hold what you think it holds for the link tag. So, you will need to create a new one.

https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

You probably want something like this:

{% set link_attributes = create_attribute() %}
{% set link_href = content.field_link.0['#url'] %}
{% set link_title = content.field_link.0['#title'] %}

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

 {{ content.field_link.0['#title'] }}

Unfortunately, since you are wrapping fields with the value of a link field, this might be more manual than you would prefer. This is because Drupal is not rendering the field, you are creating html on the fly - link fields in particular are tricky because there is often the case of wrapping data with an anchor in say, a card display format or a clickable CTA. I am not sure if anyone has found better methods of achieving this.

I wonder if anyone has written an extension that will in fact let you render a link field but intake other fields in a tag like you mentioned in another question, so you could wrap them.


Checking https://packagist.org/packages/drupal/drupal for the versions available there is NO 7.x version. Drupal 7 has no composer.json for this to command to work.

You can use one of the other 2 methods mentioned on https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

Using https://github.com/drupal-composer/drupal-project you need to tell the version

composer create-project drupal-composer/drupal-project:7.x-dev \
  test-3 --stability dev --no-interaction

Using https://github.com/hussainweb/drupal-composer-init you can do

composer drupal-init --drupal-7

Please note:

applying core patches seems tricky or even not working. The core tree (whole web root) is deleted then reapplied. But then ie sites/all/modules gets emptied. See

https://github.com/cweagans/composer-patches/issues/42
https://github.com/drupal-composer/preserve-paths/issues/10
In https://github.com/cweagans/composer-patches/issues/42#issuecomment-288365507 a patch is available but that seems NOT to work 100%


When programmatically adding file field, how to set allowed file extensions?

The allowed file extension settings are added to the field instance settings, rather than the global field settings.

The variable is called 'file_extensions' and not 'allowed_file_extensions'

It is also a textfield string value, rather than an array.

You could try something like:

field_create_field(array(
    'field_name' => 'xxx_video',
    'type' => 'file',
    'entity_type' => array('node'),
));
field_create_instance(array(
  'field_name' => 'xxx_video',
  'required' => true,
  'entity_type' => 'node',
  'bundle' => 'xxx',
  'label' => t('Video'),
  'settings' => array('file_extensions' => 'mp4, avi'),
  'description' => t('Video to play in smartbox.'),
));


How can I remove the %20 from a URL evaluted by a contextual filter?

Don't worry, Drupal won't leave you hanging with ugly urls.

1) Open your contextual filter in the admin interface.

2) Expand the "More" section at the bottom.

3) Check "Transform spaces to dashes in URL"

Terms like "my-taxonomy-term" will now be processed as "my taxonomy term"

Bonus: If you need that term to be capitalized for the page title, change "Case" to "Capitalize each word" (also in the "More" section).


Get created term entity after creating term programatically

Term::create() returns the entity that the save() method gets called on. So what you want to do is save that entity to a var before calling the save() method on it.

$term = Term::create([
  'name' => $member[$roster_key],
  'vid' => 'topic_area',
]);
$term->save();

//Retrieve the tid of the new term
$term->tid->getValue();


How to hook contact form of drupal 7 for custom styling?

Or you can use hook_form_FORM_ID_alter() to get the specific contact form. hook_form_alter() will run for every form on the page.

function MYMODULE_form_contact_site_form_alter(&$form, &$form_state, $form_id) {
  $form['name']['#attributes']['class'] = array('class1', 'class2');

  $form['mail']['#attributes']['class'] = array('class1', 'class2');

  $form['subject']['#attributes']['class'] = array('class1', 'class2');

  $form['message']['#attributes']['class'] = array('class1', 'class2');

  // add class to the overall form
  $form['#attributes']['class'] = array('class1');
}

If you don't know how to use custom modules, you'd have to research that first. Dropping this function in and replacing MYMODULE with your module name will make this work.


Create the pdf version of a node programatically (and attaching that pdf version to that node)

You can could start by taking a look at the PHP PDF extension and see how that works out for you. If it does, then you can implement a hook_node_save() - assuming you are in D7, and every time that a node is saved, call your custom PDF functions to generate the PDF.

After your PHP PDF implementation creates the PDF file, you should use Drupal's File API to place the file in the proper place. You would use the File API because it creates an entry in Drupal's file table, and it automatically handles permissions for you - so you can for example, support both public and private (session-protected) files.

Once you upload the file to your web server with the File API, you can then use the Field API to put a reference to the newly created PDF file in one of your node's custom fields. The node's custom field would be of type "file field", and what you would save to that field programatically is the newly created file's fid. The Field API will provide you with the fid.

Finally, you will need to implement a theming function that accepts the node id as a parameter, loads the node in question, looks for the custom field holding the file (using again the Field API), turns the fid inside that custom field into a link with the proper access-level (using the File API), and returns the themed link to your theming layer so it can be printed with the page, and clicked with the users.

In conclusion, unless somebody suggests a contrib module that does this, you would end up implementing at least two Drupal APIs, one external PHP API, and creating some theme hooks. If you are an experienced developer, it should take at least a few hours (or a pair of days).


Set default value for taxonomy list using form_alter

If you are using hook_form_alter I believe this will work

$form['taxonomy'][3]['#default_value'] = array(0 => 6);


Rewrite View Header into first views-row

You can use hook_views_post_execute() or hook_views_pre_render() hooks. Provide you just an example, so you have to add validations and change format of $item variable youself, it depends of your views configuration.

/**
 * Implements hook_views_post_execute().
 */
function mymodule_views_post_execute(&$view) {
  $item = (object) array('node_title' => $view->header['area']->options['content']);
  array_unshift($view->result, $item);
}


Video file upload errors with Cloud FIles

Found the issue, it was with the Cloud Files module (I'm using a dev version) and I've submitted a fix to the author.

The Cloud Files code was creating directory entries in the db for all of the intervening directories when mkdir() was called. The mkdir() code in the file stream wrapper was always trying to insert a row into the cloud_files table. My guess is that it was assumed other modules would check for the existence of a directory before creating it, so he didn't want to do a redundant check. However, I think that other code would usually just blindly call mkdir() because if the directory already existed and it failed there wasn't any real downside to it.


Private tempstore storage contains data for previous anonymous user

Yes, this looks very much like a caching problem. You don't need to disable the anonymous page cache, though, this happens automatically for requests with a session cookie. What you need is a cache context session in render arrays containing session data, no matter whether you serve anonymous or authenticated users:
public function build() {
  $session = \Drupal::request()->getSession();
  $build = [
   '#markup' => $session->get('value'),
  ];
  $build['#cache']['contexts'][] = 'session';
  return $build;
}

The private tempstore is for large amounts of data. See What is the difference between \Drupal::request()->getSession() and \Drupal::service('user.private_tempstore')?


How can a user access only one specific node, and not all nodes of that type?

Using an existing module, you can do that with Content Access, which (when used  together ACL) allows to set the permissions to access a node for each user.
This means that you need to set the access permissions manually for each node.

If you manually create the nodes, and then you want to be sure that only the user who is set as owner of the node is able to view (and edit) it, then you can create a custom module (which means a module that is used for your site), and implement hook_node_access() as follows (the code has been written to make it easier to read):

function mymodule_node_access($node, $op, $account) {
  // We are interested to existing objects. When the node is being created, Drupal passed the node type instead of the node object.
  if (is_object($node)) {
    $bool = (
      ($node->type == 'the node type you need to check') &&
      (($op == 'view') || ($op == 'update'))
    );
    if ($bool) {
      if ($account->uid == $node->uid) {
        return NODE_ACCESS_ALLOW;
      }
      else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

Using this hook implementation, you don't need to manually edit the access permissions given  for each node of that content type you create. Changing the owner of the node would also be easier, as you don't need to change the access permissions of that node; the code would automatically grant the update and view permissions to the user set as owner (or author) of the node.


How to display content in views with large 4-layer taxonomy term tree filter?

You can filter by parent term in views; that way you don't have to list every term in the vocabulary.  Also, learn what a contextual filter is and how to use it.  Here's a series of free screencasts on learning how to use Views.


Feature automatically reverts on cache clear

This is not supposed to happen, a cache clear should not have any effect on overridden features.

I'm just guessing here, but have you tried to uncheck the option 'Rebuild features on cache clear' on the features settings page (admin/structure/features/settings)?

Rebuild and revert are two different things where rebuild should leave the overridden features as they are, but who knows? It's worth the try.


How to add a "Last Updated at" field in footer area?

Not all page types have a a $node object associated (the user page, for one does not).  You can get rid of the error message that says:

Notice: Undefined variable: node

by wrapping the call to format_date in an if-statement like this:

<?php
if (isset($node->changed)) {
  print "Last modified date: " . format_date($node->changed);
}
?>


Drupal as an interface for users to Add/Edit/Search a database

Start off with something like this:

Build Content Types for the data you want to represent. Remember that relationships in Drupal are different than the DB world and are joined with things like http://drupal.org/project/relation or http://drupal.org/project/entity_reference
Use a module like http://drupal.org/project/migrate or http://drupal.org/project/feeds to import your data and map it into your nodes. Feeds will handle what you're doing here pretty handily but if you need more advanced manipulation on the way in, Migrate is the way to go. This can basically run on some kind of cron/batch to continue a "sync" of your data.
Use http://drupal.org/project/views to build reports of your data

If you need to manipulate the data tables directly, that's not exactly what Drupal is built for. It's more than a Front End. It's a full CMF.


I've solved this.
In Drupal, modules also use composer (which I wasn't aware of). The vardumper module depends on the symfony/var-dumper package.
Running:
composer require --dev symfony/var-dumper
causes dependency conflicts, however using:
composer update
Will install the var-dumper package, fix the problem - now I can see very beautiful variable dumps.
Lesson learnt:

Always check composer for dependency errors.


Loading nodes from a specific user and a specific node type

In D6 you could pass criteria to node_load(), so you could do

 $criteria = array(
   'uid' => $userID,
   'type' => $type,
 );

 $nodes = node_load($criteria);

would do the job.

In D7, you don't have this option with node_load as it is just a wrapper for entity_load. This has a depricated argument which allows you to load nodes in the same way

 $criteria = array(
   'uid' => $userID,
   'type' => $type,
 );

 $nodes = entity_load('node',FALSE,$criteria);

note untested

This may work, but is not guaranteed to.

The approved way to do this in D7 is to use EntityFieldQuery

  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $type)
    ->propertyCondition('uid', $userID)
    ->execute();
  $nodes = node_load_multiple(array_keys($entities['node']));

note also untested


Supposing that example.com is a site running Drupal, what Drupal does when you try to access  example.com/exhibition/speacial_feature is:

Verify exhibition/speacial_feature is a path alias
Verify there is a menu that uses exhibition/speacial_feature as path
Verify a module define a menu callback for exhibition/speacial_feature

If none of the conditions is verified, then Drupal returns a 404 error.

In your case, as you want to execute code when a path is entered, you need to create a module that defines a menu callback.

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

  $items['mymodule/%/%'] = array(
    'page callback' => 'mymodule_abc_view',
    'page arguments' => array(1, 2),
  );

  return $items;
}

function mymodule_page_view($first, $second) {
  // Execute the query, and show the result.
}

The code for hook_menu() I shown is the minimum required; see hook_menu() for more information.

As also noted from Berdir, you don't concatenate input given from a user to obtain the query to execute, as that causes SQL injection. You need to use query parameters, which are supported in any Drupal version. Also, with static queries, the name of the database tables are surrounded by { and }.


Core Search only yielding results on specific words

Found the culprit after hours of debugging, it seems that the module Features is causing major issues with resetting the Drupal static. See this issue which contains a temporary workaround patch, since this issue has not been resolved with a solid fix yet.


How to get nid of all nodes that are displayed inside a view?

You can use views_get_view_result($name, $display_id = NULL)

API Docs: views_get_views_result();


One thing to do when you get the WSOD is to turn on all error reporting to see what led up to the failure to produce output.  The error_reporting setting you show is turning of a lot of reporting.

You'll get more runtime error reporting by adding this to the start of settings.php on your site (you add it just below <?php):

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

In addition, navigate to: Administration→ Configuration→ Development → logging and errors and select All messages. This sets $conf['error_level'] = 2;.

Also, check the logs (in particular most recent log messages).

If I should try to guess, I would say you're out of memory.  Having a 32M memory_limit when running Drupal 7 does sound like a source for trouble (I've no Drupal 7 site with less than 128M).


Content from the same content type as the current user

Create a content view
Add the Content: Author relationship
Add the Content: Author uid contenxtual filter

Provide default value: User ID from URL

So far we have a view displaying content created by a certain user, we still have to narrow down the results to a single content type.

Add the Content: Type filter = Org

Note that a page view (with a path) will show no results if you just hit the path. To have results you must pass a uid to the url, like mypath/%uid. On the other hand you can create a block or a content pane and place/embedded it to the user's profile, view's will return all results (if any) for you!


For views 3 - make sure that under "Format->show" field is selected "Fields" (NOT content)

Than go to views and find "Theme: Information" there you can see list of all template currently used (BOLD) and candidate template files. Find witch tpl.php file you want to use.

Go to views module directory and under "theme" folder you should be able to find base tpl.php for your chosen file. Copy that file in your theme folder. Rename it on naming convention given in Theme:Information.

Rescan template files.
If everything is OK views-view-fields.tpl.php should not be bolded anymore. Bolded should be your newly created tpl.php then you can style new tpl.php file as you like.


How can you load redirects for a node to delete them? (redirect api)


How to redirect a user to the Last Domain Browsed

You need to use Cookie as Sessions will be lost once browser is closed.
You can use hook_init() or hook_boot() or page-front.tpl.php

function hook_init(){
 $domain_last_accessed = $_COOKIE['domain_cookie'];
 if($domain_last_accessed != "" && $domain_last_accessed != $_SERVER['HTTP_HOST']){
 // Check if cookie is set and previous visited was not this domain then redirect
 // redirect using drupal_goto() or Header()
 }
 else{
 // Check for Cookie and set if empty, this might be the first visit or cookie was destroyed
 // SetCookie with $_SERVER["HTTP_HOST"]
 }
}

If you want it to be machine independent then you may need to store last accessed domain in DB and note that this will only help authenticated users.


Difference between hook_services_services and hook_services_resources

The first article is incorrect, there is no hook_services_services() (at least not according to any documentation for the services module, nor in my experience).

The correct hook to use is hook_services_resources(). See the docs/services.services.api.php file included with the module for full details.


Does views load all nodes in a result or just the ones in each page of results?

When you display a certain number of records per page it does not load and hide the extra records, it simply never pulls them from the database. So you'd certainly be helping performance by limiting the number that are displayed per page.

In fact, if you look at the SQL query generated by the view, it'll say the following if you're showing 20 items per page, for example:

...
LIMIT 20 OFFSET 0
...

====================== EDIT ====================

What this means for performance

As @Clive and I were discussing above in the comments, A LIMITed query will inevitably be faster than one with no LIMIT, but overall performance will also inevitably decrease as the number of nodes you are searching through increases.

Limiting the number of returned records has performance savings on the Drupal side too, though.  That's because Drupal wouldn't be running the additional processing on the Drupal side to do things like access checks, pre-processing and other display-related functions for the records that aren't returned by the query.

==============================================

p.s.  You can configure whether you want Views to show you the sql query it's generating by going to /admin/structure/views/settings and checking the 'Show the SQL query' checkbox in the 'Live Preview Settings' section.


Manually importing webforms and data with mysql... where is it now?

Webforms are nodes, so you'll also need to bring the node (and potentially field and other depending on your site's configuration) data across.

Make sure the node ids for the webforms are the same as they were in the original site, or you'll have to do some manual work to get the data linked back up again.

This is why it's arguably better to migrate content, rather than do a raw data export/import, as it gives you the opportunity to massage/prepare data as required for the new system.


Its not called search, it will be called filtering.

Goto your view and add a filter.

And then select the expose option in the filter.


Allow users to uploading videos to vimeo

I don't believe uploading directly to Vimeo is a supported feature. I do see an unmaintained module that claims to do something similar, though: http://drupal.org/project/mm_vimeo

I haven't looked at the code, but you could write a module to accomplish the following:

Use a regular file upload field for videos. Nothing fancy. Use the Media module to enable URL video embedding (as if we've copied/pasted a Vimeo URL directly).
Create a cron job to keep an eye on nodes created/updated of that type, making note of videos that should be uploaded to Vimeo.
Upload videos to Vimeo (see: http://developer.vimeo.com/apis/advanced/methods#vimeo-videos-upload)
Modify the Video nodes to include a Vimeo URL to embed in the player.
Remove the file upload, chances are it's huge and not worth retaining.

I've used a modified approach with this in the past with transcoding services in conjunction with Amazon S3 storage and Cloudfront CDN hosting. Very good combo.


Drupal as (powerful) relational database

You have a good start on working with the databases.  From my own experience I am loath to rely/allow Drupal to maintain any sensible data.  And since you already have a robust database it sounds like it would not be a good option for you either.

With all that said, it seems like you want to simply hook into the node/content saving that occurs in drupal.  You will then be able to connect to an external database and process and insert the data anyway you choose.

Node API Hooks - D6 has similar functions, just named differently.  There are a lot of hook points in the process.  You can even alter forms and add your own submit functions.


Set views to output as Show: Content | Teaser

Then in your content type > manage display, click the teaser display mode tab, then set the body field to 'Summary or Trimmed'.

Hope that helps.


How can I disable the node page for a specific content type? (But still use colorbox-node)

In node.tpl.php you can test if node is accessed directly, and if so - redirect him to page with the same node inside colorbox. Or any other page, of course.


I'm afraid not, variable_get() is a very simple function that just returns an item in the global $conf array, there's no method for searching built in.

You could write your own variable_select() function though, and you wouldn't have to go into the database as the entire variable table is loaded into $conf at the start of the page build. It might go something like this:

function variable_select($prefix) {
  $found = array();

  global $conf;
  foreach ($conf as $key => $value) {
    if (strpos($key, $prefix) === 0) {
      $found[$key] = $value;
    }
  }

  return empty($found) ? FALSE : $found;
}

I'm sure that could be improved but it's a start. It's worth noting that this method might match elements from the settings.php file that aren't actually variables in the database as such.

For example, if your prefix is data, it's likely you'll see the $conf['databases'] variable from settings.php in your results. There wouldn't be a way around that without going directly into the db I don't think.


jquery cannot hide span attribute in Drupal 7

Just a wild guess but

jQuery(document).ready(function($){
  $('span.fieldset-legend').hide();
  console.log('Hidden the spans');
});

Try the above code and see if "Hidden the spans" gets output on your javascript console. If it does, then the module you're using (Horizontal Groups? or whatever) is tampering with the spans and perhaps showing them after your code has run and hidden them.


Custom submit handler is also called when deleting a node

You made the mistake of giving the form submit function a name that matches the patter form-name_submit. So it does not only trigger by your submit button. It is triggered by every submit button in the form.

Rename your function and you should be good.


Drupal Module - Mailing List, cannot export list, get browser error

If you are having trouble with the module you are using, there are other mail-type modules available.

MailChimp - Module to utilize subscriptions/emails with mailchimp.com
Simplenews - Publishes and sends newsletters to lists of subscribers (still in Alpha)
Notifications - Complete Subscriptions/Notifications Framework aiming at extendability and scalability (still in Alpha)


How to create image gallery and integrate it to lightbox2

You can do this by using Colorbox module.

  Colorbox is a light-weight customizable lightbox plugin for jQuery.
  This module allows for integration of Colorbox into Drupal. Images,
  iframed or inline content etc. can be displayed in a overlay above the
  current page.

How to use ?


How do I get the taxonomy term's path alias?

You can get it by this way as well (assuming you know $id in advance in code) as of Drupal 8.5.x:
1. For taxonomy term:
Term::load($id); //not important
$aliasManager = \Drupal::service('path.alias_manager');
$alias = $aliasManager->getAliasByPath('/taxonomy/term/'.$id);

2. For node:
$node = \Drupal::entityManager()->getStorage('node')->load($id); //not important
$aliasManager = \Drupal::service('path.alias_manager');
$alias = $aliasManager->getAliasByPath('/node/'.$id);

OUTPUT:
$alias = /fruits/apples
EDIT:
As of Drupal 8.8.x, path.alias_manager has been deprecated, use path_alias.manager in future versions of Drupal.


It's not a bug. Node creation date is stored with hours, minutes and seconds. If you are sorting by creation time, only nodes created in the very same second will ever use secondary sort criteria - Unless you will set granularity:


Views exposed filter auto submit loses focus

Also a workaround for the core problem, but including this js in my theme solved this problem for me.


Repository module code completely different from downloaded file

I think the master branch is still pointing to an old (probably obsolete) branch. To get the latest version, which is inline with the zip file you downloaded, you should use:

git clone --branch 7.x-2.x http://git.drupal.org/project/soundmanager2.git

Maybe you should open an issue and point them to the Moving from a master to a major version branch documentation.


Does adding more processing power increases Drupal Page Load Speed

APC might be your answer

Best APC settings to reduce page execution time

There's a lot here on Drupal speed and performance generally ...


How to show a map within a node using gmap and location modules

In the display settings of your content type, you should be able to change the value to "Map only" or "Adress with Map".

Then it should display it as a GMap.

I use:

GMAP
GMAP Location
Node Locations
Location CCK

I think you're missing Location CCK, in order to get the Map stored as a field in the content type.

Otherwise, if you use the content Location, I think the map is available as a block (not sure about this one).


Overriding the logic of "request new password" in Drupal?

The login system uses various core functions in the core User module to process logins and forgotten passwords.  You really don't want to mess with those (don't edit them).

At any rate hook_form_alter cannot change what those functions do but it can change which function is called.

I would suggest a custom module that

Creates your own separate login page with the logic you desire
Has a function that sends an email with the tokenised link to your new form
Alters the user_pass form to call the function in #2 instead of the standard function which you can do by editing $form['#submit'].


How do I change the image style for avatars displayed in comments

You can modify the image style used for displaying avatars in comments by editing the "compact" display mode for user accounts.

The setting can be found at /admin/config/people/accounts/display/compact. Or by navigating the administration interface:

Admin -> Configuration
Account Settings
'Manage display' tab
'Compact' sub tab.
On the 'Picture' row, click the edit field settings button (Cog image) located on on the right.
Then select your image style.


Flagging content via email notification using Rules, Flags and Drupal 7

As far as I know, the Flags module in Drupal 7 has full Rules support since several months, but only in the -dev version, so have you tried something never than the beta?

This ought to be enough to accomplish what you ask for, but I may misunderstand where you are having problems with the integration.


Have a look at the Node access user reference modules (with about 4,3K reported installs ...), available for both D6 and D7.
Some details from its project page:

Gives content access permissions to users for content that references the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

The above details seem to me like a perfect solution to answer your question. So either just use this contributed module in combination with your own module, or use it a inspiration about how you should enhance your own module in combination with User reference or Entity reference.


Return to calling page after save button

You can use a rewritten "Content: Nid" field to create the Edit link field with a destination parameter that points back to the URL of the page with the table.

The "Link path" field should look something like this:
node/[nid]/edit?destination=path/to/table


Alternate page for mysql connection error

Having a look in drupal_bootstrap() for D7 it looks like hook_boot comes after the database "phase" so you'd need to put something in the cache phase or the configuration phase if you want to trigger a redirect before Drupal tries to bootstrap the database.

Easiest way would probably be to attempt to open a connection to the database yourself near the bottom of settings.php with the connection string defined earlier in settings.php and then if you detect a fail adapt this approach for "fast 404 pages" - http://2bits.com/drupal-planet/reducing-server-resource-utilization-busy-sites-implementing-fast-404s-drupal.html

You could print some html straight to the screen and exit().


Cannot add content to panels pages (stuck in overlay)

So it turned out to be a jquery version problem.

In case somebody else needs it, here is how I managed to solve it.

Installed the jQuery Update module
went to the module's configuration page (admin/config/development/jquery_update)
selected jQuery Version 1.7

and all my troubles faded away :)


How to apply a theme function/template to my form

Is there a #theme property (or something like that) available for forms, which I can set to my theme function/template file?

Yes there is. Take a look at the #theme key in the Form API Reference. Take a look at the code for theme_form() for the default implementation.


you can also use the https://www.drupal.org/project/quicktabs for this
    (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. Clicking on the tabs makes the corresponding content display instantly, using jQuery. With the 6.x-2.x branch, this can be done in either ajax or non-ajax mode:)
available  for drupal 8


How do I show in the home page the facets shown in the product page?

Facets are built inside blocks. Just go to the admin/structure/block and search for Facet API, click configure on the Facet you would like to display on the front page, scroll to the end of the page and you will see a section Visibility options > Pages and on the right a selection named Show this block under the following pages.

You just have to add the pages where you want the selected Facet API block to appear. For instance if you type collection/*, the Facet will appear under every collection for the user to filter.


How can I delete orphaned Product Displays?

Perhaps a PHP script that mimics creation of that View list and then utilizes a node_delete_multiple().  Granted, you will want to test this out very carefully before actually using a method like this.

That said, an Entity Field Query coupled with a node_delete_multiple() may be what you're looking for.  Again, test very well, look at the DB after a test run, see that everything you want deleted is.


Deploying block settings as an update script?

You could do this if you like, but this is an unstable and hacky way of fixing your problem. The thing is that blocks can be rearranged at any time so using an update function to sort the block weights is not the best way to deal with this.

What you could do instead is to use the context module to deal with blocks. If offers a better interface to control blocks and allow you to display the same block in different regions. It also gives you a more advanced control of when blocks should be displayed, like display on all nodes of type x, or on these views etc.

In addition to all the nice features described above, contexts can be exported as features. This mean that you can with a click of a button create a module that have your block setup stored in code, including weights etc. If those blocks were to be rearranged, you could revert the feature back to the old state.


Print module theming address for user page

The print module that you try to use only works for nodes.
You can use the Entity Print module for Drupal 7.
You can read in the docs how to override the default template.

Overriding Templates
You can copy the entity-print.tpl.php template into your theme to take control of the global PDF template.
If you wish to have per entity type templates you can do so by implementing hook_theme() for different entity type keys, for example:
<?php
function MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'entity_print__commerce_order' => array(
      'base hook' => 'entity_print',
      'template' => 'entity-print--commerce-order',
    ),
  );
}
?>


creating a custom report page with a table

Yeah I think you're conflating a few different concepts and making everything way more complex than it needs to be.
If you all you want to do is render a particular custom template with your controller then you'd want to:
// In fun.module
function fun_theme() {
  return [
    'a_fun_template' => [
      'variables' => [
        'heading' => '',
        'activities' => []
      ],
    ],
}

// Then in your controller
public function yourRenderMethod() {
  $heading = 'Some fun activities';
  $activities = [
     'Rocket League',
     'Violin'
  ];
  return [
    '#theme' => 'a_fun_template',
    '#heading' => $heading,
    '#activities' => $activities,
  ];
}

// Then in a-fun-template.html.twig
{#
  Do whatever with your variables, like print them
#}

{{ heading }}

{% for activity in activities %}

{{ activity }}

{% endfor %}

EDIT: I think I figured out why you're looking at the block. All that that is is the "Main page content" block from the blocks page. This just renders the main content for the page, which in this case would be the contents of your controller's template. Now that said, what I wrote before was...
I really don't understand where the block is coming into play here, but I think you're misunderstanding that as well.
First, the default template suggestions are very general. block--wd-admin-content.html.twig is probably added by wd_admin to every admin block by default. That's why a template by that name would be used by all blocks in the admin area. Generally the longer the suggested template name, the more specific it is. Template suggestions that you add to hook_theme_suggestions_block_alter() will apply to all blocks unless you wrap the suggestion in conditional logic that says otherwise. If all you're doing is using a hook_theme template in a controller then you don't need this hook at all.


Create a Block to display Titles - even pages, view-pages, articles

Welcome to Drupal answers.

How hide a title? There are a lot of questions that have been answered about this topic. Here one of them.
How put the title in a block? You have different ways to achive this goal. if you only want to display the title with a content-type and the title is always in the same place, i would create a template for this content-type.

Another way to do it, you should build a module that declare a block. The content of this block(the title of the node) has to to be rebuild when a page is requested.


Facets are missing post updating Apache Solr Search to 7.x-1.4 version

Just wanted to log the answer that is suggested on Drupal.org: https://drupal.org/node/2123683, since this question is the first thing that popped up when I ran into this issue.  :0)

Here is the issue: the taxonomy facets are the ones affected by the upgrade, because even though your taxonomy terms are probably hidden in the 'Search index' view mode on your content type's configuration page, apachesolr used to ignore those settings (a bug).

The new update fixes that, which means you need to go back to your content type's manage display page -> search index tab -> make sure the taxonomy terms in question are not hidden.

Hope this helps!


try this

function grasmash_form_user_register_alter(&$form, &$form_state, $form_id) {
  $form['#submit'] = array(
    'user_register_submit',
    'ctools_wizard_submit',
  );
}


Try this Out:

use Drupal\node\NodeInterface;

    $query = \Drupal::entityQuery('node')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('type', 'event')
    ->condition('field_event_date', ['10.09.2018', '11.09.2018', '13.09.2018' ], 'IN')
    ->range(0, 10);

  $result = $query->execute();


Has anybody figured out how to add videos to a node gallery?

http://drupal.org/project/video    This maybe is the module you need to try?

or users add simple link to youtube http://www.youtube.com/watch?v=-LF30SUwr5Q


How to I place the create form for content type on a page that can save the user's id?

First, to get rid of the "modal window", go to admin/modules and disable the Overlay module.

Second, if you want your logged in users to be able to create articles:

Go to admin/people/permissions and scroll down to the Node section.
There you will find different options to grant them Create, Edit, Delete, etc. permissions. For example, you can check Article: Create new content under the Authenticated User column to allow them to add new items in the Article content type.

Now your logged-in users can go to node/add/article page to find the form.


How can I make the taxonomy terms appear in a drop down list?

Thanks to @Bhuvana

I had just changed the setting, it's work.

Home > Administration > Structure > Content types > Technology


This is not completely straight forward. If you try to create and save a menu link like book/page#anchor-id, Drupal will give this error

  The path 'book/page' is either invalid or you do not have access
  to it.

You will need the node ID. Drupal wants the link to look like this: node/55#block-you-want.

The easiest way to do this is

Save the menu link without the anchor id. ex: /book/page
Drupal will create the menu link like this: node/55
Edit your menu link to: node/55#anchor-id. Save again.


That's stored in the third party settings of the node type.

$type = NodeType::load('article');
$type->getThirdPartySetting('menu_ui', 'parent')

See also menu_ui_get_menu_link_defaults().


Installing Acquia BLT on an existing site

You have two distinct problems here:

"Composerizing" your codebase
Installing BLT

The latter should be pretty painless once you've got the former (theoretically more painful) out of the way.
Fortunately, the Composerize Drupal plugin should get you most if not all of the way there. From the description of your project, you'll want to run this in the root folder (the one containing config/ and docroot/). You don't need to move anything out of the docroot/ folder yourself, anything that needs to be updated will be.
Once that process is complete, run database updates (contrib modules may have been updated to more recent versions), clear cache, verify the site is working, and commit the changes.
At this point you have the structure BLT is expecting, so following the installation instructions again (link in your third approach) should work out a bit better.


Auto Increment value for field collection

The Serial Field module should be able to do that:

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.


Hide the displayed article in a most viewed/popular sidebar

I figured it out by going to Advanced > Contextual Filter. Choose Content: Nid. Then
under "WHEN THE FILTER VALUE IS NOT AVAILABLE", pick "Provide default value", Type = 'Content ID from URL'. Under "More", check on 'exclude' checkbox.


You wont get anywhere triiming in a contextual filter, you need to click on the field and use the rewrite results fieldset in your fields settings.

Simply enter a maximum length, and choose extras like an ellipsis "..." to text that is cut off.

You may also need to change the format to plain text. Or choose a trimmed format.


How to build a module which calls a JS file on one certain node?

I think you're looking for something like hook_page_alter() + drupal_add_js(), e.g.

function MYMODULE_page_alter(&$page) {
  // Check that we're on the right page.
  if (arg(0) == 'stuff' && !arg(1)) {
    // And add some JS.
    drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/MYMODULE.js');
  }
}

This could also be done in hook_preprocess_page(), hook_init(), and probably a bunch of other places. I chose hook_page_alter() at random out of those, each should be equally effective.


How to restrict user posting a node in certain circumstances

You can use the Node access user reference module:

  Gives content access permissions to users for content that references
  the users with User reference or Entity reference.

  This is great if you want your content authors to be able to choose
  additional authors, or choose who can view their content, as well as
  being able to display the list of authors or viewers within your
  content, or in views displays.


View for the user followed by the author of a node

This is a little tricky, but it is very similar to the article posted at http://drupal.org/node/326580.

Create a view of users
Add the "Flags: User flag" relationship making sure that the flags are by any user.
Add the "Flags: User" relationship which will allow us to filter by the person who did the flagging.
Add a contextual filter (D7) / argument (D6) fir the "User: Uid" and make sure is uses the "Flag user" relationship.
In contextual filter / argument, select the "Provide default value" option and add the following code snippet to pass the node author as the value.

Code snippet:

if ($node = menu_get_object()) {
  return $node->uid;
}

In order to get the count it will depend on whether you are using Drupal 6 or Drupal 7, but using the Views Group By module for D6 or the internal Aggregation features of D7 should be able to get you the number of users.


Try the Background Images Formatter module

This module provides an image formatter who allows you to set an image in background of a div.
The images are from a field of an entity and not from a configuration page or sth else, so it's very easy to setup and manage.

This can be done using Views. Create a block, select the "Background Image" formatter for your image field, save, place the block, boom, you're done.


How do i get parent ID of a taxonomy term?

See this core issue: https://www.drupal.org/node/2543726

This will address this. Right now, parent is a special pseudo-field that only supports saving parent relationships but not actually loading them. That's why serialization doesn't work.

You would have to write your own serializer that uses the getParents methods of the taxonomy_term storage to load the data


How drupal keeps revisions for some content types only

For D7:

admin/structure/types/manage/YOUR_CONTENT_TYPE

You need to tick the checkbox "Create new revision" for saving revisions of any content type you want.

For D6:

administer/content management/content types/edit/workflow

Thanks!


entity_id is the entity ID of the entity the field is attached to; in this case, the ID of your field collection item. To add a condition on that, you need to use a propertyCondition() on the "field_collection_item" primary key.


How do I disable/enable the Advanced Content Filtering (ACF) in CKEditor 4.8.0?

It seems that the short answer is "no" in Drupal 8. You should ensure that your HTML is W3C compliant and changes to your code will be minimal.


Conflict between Omega and Views 3 exposed sort (Ajaxified)

I found the solution, it seems to be a database problem for Drupal, and nothing to do with Theme or Views!

  Just remove that specific view from the layout inside your Panel/Page
  design in Pages section, and add it another time.

It will update the Drupal database and everything starts to work!


Jquery Ajax to Drupal to External site, reading response

Try this:

ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('node/1');
print ajax_render($commands);
exit;

Reference D7 AJAX Form Redirect.