Re-Indexing on Search setting, What for?

The possibility to re-index makes sense if your structure has changed or you gather information for the index in another way. For example if you want to show on a node a referenced node in another viewmode (e.g full instead of teaser). But this depends on your general setup and how you configured your content types and viewmodes.

The re-index option deletes the current search index. The "run cron" writes the new search information to the search index everytime the cron runs.


fastest between hook_js vs hook_menu to get JSON via REST

Actually, as the project documentation says, you should use http://example.com/js.php?q=js/mymodule/callback instead of http://example.com/index.php?q=js/mymodule/callback, and basing on the test reported from the maintainer, the previous is faster than the latter (59.371 ms per request versus 446.846 ms per request). Since you are waiting a reply from another server, probably you would not notice that difference too.

For you second question, if you are going to use the High-performance JavaScript callback handler module in the way shown in the documentation, js.php bootstraps Drupal at DRUPAL_BOOTSTRAP_DATABASE level. In any case, if you are not using any Drupal function nor the session, and you are using just plain PHP functions or classes, then you don't need to bootstrap Drupal at all. Keep in mind that this means you cannot use any function implemented by Drupal modules too.


Drupal 7 - Exposed form block also inside results

You can override View tpl file and do the arrangement as per requirement. Also check the setting for exposed for under view.


Use drush to put a site in maintenance mode

system.maintenance_mode is not a boolean, it is an integer:

drush ev "var_dump(\Drupal::state()->get('system.maintenance_mode'));"

Result:

int(0)

The answer to the question, how to use drush to put a site in maintenance mode:

drush sset system.maintenance_mode 1


View with entityreference: make exposed filter autocomplete

The patch I added to the initial question did the trick: http://drupal.org/node/1492260
The only thing you need to know is that you need to enable a checkbox on the fieldsettings of the field on you content type.


Noitifications about security updates keeps coming after the update is done

I think this is the default behavior of the Update Status module, which is part of core. Unless you turn it off or reconfigure it, the modules will be checked daily and the site administrator will get email notices.


How to create a new parent section on the Configuration page?

Here is a way to do it.
#example_codes.links.menu.yml
example_codes.base:
  title: 'Example Codes Module'
  parent: system.admin
  description: 'A Module with various Examples.'
  route_name: example_codes.base
  weight: 0

You need to define system.admin as parent.
And in your routing.yml should contain this base route.
#example_codes.routing.yml
example_codes.base:
  path: '/admin/examples-codes'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Example Codes Module'
  requirements:
    _permission: 'administer example codes configurations'


How can I print a field value in node.html.twig?

While you can print the first value of the field without the surrounding div container with {{ content.field_test[0] }}, this is not a recommend way to do it.

The markup you want to change is in the field template. If you don't want for example any div's around the field field-test, then place a field template in the template folder of the theme:

field--field-test.html.twig:

<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

The benefit you get is that this outputs multi-value fields and that you keep the attributes of the field, which is important if you want the theme to work with core and third-party modules for client side functionality like, for example, quickedit.


Add an item among those displayed in a Views block that links to the item creation page

Add a header to the view and style it to fit your needs.

You can chose between rendered entity: custom menu link or just add a textarea and enter your link. The first option might be better because it provides an access check.

You might need to customize some of the fields HTML within the fields style settings to make this work.


How to remove blocks as a Context reaction?

@jack, you can't remove blocks that are already being rendered, but you can show them only on specific pages, which will effectively do what you need.

For example, I had a footer contact form which I want to show on all pages on the site except on the contact page. I used the following steps:

Added a new context called "except_contact".
On the new context editing screen, added a path condition with the path negation operator, "~" (which is specific to contexts):  "~contact/info" will activate the context in all paths except contact/info.
Added the global contact block to the footer region.

This does what you need - show the block in all pages except the designated page where the block is effectively removed.


You can get access to help by use field_info_instance function in Your template.php

At the beginning let's assume that You have a field called 'spagetti' created in content type 'Article'. Also,  in this case, mytheme is Your default theme.

First, edit mytheme's template.php file and put into following code:

/**
* Implements template_preprocess_field
*/
function mytheme_preprocess_field(&$variables) {
  $field_name = $variables['element']['#field_name'];
  if($field_name == 'field_spagetti') {
    //Get help ('description' parameter) of field Spagetti
    $instance = field_info_instance('node', $field_name, 'article');
    //Add new parameter to the field
    $variables['element']['#help'] = $instance['description'];
  }
}

Now You can get help value from field array.

For example You may to create template for field spagetti:
(field--field-spagetti.tpl.php)
and render field inside:

$field = $variables['element'];

echo $field['#title'];
echo $field['#items'][0]['value'];
echo $field['#help'];


Proper way to create image field in a content entity

See ...

$entity->getFieldDefinition('image')

'file_extensions' => string(16) "png gif jpg jpeg"
'file_directory' => string(31) "[date:custom:Y]-[date:custom:m]"

And edit

$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setDescription(t('Image field'))
  ->setSettings([
    'file_directory' => 'IMAGE_FOLDER',
    'alt_field_required' => FALSE,
    'file_extensions' => 'png jpg jpeg',
  ])
 ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'default',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'label' => 'hidden',
    'type' => 'image_image',
    'weight' => 0,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);


How to include the Title field of a content type inside of a Group?

There is only one way I'm aware of to do this. But since this solution is structural, it may not make sense to use it since the goal here is more for admin-usability.

You could use the Automatic Nodetitles module ("ANT") create a new CCK field for the title, put it in the fieldgroup that you like, and configure ANT to populate the true title field from that new custom CCK field.


How to implement custom access to node revisions?

As you said, node revision does not have hook implement for check access. So you need other way to resolved your problem. My way is alter existing services. Just following document, there is file my_module/src/MyModuleServiceProvider.php

<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class MyModuleServiceProvider.
 *
 * @package Drupal\mymodule
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('access_check.node.revision');
    $definition->setClass('Drupal\my_module\Access\MyModuleNodeRevisionAccessCheck');
    $definition->setArguments(
      [
        new Reference('entity.manager'),
      ]
    );
  }

}

After alter access_check.node.revision service. I'll define new class check access view node revision with extend class NodeRevisionAccessCheck and override method access like this. File src/Access/MyModuleNodeRevisionAccessCheck

<?php

namespace Drupal\my_module\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\node\Access\NodeRevisionAccessCheck;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Provides an access checker for node revisions.
 *
 * @ingroup node_access
 */
class MyModuleNodeRevisionAccessCheck extends NodeRevisionAccessCheck {

  public function access(Route $route, AccountInterface $account, $node_revision = NULL, NodeInterface $node = NULL) {
    if ($node_revision) {
      $node = $this->nodeStorage->loadRevision($node_revision);
    }
    $operation = $route->getRequirement('_access_node_revision');
    // You can override logic check access here or provide a new hook.
  }

}


How to show warning and list of related content

Use the Unique field module:

  This module performs additional validation when a node is created or
  updated by a user to require that a node's title, author, language,
  and CCK fields are unique within a given context.


You need to define it in either a module, or the libraries.yml file of your theme. Then you need to attach it to the page. See the "CDN / externally hosted libraries" of this doc page:

https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

Then you need to attach the library - this is fairly straightforward in mytheme.theme.

Example mytheme.theme file:

function mytheme_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'mytheme/chartjs';
}


How to upgrade outdated Drupal 7 version

You can upgrade directly to the new version as it contains all the previous changes as well. But don't forget to follow the backup instructions...


Make Admin fieldset open by default when editing comment

Use hook_form_alter(). Here's an example:

    function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
      if ($form_id == 'comment_node_YOUR_CONTENT_TYPE_form') {
        $form['author']['#collapsed'] = FALSE;
      }
    }

You can place this in a custom module, or in template.php of your your front end theme.


Assuming that you inherited the custom modules along with the site, and there is no external maintainer of those, you should refactor the modules.

For contributed modules (i.e. modules maintained - or in some cases not - at drupal.org/projects), the options are more complicated.  I don't recommend creating yet another module (global_fixes) to deal with this.  You'll have problems keeping this in sync with new releases of the contributed modules you feel the urge to "fix".

Instead:

If you're community oriented person, raise an issue in the module's project issue queue for what you consider duplicated code (or other defects). If you fix the problem yourself, make your fix a patch, and add the patch to the issue queue.
If you don't want the hassle of dealing with module maintainers and the community, make a local fork where you essentially turn a contributed module into a custom one, and do whatever you like with it.  This also means that you will no longer be able to download improved versions of this module drupal.org/projects. You'll have to maintain it yourself (just like any other custom module).

If you want to follow the community route, you'll probably notice that not all Drupal project maintainers are prepared to resolve your issues or commit your patches in a timely manner.  So if you decide to create and submit patches, I strongly recommend that you install git and maintain a local repository that let you work with the code locally (independent of the repository at Drupal.org).  Just do a merge whenever there is a new commit available at the central repository.

If you're really community minded, and discover that all the fine patches you create and submit to a project's issue queue appearently fall into a black hole, you may want to read up on this: Dealing with unsupported (abandoned) projects.


Creating a redirect for content type conditionally

No problem bro, its pretty simple.  I'll write you a step by step tutorial as an edit. Standby.

You will need to create a preprocess function.  Add a folder and a file in your theme.  THEMENAME/preprocess/node.preprocess.inc with this code:

<?php

/**
 * Implements hook_preprocess_node().
 *
 * Hyjacking the nodes normal node link if an external link is specified
 *
 */
function YOURTHEMENAME_preprocess_node(&$variables) {

  $url = NULL;

  switch ($variables['type']) {
    case 'article':
      if (isset($variables['alternate_link']['und'][0]['url'])) {
        $url = (!empty($variables['alternate_link']['und'][0]['url'])) ? $variables['alternate_link']['und'][0]['url'] : NULL;
        $variables['node_url'] = $url;
      }
    break;
  }

}

My example states that In the case of a Content Type with the machine name of 'article' (yours may be different) do something.

THEN check if my field with the machine name of 'alternative_link' (your machine name will be different) has a value then do something.

It will then use the node's default $url variable.

If it is not set, it will ignore this code and leave your $url clean


Print from drupal to a printer over the internet

You can create batch script on remote PC that connects with your site database and check if it required to print something. Then generate document from database data, and print it from command line.


Display images twice in a node with different image cache settings

You can get the image path by using following code:

<?php
var_dump($node);
?>

Now find the path of the image and write the following code:

<?php
theme('image_style', array('style_name' => 'stylename', 'path' => 'image path', 'alt' => 'image alt', 'title' => 'image title', 'width' => 'some width', 'height' => 'some height')));
?>

Where you can define your own style name. I hope you know how to create image styles.
Just Goto admin/config/media/image-styles and add your style and use it in above code. Use above code twice to print images in two different style.

Entire code:

// filename relative to files directory
// e.g. 'masthead.jpg'
$filename = $node->field_image['und'][0]['filename'];

// relative path to raw image in 'scheme' format
// e.g. 'public://masthead.jpg'
$image_uri = file_build_uri($filename);

// relative path to 'styled' image (using an arbitrary 'banner' style) in 'scheme' format
// e.g. 'public://styles/banner/public/masthead.jpg'
image_style_path('banner', $filename);

// html for a styled image
// e.g. '<img typeof="foaf:Image" src="http://mysite.com/sites/default/files/styles/banner/public/masthead.jpg" alt="" />'
print  theme('image_style', array('style_name' => 'banner', 'path' => $image_uri));


Regarding your 2nd and 3rd questions, you could try this answer here: https://drupal.stackexchange.com/a/62407/12701

Instead of hacking the statuses module, you should create your own module and use hook_form_alter() like this:

/**
 * Implements hook_form_alter().
 * Adding WYSIWYG editor to statuses
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'statuses_box':
      $form['fbss-status']['#type'] = 'text_format';
      $form['fbss-status']['#format'] = 'filtered_html';
      break;
    case 'fbss_comments_edit':
      $form['status-comment-edit']['#type'] = 'text_format';
      $form['status-comment-edit']['#format'] = 'filtered_html';
      break;
  }
  if (substr($form_id, 0, strlen('fbss_comments_box')) === 'fbss_comments_box') {
    $form['status-comment']['#type'] = 'text_format';
    $form['status-comment']['#format'] = 'filtered_html';
  }
}


In hook_page_alter you can override js settings just by using drupal_add_js like you pasted above.


Views Block: one node latest of several categories

You can create a normal view first listing only the newest item (see Pager settings).
Then, create a contextual filter for the category so that you can call the view with different category ids.

Now, you'll the Views Field View module, it enables you to add other views as fields. Add a View Field Views field for each category to your block display.


Token authentication- "The form has become outdated" and rules issues

From my point of view, it would seem Rules are not being triggered at all. You could, however, try invoking a rule manually by placing a rules_invoke_event() call within inside a custom form submit function.

Note that the #submit property on Drupal forms allow multiple submit handlers to be called for a single form.

In the hook_form_privatemsg_new_alter() and hook_form_privatemsg_form_reply_alter() form alters you have implemented you should be able to find and modify the #submit property. Just do something like:

// Implementation of hook_form_FORMID_alter().
patricks_form_privatemsg_new_alter($form, &$form_state) {
  ...
  $form['#submit'][] = 'patricks_privatemsg_submit';
  return $form;
}

Then in your submit handler you can use the rules_invoke_event():

function patricks_privatemsg_submit($form, &$form_state) {
   drupal_set_message(t('The form has been submitted.'));
   // Pass parameters for the variables provided by this event, as defined in hook_rules_event_info()...
   rules_invoke_event('privmsg_foo_rule', $foos, $barf, $bam);
}

If for some reason you get a rules_invoke_event() function not found error, just add a module_load_include() to your submit handler before invoking the rule.


what is a reasonable value for max_allowed_packet for Drupal 7 with moderate traffic？

I saw an interesting answer to a question about the biggest BLOB you may have. Here is the statement I saw in ServerFault : innodb_log_file_size and innodb_log_buffer_size combined must be larger than ten times your biggest blob object if you have a lot of large ones.
Based on that ServerFault post from Nils-Anders Nøttseter, you should query the table and find out which BLOB is the biggest, multiply that number by 11 or more, and use that answer as the max_allowed_packet going forward.
It's funny that I addressed another question where I suggested sizing the max_allowed packet to hopefully solve the issue.
CAVEAT
According to the Book

Here is what Page 99 Paragraphs 1-3 says about MySQL Packets:

MySQL network communication code was
written under the assumption that
queries are always reasonably short,
and therefore can be sent to and
processed by the server in one chunk,
which is called a packet in MySQL
terminology. The server allocates the
memory for a temporary buffer to store
the packet, and it requests enough to
fit it entirely. This architecture
requires a precaution to avoid having
the server run out of memory---a cap
on the size of the packet, which this
option accomplishes.
The code of interest in relation to
this option is found in
sql/net_serv.cc. Take a look at my_net_read(), then follow the call to my_real_read() and pay
particular attention to
net_realloc().
This variable also limits the length
of a result of many string functons.
See sql/field.cc and
sql/intem_strfunc.cc for details.

Knowing this about MySQL Packets allows a DBA to size them up to accommodate multiple BLOBs inside one MySQL Packet, even if they are obnoxiously large.
Regarding your situation, you should find out what is the biggest BLOB in your database, multiple that number by 11 and set your max_allowed_packet to that number. You should be able to set it for the server without a mysql restart (Personally, I would set it 256M because it would address other problems regarding migration and replication, which is beyond the scope of this forum). To set it to 256M for your database for all incoming connections, please run this:
SET GLOBAL max_allowed_packet = 1024 * 1024 * 256;

Afterwards, add this setting to my.cnf under the [mysqld] section:
[mysqld]
max_allowed_packet = 256M


How to pass values to content creation page to set default values in form elements?

Altering the form

You should implement the hook_form_FORM_ID_alter. Then, read the parameters like this:

$name = \Drupal::request()->request->get('country'); // from param

Then alter the form elements, rewriting the #defatult_value conditionally, like this:

$form['field_country']'#default_value'] = 'my domain specific default';

In the case of a checkbox widget, the #default_value is an array (source):

$form['countries']['#default_value'] = [1, 3];

Passing parameters in general

If your parameters are simple strings, like country: denmark, you could use GET parameters. This answer has the sample code:

How do I create a link?

Passing parameters through the '/node/add' route

This is a special route, it is not so simple.

Method 1: Implementing a subtheme

If you are using the default admin theme ('seven') you would have to create a subtheme, and overwrite this hook, so that your custom parameters are passed:

   /**
     * Implements hook_preprocess_HOOK() for list of available node type templates.
     */
    function seven_preprocess_node_add_list(&$variables) {
      if (!empty($variables['content'])) {
        /** @var \Drupal\node\NodeTypeInterface $type */
        foreach ($variables['content'] as $type) {
          $variables['types'][$type->id()]['label'] = $type->label();
          $variables['types'][$type->id()]['url'] = \Drupal::url('node.add', ['node_type' => $type->id()]);
        }
      }
    }

Method 2: Overwriting the twig template

The links are ultimately rendered by the  core/themes/seven/templates/node-add-list.html.twig template. To overwrite this output, you would:
 - Implement a hook_theme_suggestions_HOOK
 - Copy the node-add-list.html.twig to node-add-list--custom.html.twig and implement your custom changes here.

/**
 * Implements hook_theme_suggestions_HOOK()
 */
function hook_theme_suggestions_node_add_list(array $variables) {
  $suggestions = array();
  $suggestions[] = 'node_add_list__custom';
  return $suggestions;
}


Commerce for Drupal 8 must be considered unusable at this stage and very unstable as it is still in alpha version.

No stable version has been released yet, therefore it is advised not to try to build anything yet with it, and installation shall be considered for development purpose only.


How to add a report an error button in a Drupal 7 website and collect user's browser details?

You could check out the Feedback module to see if it meets your needs - it's pretty simple and lightweight. If you don't want to use a contrib module, you could do something similar to the Feedback module - create a block (either using existing blocks in your theme or create a new block region programmatically), position it absolutely, and then link the 'Report an Error' block text to some kind of web form where you can collect the desired information. You could also use the Webform module to help you quickly create a form.


How do I pass data between hooks that don't interact?

In Drupal 7, or higher, use a static variable handled with drupal_static().
drupal_static() is a function that handles a central storage for static variables. Differently from the variables declared using the static keyword, the static variables handled with drupal_static() are accessible from every function; this is possible because drupal_static() returns the variable's content by reference, allowing every function to alter it.

Suppose that you need to pass a value between a menu handler, and the implementation of hook_block_view(); you could use the following code.

function mymodule_menu() {
  return array('path/%' => array(
    'page callback' => 'mymodule_callback_function',
    'page arguments' => array(1),
  ));
}

function mymodule_callback_function($data) {
  $data_passer = &drupal_static('mymodule_block_data');

  $data_passer = $data;

  // Other logic specific to this page callback.
}

function mymodule_block_view($delta = '') {
  // $data_passer will now contain the value of $data, from above.
  $data_passer = &drupal_static('mymodule_block_data');

  // Change the block content basing on the content of $data_passer.
}

In the case that data need to be accessed more frequently, you should use a static local variable that would contain the value returned from drupal_static(). As static variables can only be initialized from literal value, and static variables cannot be assigned to references, the only working code is similar to the following one. (This code is taken from user_access().)

  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  }
  $perm = &$drupal_static_fast['perm'];

The value returned from drupal_static() is reset every time Drupal bootstraps; if you need a value that is preserved between different pages, then you need to use a database table to store the value, or use variable_get()/variable_set().

Drupal 6 doesn't implement drupal_static(), but you could copy its code in a function defined in your own module.

function &mymodule_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();

  // First check if dealing with a previously defined static variable.
  if (isset($data[$name]) || array_key_exists($name, $data)) {
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
    if ($reset) {
      // Reset pre-existing static variable to its default value.
      $data[$name] = $default[$name];
    }
    return $data[$name];
  }

  // Neither $data[$name] nor $default[$name] static variables exist.
  if (isset($name)) {
    if ($reset) {
      // Reset was called before a default is set and yet a variable must be
      // returned.
      return $data;
    }
    // First call with new non-NULL $name. Initialize a new static variable.
    $default[$name] = $data[$name] = $default_value;
    return $data[$name];
  }

  // Reset all: ($name == NULL). This needs to be done one at a time so that
  // references returned by earlier invocations of drupal_static() also get
  // reset.
  foreach ($default as $name => $value) {
    $data[$name] = $value;
  }

  // As the function returns a reference, the return should always be a
  // variable.
  return $data;
}

Before using a static variable with drupal_static() (or the back ported function defined in your module), you should keep these considerations in mind:

The code works only when the code that sets the static variable runs before the code to get its value; if the execution order is not the thought one, the code doesn't work. When the order of execution is not clearly defined in Drupal documentation, there is the risk the order changes in future versions of Drupal; check the execution order doesn't change in the Drupal version for which you are implementing your code.
Drupal could have implemented a mechanism to share data between different hooks. For example, in the case of different implementations of hook_form_alter(), each implementation can share data with other hook_form_alter() implementations using $form_state; in the same way, form validation handlers, and form submission handlers, can share data using the $form_state parameter that is passed by reference. Before implementing your own code, verify it is possible to share data using a different mechanism already implemented by Drupal for the specific case.


View is using original template rather than new custom template

After a rescan and flushing of caches, the views-view-grid-panel-pane
  is bold in the tab, however, my changes are not reflected in the
  preview.

The view's preview does not use template files from your custom theme. It uses the admin theme.

Thus, you can add the template files to your admin theme. The Drupal default admin theme is called "Seven".

Another option would be to just go directly to the view page url or where the view block gets displayed and just ignore your view preview.


How to redirect user to an url when node is flagged?

You need to use the event, After saving new flagging

Add Condition of Flag, and enter flag machine name

Add action of Page redirect, enter the url where you want to redirect. Ex: /node/1

Important

In your flag settings, you need use a link type of Normal link, because it won't work with AJAX


You should be using Google Custom Search Engine Module instead of embedding the code. Using this module would give you better integration option.

Additional Info: Avoid using PHP Filter as its creates security risk.


Remove or Redirect Users who go to www.domain.com to domain.com

If you're using Apache with your setup, this is built into the .htaccess file that comes with the distribution of Drupal. Look for the following code and follow the instructions in the comments:

  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment and adapt the following:
  # RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
  # RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

You'll have to replace example.com with your own site's domain.


There was an error with the file in gathercontent module of Drupal

It might well be that your problem is caused by what is described in issue 1908144.

That issue also mentions CURL (as in the comment to your question).

Curious to hear if this somehow helps ...


Images uploaded with CKeditor disappear after cron run

Whatever text editor are you using either Basic HTML, Restricted HTML or Full HTML.

In setting if Limit allowed HTML tags and correct faulty HTML is enabled under the Enable filters setting. Check under the Filter setting in the list of Allowed html tags, <img> tag has been enabled or not? If not listed in that list, the image will be strip off from the content as for that case it is restricted html element.

Update-1


How to give user permissions to edit other user fields except user id & pwd?

I think what you want is Restrict Password Change module.

Related modules:

https://www.drupal.org/project/user_readonly
https://www.drupal.org/project/userprotect


Field api - taking responsibility over a field display

Fields are displayed through formatters (you can have multiple ones, and then you chose which one you want when adding the field to a content type, or any bundle of an entity).
So, hook_field_formatter_info() and hook_field_formatter_view().
Open the core image module: modules/image/image.field.inc in your Drupal install, and use that as an example.

You can use hook_field_formatter_info_alter() to add formatters to existing field types (not declared by your mpdule).


Custom module menu path renaming/redirection

You could modify $_GET['q'] during hook_boot(), something like the following.

function mymodule_boot() {
  $_GET['q'] = implode('.', array_slice(explode('.',$_SERVER['HTTP_HOST']), 0, -2));
}

There is probably a regex that could do the same as that explode/implode mess, but that does the trick to start with.


How to list all the commands in Drush 9 (aka: drush help)?

It is clearly a bug that drush help is printing a meaningless error message. Instead, it should tell you how to get the list of available commands.

drush list is the way to do that.


Saving a webform programmatically in a custom webform handler throws "Entity validation was skipped."

The WebformSubmission::resave() method prevents the ::save and ::postSave recursion issue from occuring.


Sharing variables between node preprocess and page preprocess

The node object itself can be used to share information across these two functions. In your template_node_preprocess() override do something like:

$node = $variables['node'];
$node->my_data = my_data_function();
$variables['my_data'] = $node->my_data;

Then in template_preprocess_page() override write:

if (!empty($variables['node'])) {
  $variables['my_data'] = $variables['node']->my_data;
}


A user field's text format defaults to "- Select -", how do I force it to an allowed option?

The text format is added in an after build function somewhere. This is off the top of my head so might need some tweaking, but the idea will be very similar:

function MYMODULE_form_some_form_alter($form, &$form_state) {
  $form['field_bio']['#after_build'][] = '_MYMODULE_some_form_alter_textformat_options';
}

function _MYMODULE_some_form_alter_textformat_options(&$element) {
  $element[LANGUAGE_NONE][0]['format']['#default_value'] = 'filtered_html';
}


On Drush 5.7 you can run the command drush pm-update --no-core module-name. Drush will automatically backup the current module, download the new version and prompt you to update the database.


Semver, core_version_requirement and update hooks

I wouldn't use semantic versioning just for the sake of using it, especially since using it on drupal.org forces you to increase the major version number. Changing major version number means the new version is not compatible with the previous one, which also means the codebase diverges significantly (or it will diverge significantly).

core_version_requirement key require Drupal 8.7.7, while semantic versioning requires Drupal 8.8.3, as previous Drupal versions don't handle them, which means that if you are semantic versioning, you should also use core_version_requirement in the .info.yml file.
Using core_version_requirement doesn't change how semantic versioning works, and using semantic versioning doesn't change how core_version_requirement works, except that with semantic versioning I would set core_version_requirement to ^8.8.3 || ^9, at least.


Check the block configuration for the menu, might be set to only on the default front page, changing the default home page changes the url, so your block needs to be configure to display on the url for your "new" front page. At least I think this is what's going on.


Changing drupal_set_message red or yellow

You've put warning as a 2nd argument for function t(). Look carefully at the syntax. It should be an argument to the drupal_set_message function instead:

Wrong:

 $errors[] = drupal_set_message(t(' Gammarus (Freshwater Shrimp) should be a number!', 'Warning',));

Correct:

$errors[] = drupal_set_message(t(' Gammarus (Freshwater Shrimp) should be a number!'), 'warning');


Multi-site: how to handle some module differences?

Create three modules named site1.module, site2.module and site1site2.module respectively. Store changes (hook_form_alters) for site1's forms (including those of your custom module) in site1.module, sites2's forms in site2.module, and forms of both sites in site1site2.module.

The module names will of course need to be swapped for more meaningful alternatives.


Anonymous Flag with boost module enabled

I'm not too sure, but you'd need to look into how Flag is handling the anonymous user session cookies. You may have to hack the code to add your own user-id and add it to the cookie...


How to theme the create content of custom content type?

Sometimes I want certain roles to see the admin theme on a given page, and sometimes I don't. whitefleaCH's ThemeKey suggestion might address that better (haven't tried that module) but another module suggestion that addresses this is Page Theme. Extremely simple module that does exactly what it's name implies:

Install the module
Go to /admin/structure/page-theme and click "Add theme"
Pick your installed theme and add "node/add/property" and "node/edit/property" and any number of other relative paths to the "Pages" field.

Anyone visiting any of those paths will see the content through the theme you designated.


Best approach to inject variable data into JavaScript files?

Drupal have a javascript array for save settings and variables, take a look here:

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_js/6

Check the "settings" option in that page.

A example could be:

$my_module_variables = array(
  "url"  => "http://google.com",
  "name" => "this is a variable"
);

drupal_add_js(array("my_module_vars" => $my_module_variables),'settings');

And for use it in your javascript files you can do:

console.log(drupal.settings.my_module_vars.url);
//will print http://google.com
console.log(drupal.settings.my_module_vars.name);
//will print "this is a variable"

In this way you can set javascript vars without need print javascript code, only using a php array.


How can I disable JavaScript in Drupal themes or Drupal itself?

Javascript in and of itself is not the problem. I'd place more energy into ensuring that your Rich Textareas  (body, comments, etc) and permissions are configured properly. This is one area where people can slip in rouge JavaScript which may be run on other visitor's browsers. Use TLS (Https) by default and use modules that aid in security such as Security Review, Secure Pages or Secure Login help secure the login process.

There is also tons of great advice and direction on line:

10 Simple steps to protect your Drupal site
Configuring text formats (aka input formats) for security
Securing file permissions and ownership


Using Panels and Views to Display Information from Entity Reference

First, you need to create a view (probably block display) of the sales surveys, with a contextual filter. Create a new view of Sales surveys, with a block display. Add whatever fields you want to the display. Then, open the "advanced" tab, and add a contextual filter:

choose the field that you've named as the entity reference to the store
provide a default value -> "content ID from URL"

Once you save that view, go into panels, and add that view to the page you are creating for the stores.


How to print the file description to my twig template?

The node variable is available in both page.html.twig and node.html.twig, so you can get your file description with

{% for file in node.field_myfile %}
  {{ file.description }}
{% endfor %}

Replace field_myfile with the machine name of your file field.


The problem turned out to be multiple required versions of jquery. A jquery manaement module solved the problem.


Create block and place in Header Top. Go to Structure -> Block -> Add Block, then in Block body, write custom HTML. Below block body, Text format should be in "FULL HTML" to display the image.

I think it will work.


Create view to display a Gmap for locations on node you are currently viewing

Filter on 'Content: Nid' in contextual filters.
Under 'WHEN THE FILTER VALUE IS NOT AVAILABLE', choose 'Provide default value' and 'Content ID from URL'

This will look for a node id in the url and filter your view on that id.


Do I need to build a custom page to list nodes by content type?

No need to build a custom page.  What you want to do is very simple to do with the Views module.

Just build a View to list nodes, and under Filter criteria, add a filter that only displays nodes of whatever content type you want to single out.


Importing nested XML using Feeds XPath Parser

Answered on drupal.org

Import will need to be done using the context \\item\upgrade.

Then to target the title from the parent node, use ..\title.


Please see the solution that should work !

Hook into node view using hook_node_view by writing a custom module.
Change the image field to a image with link using below technique

Get nid of current node using $node->nid;
Get taxonomy term id associated with node object using this technique.
Get all other nodes attached with same taxonomy term that you got in step 2 using taxonomy_select_nodes
From the list of node id's that you got in step 3 check the node id which is just greater than $node->nid and store it in variable $next_nid
Form a link using l function that should be markup for image field.

$overrided_image_field_value = l($image, 'node/' . $next_nid, array('html' => TRUE));

That should do the work !


Selecting field from all comments on a particular node

On the field settings screen, it is important to set the “Voting
target” to “Parent node,” so that these votes will add ratings to the node; then,
click the “Save field settings” button


How to use a custom template for a custom view in Drupal 7?

You dont need to tell drupal use your template to display output. In your view, click on Theme: Inforamtion (at bottom right), see the file names in Display Output and Style Output section (Last file in both the sections). Create files with same name and save them at sites/all/themes/YOURTHEME/templates directory.

To design whole page use last file from Display Output and to design each row use last file from Style Output. First create and save the files. Then click on Display Output or Style Output, copy the code and paste it respective file. Use your HTML/CSS to design the page. Clear the cache and you will see the result.


Is it possible to implement theme preprocessor on specific template in drupal 8?

If you implemented your own template suggestion then it's as easy as writing a function with the following name:

function THEME_OR_MODULE_NAME_preprocess_field__default__node__node_submitted_by__blogs(&$variables) {
}

The main thing to take care of is to convert the hyphen characters (-) to underscores (_).

Good luck!


Redirecting Views dynamically generated URL's via .htaccess RewriteRule - CSS stylehseets arent loading after change

actually i put the RewriteRule above the RewriteCond and it seems to be working good now. so it seems that RewriteCond corresponds to the RewriteRule that's right below it only like an inline if statement


Select 'And/Or' next to Filter Criteria, this will show a popup where you can rearrange them.


Like you said, there is a vcard module for user profiles, but there is also a vcard module for cck fields; you might want to try the module on a local test site, and check if there isn't any issue, as the usage statistics of this module is very low.


Can you restrict core search to the current language?

With a View you will need to do the following:

Make sure, you have also a second language and content translation is enabled (else you won't able to see the filter we need)
Add Filter Criteria: "Translation language"
And then check the following checkbox: "Interface text language selected for page"

Now this view is only going to list elements, which are available on the current language (and their translated version is going to be listed).


For Drupal 7 and earlier, try using drush pm-info module. It may give you what you want.

For Drupal 8 and later, the pm commands are mostly deprecated.  To get module information, you would use composer show drupal/module.


If you used a Media field, I built a module for this purpose: http://drupal.org/project/media_entity_download - it will take file(s) in a media object and give them an instant download uri. It will not show the actual file path to the user.

If you just have a file field, you're basically looking at what private files option does.

In the end, you'd need a solution that ensures a BinaryFileResponse from a controller, you can see an example in my module.


In the latest version of the ckeditor library there is the new Enhanced Image plugin.
This plugin allows you to resize the inline image by dragging the image corner.
Go to ckeditor building website ( http://ckeditor.com/builder) and select the Enhanced Image plugin (image2) and also deselect the standard Image plugin from the build.


js file run again when file upload ajaxly

Solution: Using jQuery Once

Drupal 7 integrates the Jquery Once plugin into Drupal 7 core. This plugin adds a simple class to the HTML element to ensure that the behavior is only processed one time. Here is how we would modify our JavaScript to work with the Jquery Once plugin.

(function ($) {
  Drupal.behaviors.tgdev = {
    attach: function (context, settings) {
      if($('#edit-field-images .image-preview').length==0){
        $('.form-item-field-feature-und-email .iCheck-helper ').once('click', function () {
          if($(this).parent('.icheckbox_line').hasClass('checked')) {
            console.log('checked');
            getSubsAj('mail');
          });
      }
    }
  };
})(jQuery);


How can I lock a user profile field after registration?

Could you use the Field Permissions module?  You could set permissions on the field so that authenticated users (or any other user role if you're using any) cannot edit this specific field, but anonymous (registering) users can.


Fatal error message after installng drupal

This error say that can not  the specified file '/home/mydomain/public_html/includes/drupal/includes/database/select.inc' , It may happened by 2 reason , one permission and another reason ( with more probability ) The file not exist, please make sure that the file exist or have permission .


How to change value of hidden field on node publish?

Piece of cake, if you are willing to use the Rules module for this ... like so:

Rules Event: before saving content, which covers all variations of updates of nodes, and creations of new nodes (and does not require an explicit "entity save" action).
Rules Conditions:

Entity has field, for your hidden status field, that way the logic implemented via this rules only applies for nodes that use this field.
Node-unchanged has status unpublished.
Node-changed has status published.

Rules Action: Set a data value, for your hidden status field, to assign the value 'published'.

With the above in mind, have a look at this rule (in Rules export format), in which I'm using a status field with machine name field_status (and for which a value of "P" reflects "Published" status:

 "rules_change_value_of_hidden_field_on_node_publish" : {
    "LABEL" : "Change value of hidden field on node publish",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } },
      { "NOT node_is_published" : { "node" : [ "node-unchanged" ] } },
      { "node_is_published" : { "node" : [ "node" ] } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-status" ], "value" : "P" } }
    ]
  }
}

If you adapt the machine name field_status to match your own field's machine name, together with the value used to reflect "Published" status, you should be able to import the above rule in your own site. After doing so ... you should be done!


Can Drush 9 be used with this core version?

No. Drupal 7 requires Drush 8.

See https://www.drush.org/latest/install/#drupal-compatibility

Furthermore, Drush 9 can't be installed globally.

See https://www.drush.org/latest/install/


You want something like:

function _mymodule_is_db_column_int11($drupal_field_name) {
  // See example output below.
  $drupal_field_info = field_info_field($drupal_field_name);

  // From this table you can get the table name, which follows a known
  // convention in the Field API (but this lets you get it grammatically)
  // and also value field names from the definition array.
  $sql_details = $drupal_field_info['storage']['details']['sql'];
  $table_name = key($sql_details[FIELD_LOAD_CURRENT]);
  $value_col_name = $sql_details[FIELD_LOAD_CURRENT]['value'];

  // Then in MySQL check the column type. I see no way to do this using
  // the drupal api.
  $raw_table_info = db_query("SHOW COLUMNS FROM :tbl;", array(':tbl' => $table_name)->fetchAll();

  $is_int11_field = FALSE;
  foreach ($raw_table_info as $result_id => $recObject) {
    if ($recObject->field == $value_col_name && $recObject->Type == 'int(11)') {
      $is_int11_field = TRUE;
    }
  }
  return $is_int11_field;
}

An example of output of field_info_fields() for 1 field:

/*
[field_foo_feedback023] => Array
    (
        [entity_types] => Array
            (
            )

        [foreign keys] => Array
            (
                [format] => Array
                    (
                        [table] => filter_format
                        [columns] => Array
                            (
                                [format] => format
                            )

                    )

            )

        [indexes] => Array
            (
                [format] => Array
                    (
                        [0] => format
                    )

            )

        [settings] => Array
            (
            )

        [translatable] => 0
        [storage] => Array
            (
                [type] => field_sql_storage
                [settings] => Array
                    (
                    )

                [module] => field_sql_storage
                [active] => 1
                [details] => Array
                    (
                        [sql] => Array
                            (
                                [FIELD_LOAD_CURRENT] => Array
                                    (
                                        [field_data_field_foo_feedback023] => Array
                                            (
                                                [value] => field_foo_feedback023_value
                                                [format] => field_foo_feedback023_format
                                            )

                                    )

                                [FIELD_LOAD_REVISION] => Array
                                    (
                                        [field_revision_field_foo_feedback023] => Array
                                            (
                                                [value] => field_foo_feedback023_value
                                                [format] => field_foo_feedback023_format
                                            )

                                    )

                            )

                    )

            )

*/

If you're going to try and use this you'd probably want to add caching, probably want to assure your type check is always forced to lower-case etc. Also check your mysql credentials allow for this sql usage of SHOW.

EDIT: A slightly simpler solution

The only problem I see with this solution is for complex or custom fields you will always have to know what the value field you want to check is; and require a custom check -- for default simple value fields this should work without needing custom SQL:

function _mymodule_is_db_column_int11($drupal_field_name) {
  // See example output below.
  $fields = field_read_fields();
  $my_field = &$fields[$field_name];

  $field_uses_sql_storage = $my_field['storage']['type'] = 'field_sql_storage';
  $field_value_uses_int_11 = $my_field['columns']['value']['type'] == 'int' && $my_field['columns']['value']['length'] == 11;

  return $field_uses_sql_storage && $field_value_uses_int_11;
}


How to prevent people to ask for registration in Drupal 7?

Go to Configure > People > Account Settings (/admin/config/people/accounts) and set it so only Administrators can register accounts.


Rendering a field in a custom print template

After a few days of working on this, it ended up being pretty trivial to accomplish this so I'll answer my own question for those who need help in the future. I had most of the solution working but in my custom print template, the key was to have:

<?php print render($ecard_logo); ?>

NOT:

<?php print $ecard_logo; ?>

So the full function in template.php is:

/**
  * Renders the content of the print page using the theme api.
  */
function usfig_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];
// Compartmentalize only for ecard content type.
if($vars['node']->type == 'ecard') {

// Create a var and render using field_view_value, we don't need anything special for this, otherwise use field_get_items for data parts.
$vars['ecard_logo'] = field_view_value('node', $node, 'field_ecard_logo', $node->field_ecard_logo[$node->language][0]);
}

}

... and then in my custom print template I do:

 <?php print render($ecard_logo); ?>

and it works!

Extra credit:

You can create and render an image style with field_view_value as well like so in your theme's template.php file:

 $vars['ecard_image'] = field_view_value('node', $node, 'field_my_image', $node->field_my_image[$node->language][0], array(
      'type' => 'image',
      'settings' => array(
      'image_style' => 'my_custom_image_style',
      'image_link' => 'none',
      ),
      ));

Then just render the variable in your custom template file!  What's the advantage to all this? It allows for ultra minimalist markup and precise themeing where layout and exactness are crucial. It cuts way down on the "divitis" that drupal tends to have.


How to sort name by alphabetically in drupal views?

we have a module called Views Glossary once u install the module we have to enable in stucture->views->glossary view like archive for dats and months


HOOK_entity_presave: field not accessible

Since Drupal 8 you need use OOP methods to get value from an entity field.
For example:

// If you have a field with machine name "field_final_note".
$values = $entity->get('field_final_note')->getValue();

Also, have a look for the type of the entity:

if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'node_type') {
 // Your code.
}

P.S. Well it is very helpful to know the next points

// An old entity state.
if (isset($entity->original)) {
  $old_entity = $entity->original;
  // Some code.
}

// If the entity is new.
if ($entity->isNew()) {
  // Some code.
}


Drupal base_url incorrectly writing extra subdomain

This is not a Drupal-specific problem. This can easily be checked by creating a standalone PHP page and using the same code to test. Being that the variable is overwritten immediately after it is set shows that PHP/Apache is the one doing the overwriting.

It is possible for Apache to overwrite input and output. See: What would cause PHP variables to be rewritten by the server?


Page title set from the title callback doesn't change

You're missing the title arguments key in hook_menu

e.g:

/**
 * Implements hook_menu
 */
function custom_download_menu() {
  $items = array();

  $items['download-code/%'] = array(
    'title callback' => 'custom_download_page_title',
    'title arguments' => array(1),
    'page callback' => 'custom_download_view',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * hook_menu title callback
 */
function custom_download_page_title($file) {
  if (isset($file) {
    $title = "Downloading " . $file . " Code";
  }
  else {
    $title = "Download Code";
  }
  return $title;
}

If the download link is

  download-code/my-file.txt

The page title should then reflect that.


Mod rewrite enabled and working, urls contain index.php/

If you didn't append /index.php to the base URL (e.g. setting $base_url to http://example.com/index.php, in the settings.php file), then the rewrite rules in the Apache configuration files are wrongly adding /index.php to your links.
Check both of them, and you should find what is causing the wrong behavior.


This isn't exactly the same question, but I think this answer is just as valid.

  If I understand you right, you can use a View as the source for the nodereference widget, and give it appropriate filters to only show nodes of a certain type authored by the current user. Or have I got the wrong end of the stick?!


Your block content should look like this:

function cse_block_content($which_block){
  switch ($which_block) {
    case 'cse_search':
      drupal_render(drupal_get_form('my_custom_form'));
    break;

    default:
    break;
  }
}

function my_custom_form($form, &$form_state) {
  $form['cse_search'] = array(
      '#title' => t('CSE Autocomplete TEST!'),
      '#type' => 'textfield',
      '#autocomplete_path' => 'cse/google/autocomplete',
  );

  // Adds a simple submit button that refreshes the form and clears its
  // contents. This is the default behavior for forms.
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Save',
  );

  return $form;
}


Filter child field options by a parent field

I have done this type of thing before. I did it by creating a map (array) of what 'scenes' belong to which 'shows' and sent the javascript array to the page with a hook_form_alter. I then used javascript/jquery to listen for the change event on the 'show' dropdown which then hid or displayed the the corresponding 'scenes' using the array as reference. It could also be done via ajax if you preferred.


How can I restrict access to my website via web services only?

Assume a setup like so:

Assume that for site access via Services you use an account called "ServicesUser".
Create a new role, say you call it "ServicesOnly".
Make sure that there are no other "custom" roles in your site apart from anonymous, Authenticated and Administrator (if there are any: remove them again).
Authorize only user "ServicesUser" for this role "ServicesOnly".
Tune your permissions where appropriate, so that:

No permissions are granted to Anonymous or Authenticated.
All permissions are granted to Administrator (but only in case you have a need to ever login without using services, with a userid different from user/1, if there is no need for that, then no permissions granted to Administrator either).

Granularly issue permissions to role "ServicesOnly", so that "ServicesUser" receives appropriate permissions whenever required.
Whenever the site is switched to maintenance mode (eg to apply Drupal updates), ServicesUser will not be able to login either, which is what you should want also.

With a setup like above, access via Services (and userid = ServicesUser) should work as desired. While I cannot think of any other user who can do anything on your site, except user/1 (and optionally some other user who has access to role Administrator).

With this configuration, these are the only ways around it that I can think of:

Some security issues that are exploited somehow.
Somehow getting access to the ServicesUser account

Note: no additional contributed or custom) modules needed either ...


how to use hook_webform_submission_presave on a site with multiple webforms

Ok, So I've figured this one out:

function cheetahmail_webform_submission_presave($node, &$submission) {
Do something here
}

Without calling a specific form, will effect all webforms.
in my specific instance, i'm trying to catch the submitted/validated info before it enters the DB.


you can get Url it by   get('user_picture')->entity->url()( you can get URI too with get('user_picture')->entity->getFileUri()), So

function tropical_preprocess_page(&$variables){
  // gets current user name
  $user_logged_in_name = $variables['user']->getDisplayName();

  // creates value to ouput in the DOM & capitalize first letter
  $variables['user_logged_in_name'] = ucfirst($user_logged_in_name);

  // gets user email
  $user_email = $variables['user']->getEmail();
  $variables['user_email'] = $user_email;

  // get user picture
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())
  $variables['user_picture'] = $user->get('user_picture')->entity->url();

}

Additionally,  If you want to get the default image when the user account doesn't have an image associated, use the following code.

$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$picture = file_create_url($file->getFileUri());


I am getting an error "Notice: Undefined index: distribution_name in drupal_install_profile_distribution_name() ". How do I fix this?

After seeing the results of drupal_get_profile() and querying for that value in the system table, the result of the query showed that the profile's files were (supposed to be) in:

/var/www/html/profiles/[profile name]/

However, that folder path did not exist. Since Drupal could not find the profile's files in that folder path, it could not set a distribution_name.

I found the correct profile files in my original download from way back in the day, re-uploaded them to the correct directory on my server and cleared the cache. The message disappeared.


You don't need to query the DB directly, you can use an entity query:

$uids = \Drupal::entityQuery('user')
  ->sort('created', 'DESC')
  ->range(0, 1)
  ->execute();
$uid = reset($uids);


How to make a rule for limiting one product per cart

Yes, to restrict to one product per order, add a rule:

Event: before add product to cart,
Action: remove all products from cart.

The effect is existing products are removed and only the latest selected product is added to the cart.


Drush Remote Alias Fails with No Drupal Site Found

Well this is embarrassing.... The problem was my %root directive. I had an additional directory tacked on. It was usr/share/nginx/drupal/docroot. Not no html in the path.

Upvotes for @Queenvictoria though for commenting and getting me to realize my error by poking back in the alias file. Thanks!


Page not found when I try to access my custom module

There are several reason for "Page not found." I'm sharing the some points may be helpful to someone who face same issue.

Check your php log file. if there is some php error in your code, it also cause page not found. It occur in my case.

Check PHP file location, which you mention in routing file. Sometimes php file location not correct.

Most important point, check yml file for indentation, if indentation is not proper it also cause "page not found" issue.

Check recent log message and try to sort out warning/error if any

@Kiran Tej, my issue has been resolved. In my case by mistake I placed the file directly inside the 'src' folder. Please read above points may be it helpful to you if your issue not resolved yet.


How to provide template for particular view mode?

Adding theme hook suggestions in a node preprocess function should do the trick:

function MYMODULE_preprocess_node(&$vars) {
  if ($vars['node']->type == 'article' && $vars['view_mode'] == 'search_result') {
    $vars['theme_hook_suggestions'][] = 'node__article__search_result';
  }
}

After clearing the caches you should be able to use node--article--search-result.tpl.php for your template file name.

NB. You could also do this in your theme's template.php file by calling the function MYTHEME_preprocess_node() instead.


How to remove href from last breadcrumb?

If anyone else is looking for this, here is one way to solve it:

In template.php add the following function

function theme_breadcrumb($variables){
    // get an array with all the breadcrumbs (and their html)
    $breadcrumb = $variables['breadcrumb'];

    // remove the html from the last one and put it into new variable
    $cur_page_brdcrmb = strip_tags(end($breadcrumb));

    //remove the last element from the original breadcrumb array
    array_pop($breadcrumb);

    // add our html free breadcrumb to the array
    $breadcrumb[] = $cur_page_brdcrmb;

    // build the output and return it
    $output = '
' . implode(' » ', $breadcrumb) . '
';
    return $output;
}


#states and #ajax are not working on pop up

You need to load the required JS on page load, not on Ajax load. You will need to load the Drupal.ajax library as well.


You have to build a render array like this:

   public function build() {
     $build = [];
     $build['linkA'] = [
       '#type' => 'link',
       '#title' => 'Link A',
       '#attributes' => [
         'class' => 'link-class',
         'target' => '_blank',
       ],
       '#url' => Url::fromUri($this->configuration['default_LinkA_url']),
     ];
     $build['linkB'] = [
       // ...
     ];

     return $build;
   }

You can add attributes to the link, classes for css or a target to open it in a new tab.


Which Rules condition can be used to email a user when an admin updates their profile?

Interesting Rules question! Have a look at this rule (in Rules export format, just import it in your site and check the results of it):

{ "rules_notify_user_about_profile_updates_by_an_admin" : {
    "LABEL" : "Notify user about profile updates by an admin",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "site:current-user" ], "type" : "user" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Bingo ... it seems to work ..." } } ]
  }
}

To verify if it does what you're looking for, perform these steps:

use a userid with role "administrator" (which I assume to be role id = 3, if not adapt that to the role id you're using for admins).
edit any existing user profile.

If you get a drupal "message" like "Bingo ... it seems to work ...", then adapt the Rules "Action" with that "easy to generate eMail" you seem to already have (or know about).

Of course, if you have another userid available that has permission to edit user profiles, but without admin permission, then that should NOT result in such a "Bingo ...".

For anyone wondering what the actual missing piece of your puzzle was (= the "clue"): adding the condition with entity_is_of_type makes the user_has_role available. That role is related to the user performing the profile update (the "logged in user") ... which of course is different from the account being updated ...


You would need to use the Menu token module in order to get the path to the current page as you first need a valid path, and then add your anchor to the path.

The tokenized path for the menu item should be something like:

[current-page:url:path]#footer


Programmatically load 'add content' form for custom content type in form or block plugin

Entity forms are built by EntityFormBuilder::getForm(). The parameter is an entity not a form class. This can be an existing entity or a new entity to add content.

For example to add content for the content type article you create this entity:

$node = \Drupal\node\Entity\Node::create(['type' => 'article']);

Use the new entity to build the form:

$form = \Drupal::service('entity.form_builder')->getForm($node);


You are asking a lot of questions at the same time, but I assume your main question is How to recover from this failed installation?

You are seeing an UnmetDependenciesException, which means Drupal requires stuff (has a dependency) that has not been loaded... So probably several system modules did not install properly.

That would also explain the behavior you are experiencing, your Drupal installation is broken...

Best would be to start over from scratch, remove all the files and the database tables and try again. Also verify if you have met all of the web server requirements (Drupal 7 & 8).


function MODULE_init(){
  global $user;
  if ($user->uid == 0  && $_GET['q'] == 'node/add/project' ) {
    drupal_goto('user/login');
  }
}


Locking access to /user redirect if logged out

I'm not sure this is necessarily the 'best' way to handle this but you could override the access callback for the user and user/login paths in a custom module and do your whitelist check in there:

function MYMODULE_menu_alter(&$items) {
  $items['user']['access callback'] = 'MYMODULE_access_callback';
  $items['user/login']['access callback'] = 'MYMODULE_access_callback';
}

function MYMODULE_access_callback() {
  global $user;

  if ($user->uid) {
    // If a logged in user is trying to access the login page, deny access
    if (arg(0) == 'user' && arg(1) == 'login') {
      return FALSE;
    }

    // Otherwise let the user see their page
    return TRUE;
  }

  // If we've got this far the user is not logged in and the access
  // is based on the whitelist
  $whitelist = get_whitelist_array();
  if (in_array(ip_address(), $whitelist)) {
    return TRUE;
  }

  return FALSE;
}


Views isn't pulling custom field correctly

When using menu_get_object(), you'll get the node currently displayed from the menu. So for example, if you're on a page with a path like node/123, it will load the node with nid "123" (source). So that won't work inside a views for sure.

You should be able to retrieve the nid from the $entity element, which should be a parameter of your hook_field_formatter_view (as described here).


CKeditor is not working with jquery > 1.8

Okay, this may have been the cause.

I use AdaptiveTheme for my base theme on everything really. Right now the default theme makes use of a FooTheme created with a Corolla base. I had menu setting in the theme turned on and I think it was interfering with the Superfish menu.

If you are using Superfish then turn off all mobile menu options in AdaptiveTheme.


Search API module causes server error when saving index fields

After you disable a module (not 'server' ... as in the "update" part of the question ...) and then enable it again, problems like these might get resolved. There are other situations (and modules) where some similar issues occur, and then get resolved via such disable/enable.

To avoid loosing data (like your search that got deleted), this is a possible approach you may want to consider:

look at the module's `.install) file to find out which table it created (during install).
perform a backup of the tables that are mentioned in the .install file (before uninstalling the module.
disable the module, which will also perform the steps you can see within the .install file (for uninstall now) and then enable the module again.
restore your backup of your tables related to the module.


How to sort views table columns alphabetically with exposed filters?

Install and configure DataTable module.

Please follow the steps given below:

Create a new view at admin/build/views/add
Add fields to show in the table.
Select DataTables as the view style.

  The DataTables module integrates the jQuery plugin DataTables into
  Drupal as a views style and a callable theme function.


To use locales separately, each has to be added as a custom language.

/admin/config/regional/language/add
Choose Custom language.
Enter the locale that you want as the Language code.
Enter the Language name.


is there a way to use preprocess_page only for certain page templates?

I made a test using the following code, in my test site.

function code_testing_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    watchdog('code_testing', var_export($variables['node'], TRUE), array(), WATCHDOG_DEBUG);
  }
}

I then created a view showing the nodes of a specific content type (in my case, it was snippet). When I visited the view page, and checked the output from watchdog(), I have not found any information about $variables['node'].
Effectively, that is what I would expect, as $variables['node'] is set in template_preprocess_page() using the following code.

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

Probably, if the view uses a URL like http://example.com/node/1, and there is a node with that node ID, $variables['node'] could be initialized. Differently, if the view is using a different URL, I would not expect $variables['node'] to be set.

To notice that views_preprocess_node() uses the following code.

  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
    $vars['view'] = $vars['node']->view;
    $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name;
    if (!empty($vars['node']->view->current_display)) {
      $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;

      // If a node is being rendered in a view, and the view does not have a path,
      // prevent drupal from accidentally setting the $page variable:
      if ($vars['page'] && $vars['view_mode'] == 'full' && !$vars['view']->display_handler->has_path()) {
        $vars['page'] = FALSE;
      }
    }
  }

Probably the first control statement can be used in hook_preprocess_node() to check if a view is being served.


How to hide content when first displaying the view (Views contextual filter)

You can do this with an exposed filter and selecting the input required option. This option will appear in the Advanced section in the view configuration. You'll want to add an exposed filter for your title field first. I think that's in core.


Publish Content in Drupal by One Editor Only

As far as i know, Workbench moderation module works based on user roles. The permission to change the state from needs review to published can be given to one or more roles. It is not possible to give permission to specific person.

In your case:

Create a new state 'Ready to Publish'
Add two state transitions, Needs Review -> Ready to Publish and Ready to Publish -> Published
Make sure you remove the state transition Needs Review -> Published (Or you can revoke the permission for this state transition to editor role)
Create a role called 'Publisher'
Assign this role to second editor
Give state transition permission Needs Review -> Ready to publish to editor role
Give state transition permission Ready to publish -> Published to editor role.

With the above steps, teacher posts the content which will be in needs review state. Editor can review the content and can change the state to 'Ready to Publish'. Now, the second editor who has the role 'Publisher' can review the content and can publish.


Programmatically change the weight of a form element

You can do this directly inside hook_form_alter, like this:

function security_question_form_user_register_form_alter(&$form, &$form_state) {
  $form['questions']['#weight'] = -47;
}

Then there is no need to create a custom function to do it.

Another thing, you can't implement hook_form_FORM_ID_alter and then use $form_id inside that. You must implement either hook_form_alter, and check if the form id is the one you want, or implement hook_form_FORM_ID_alter and write the form id in the function name.


How to configure Context to set active on Menu item

The only reason I can think of is that the context modules is actually adding the trail classes but the theme that you are using is not using them.

You can verify this in two ways,

Change the theme back to Bartik and see if it works.
Checkout the template file of your theme, print the variables that are passed to theme_menu_item in your template.php file

If the problem is your theme, then you will need to override the theme_menu_item accordingly in your theme.


How to change the language of strings like "read more" and "submitted by"?

Install the core modules Language and Interface Translation
Add other language (admin/config/regional/language)
Configure the Selected language setting (admin/config/regional/language/detection)
To have a different language in admin enable the detection method Account administration pages
Go to user/1/edit and in Language settings section select your Administration pages language
Translate your strings (admin/config/regional/translate)


Server Error 500 - Edit Tab of Managing Custom Fields of Custom Content Types

This turned out to be a max_post_limit issue, requiring I go from 128 to 256 on my PHP version configuration.


Hiding 3rd level menu from sidebar, but displaying elsewhere. Possible? - D7

The level of control you need can be achieved using Menu Block module:

So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).
Pretty simple, eh?


(search) form without redirect or submit handler

Not sure what you're exactly asking but everything should be well documented on Form API

I've recently done a form like this so I can give you an example of a GET method form:

/**
 * Form function for iwm_collections_search_form block
 */
function mymodule_search_form($form, &$form_state) {
  $form['#action'] = url(MYMODULE_SEARCH_PATH);
  $form['#method'] = 'get';
  $form['#attributes'] = array('class' => array('form-main'));
  $form['#after_build'][] = 'mymodule_search_form_after_build';
  $form['query'] = array(
    '#type' => 'textfield',
    '#title' => t('Keywords'),
    '#default_value' => '',
    '#size' => 30,
  );

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

  return $form;
}

You need an #after_build function to remove the unnecessary hidden fields so that it doesn't clutter the address bar:

/**
 * After build callback for mymodule_search_form
 */
function mymodule_search_form_after_build($form) {
  unset($form['form_token']);
  unset($form['form_build_id']);
  unset($form['form_id']);
  return $form;
}

No javascript, no submit handlers, easy.


You can try out a more general solution for all the forms by using Hide Submit Module

  Some users accidentally click the submit button more than once while
  waiting for their post to be saved. In some cases this may result
  duplicate postings or duplicate e-commerce orders.

  There are few ideas on how to solve duplicate postings but none is
  perfect. One of the solutions is a bit of jQuery to hide or disable
  the submit button after it has been clicked and replace it with an
  informative text such as "Processing..." .

  This module wraps that jQuery code and provides some options. Of
  course this, too, is not a perfect solution as it requires Javascript
  to be enabled. For browsers with Javascript disabled this module will
  have no effect at all.


Transfer field from Organic Group to group content

I actually just ended up doing a hook_form_alter and adding a submit handler that saved the referenced field value from the form state into the field that I wanted to save it in on the non referenced node.

This worked nicely, but you had to save the node before it updates and you have to make sure to tell the web admins that the date field won't update until after they save the node. This provided a little confusion at the beginning.

So, this is a great solution for any node where you want to save form state data from one node/entity to another and have a unique identifier like nid/gid to do database lookup and save. Code sample below. I realize that node_load might be expensive to do, but since it's only happens when an admin user saves a form, I thought it was alright.

/**
 * Implements hook_form_alter().
 */
function custom_add_survey_date_form_webform_node_form_alter(&$form, &$form_state, $form_id) {

  //Add submit handler to grab and change date values
  $form['#submit'][] = 'custom_add_survey_date_submit_handler';
}

 /**
 * Adds a submit handler to webform_node_form
 */
function custom_add_survey_date_submit_handler($form, &$form_state) {

  //grab reference to event date
  $og_reference = $form_state['values']['og_group_ref']['und'][0]['target_id'];

  //load date from event plan node
  $og_node = node_load($og_reference);
  $event_date = $og_node->field_date_of_event['und'][0]['value'];

  //Store date on survey node
  $form_state['values']['field_date_of_event02']['und'][0]['value'] = $event_date;
}


It sounds like you have enabled your Administration Theme for content creation.

Check www.yoursite.com/admin/settings/admin:

and see if that check box is checked.  If it is, uncheck it and then your custom theme should be used from then on, assuming, of course, it's enabled for the user.


Your problem is the number format of your fields.  Turn off the comma that delineates thousands.


create node with a field and it updates another field in a view, elsewhere on the site

Sounds like you could create a rule where:

Event = Node->After saving new content

Condition = Node->Content is of type (your "certain content type")

Action = Set a data value.
Use the data selector to drill down to the field that your View elsewhere is displaying for location. Hit Continue. Use the data selector to drill down to the field in the recently created content that your user has entered the location data into. Save.


How to theme the edit page of a form and retrieve $form variable from the hook_form_alter into the template for theming purposes?

Try something like this:

function hook_theme() {
  return array(
    'custom_content_type_a_node_form' => array(
      'render element' => 'form',
    );
  );
}

function THEMENAME_custom_content_type_a_node_form($variables) {
  dpm($variables);
}


In fact, the metatag field IS serialized. As stated by Monkeybrain, the result you get as field value is a serialized PHP array.

This is due to the nature of the metatag field, which internally stores its value as a string (serialized PHP array). By using the JSON API module alone, you'll get this value only.

If you need the serialized PHP array to be an unserialized JSON object, you will have to do some custom programming.

Either implement an own REST API endpoint, or - probably easier to do - use the JSON API extras module. It introduces an additional resource field enhancer plugin type to process the values of JSON API entity fields. So you can create an own custom module providing a ResourceFieldEnhancer plugin for the metatags field, which could do your desired unserialization.

Bear in mind, that the value saved within the metatag field(s) does not contain entity defaults. If these are required, you should also use the Metatag module's metatag.manager service to additionally fetch this information.


How to restrict access to view node revisions with Organic Groups

Rather than worrying about access to the revisions themselves, you might be able to add relationship to the node itself and then a filter to check it the node is accessible.

I imagine there's a better way to do it, but this might work in the mean time.


What is the appropriate way to get items from an entityqueue?

Given $sid is your subqueue id:

$entity_subqueue = \Drupal::entityManager()->getStorage('entity_subqueue')->load($sid);

Loads the subqueue object.  You can manipulate this to retrieve or update your entityqueue.

To get the items:

$items = $entity_subqueue->get('items')->getValue();

To update the items, add another item to the $items array and then save the entity object:

$items[] = ['target_id' => 69];

$entity_subqueue->set('items', $items);

$entity_subqueue->save();

Voila!

You can check in the database that your entity queue is updated:

select * from entity_subqueue__items where bundle = :sid;

I would like to also add that there is a great alternative to using entityqueue in Drupal 8: the Config Pages module.  It allows you to create entity bundles that have only one entity.  You can then add any field type you like, including entity reference fields.  I recently replaced an entity queue on a project with a config page with an entity reference field, and I preferred the user experience.


Creating, modifying and removing folders and folder structures in Drupal 7

If you're using 'file browser' than you probably have the IMCE file manager enabled. What you want to do then is enable the extension module IMCE_mkdir to create directories and subdirectories (within folders your web user has permission to access):

  IMCE Mkdir allows users to create and delete sub-directories under
  directories assigned by IMCE.


There is a Drupal Dojo video that answers this exact question. It is done in Drupal 6 but might give you some clues how to accomplish this in Drupal 7.

(edit: Response to comment) Although it might add complexity to developing your website, you can use the Context module to trigger block visibility based on certain criteria such as a View being viewed or a taxonomy term page being viewed. Keep in mind that if the Context module is used with all blocks disabled in the block UI it gives a performance boost to the website.


How to truncate a given menu setting an expanded menu item as the root menu in drupal 7?

I've figured it out myself, felt like sharing:

<?php
function _themename_submenu_tree_all_data($menu = 'primary-links', $mlid, $subonly = false) {
    $tree = menu_tree_all_data($menu);
    $childtree = null;

    /*
        thanks Jari http://stackoverflow.com/questions/19112294/how-to-extract-an-array-that-has-a-given-structure-and-whichs-key-value-matc/19112508?noredirect=1#comment28260688_19112508
    */

    function recursiveSearch($array, $key, $value){
      foreach($array as $sub){
        if ($sub['link'][$key] == $value)
          return $sub ;

        if (!empty($sub['below'])){
            $returned = recursiveSearch($sub['below'], $key, $value);
            if ($returned !== null)
                return $returned ;
        }
      }

        return null ;
    }

    $childtree = recursiveSearch($tree, 'mlid', $mlid);

    if ($subonly && $childtree != null) $childtree = $childtree['below'];

    return $childtree;
}

/**
 * Implements hook_preprocess_page().
 */
function themename_preprocess_page(&$vars) {
    if (arg(0) == 'node' && arg(1)) {
        $nid = arg(1);
        $node = node_load($nid);

        $vars['type'] = $node->type;

        // your internal check to see if the menu needs to be truncated

        $isbusiness = _themename_is_business_page($node);

        if ($isbusiness) {
            $trail = menu_get_active_trail();
            $mlid = $trail[ count($trail)-1 ]['mlid'];

            $sub = _themename_submenu_tree_all_data('main-menu', $mlid, true);
            $sub = menu_tree_output($sub);

            $vars['page']['main_menu']['menu_block_2']['#content'] = $sub;
        }
    }
}
?>


How can I force the user to register/login first before being redirected back to the current URL?

Redirect to the login page and provide a destination query parameter to the current route to redirect back after login:

  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect(
          'user.login',
          [],
          ['query' => ['destination' => Url::fromRoute('<current>')->toString()]]
      );
    }

    // build form

    return $form
  }

Don't forget to add a use Drupal\Core\Url; statement to the class.


how to use image styling on a image url field

Try using the Imagecache External drupal module: https://drupal.org/project/imagecache_external

In your template file you could then call (from the drupal project example) and replace 'path' with your path from your url field:

<?php
  print theme('imagecache_external', array(
    'path' => 'http://larsjung.de/h5ai/sample/screenshots/h5ai-v0.7-icons.png',
    'style_name'=> 'thumbnail'),
  );
?>


Customise main-menu link - adding a '/' between  items

I would suggest a purely CSS approach to this. There is really no need to go through the trouble of adding a function to your theme for this change.

The following CSS code would get you (at least close to) the results you desire:

  ul.main-menu li:after {
    content: "/";
  }
  ul.main-menu li.last:after {
    content:"";
  }

The :after pseudo-class's support includes all browsers except IE 7 & below and Firefox 3.0 and lower.


Is it possible to redirect users when page caching is enabled?

Usually no. Not like that.

Caching systems are created to serve content with as minimal as possible PHP execution. If you use varnish, nginx or similar cache, or Boost module, you ay even not have any PHP executed at all. And even if some parts of PHP are executed, theming layer is usually omitted, because logic shouldn't be there - and if logic shouldn't be there, then that's exactly the part that is (or should be) safe to cache.

So first, try to move logic from template to some module, and second - learn about the caching system you are using, and how to add exceptions to it (if just moving the logic does not fix it for you already).


One node on multiple pages with tabbed navigation between fields

This is fairly easy to implement so I think you're right not to want to include a whole module to do this. There's loads of ways to do this but here's one way I've done it recently:

In an overridden node.tpl.php, individually print out the fields you'd like tabbed in a wrapper. Within the wrapper you'll also need to print the links for each tab, with a href pointing to the ID of the item it's related to. Something like this:

You can then write some simple jQuery to show and hide the tabs on click:

$('div.product_tabs ul a').click(function () {
  $('div.tabs > div').hide().filter(this.hash).show();

  $('div.tabs ul a').removeClass('selected');
  $(this).addClass('selected');

  return false;
}).filter(':first').click();

You could easily extend this so when the URL is visited with the fragment identifier on the end, the correct tab is shown.


If the comment module files are there in /modules/comment but not displayed in Admin > Modules it suggests the folder isn't readable by the webserver user.

Check the permissions are correct on the /modules/comment folder to allow read access.

For example:

# Run from Drupal root
# Comment module folder ensure readable
chmod 755 modules/comment
# Recursive chmod on files to ensure readable
find modules/comment -type f -exec chmod 644 {} \;


How can I handle the user access to specific taxonomy terms?

You may want to try to add your own access checking in your view. A possible way to do so, is to use the Views Access Callback module, which you can yuse in a custom module to make your view perform whatever access check you want. Some more details about this Views Access Callback module (from its project page):

Provides callback-based access control for Views.
Available callback functions are defined by modules using hook_views_access_callbacks() function (in the same way as in hook_perm()), then could be set in in view's "Access restrictions" configuration.

The Community documentation for this module provides some extra details to get you going with this module.


Is responsive.desktop.css for desktop & laptops design?

I'll quote from the adaptive theme documentation:

  Global styles always load.
  Responsive styles load in media queries.

So, you don't need to use responsive.desktop.css if you can declare all your styles in global.style.css. This is most probably the case if you don't follow the "mobile first" approach. But if you do, you probably have additional styles for devices larger than tablets, and that's when responsive.desktop.css comes into play. And of course this is also for laptops. It's the screen size that defines this, not the "wording"...

  Global Stylesheets

  These load by default. Using a mobile first approach you would only
  place styles that are going to be used for all devices. You need to be
  ruthless about this and cut down on what is going into these files -
  its very easy to assume you will use this or that everwhere, but in
  reality you are merely falling into the familiar routine of desktop
  first theming. On your average site these files will be rather small.
  If they start getting really big, and if you find yourself overriding
  stuff later in the responsive sheets - then you know you have a
  problem and need to re-think what you are doing.

[...]

  Responsive Stylesheets

  Adaptivetheme provides five responsive stylesheets - one for each
  breakpoint set in your theme settings. During development (see sidebar
  Development and Production Modes) each of these files is loaded in a
  link element and places the media query inside the link element
  itself, as opposed to inside the actual file as an @media declaration.
  The media queries are those you set in the Appearance settings for
  each device type. Adaptivetheme automatically uses these so your
  styles will match to your layout breakpoints.

And do not forget about this setting in the theme settings (css):

  Mobile First or Desktop First Adaptivetheme supports both mobile first and desktop first design approaches. This setting fundementally
  alters what CSS is loaded and how it is loaded. At the most basic
  level if you select Mobile first the Smartphone portrait layout will
  load as the default, if you select Desktop first the Standard layout
  will load as the default. Many other changes take place regarding
  loading of CSS for Internet Explorer, Responsive Gpanels and Panels as
  well.


How might one get a conditional display of tooltip or popup message from a rewritten view field?

You are actually on a good track - and you can use html in the no result text field. An easy solution to just attach the tooltip to the 'X's would be to add the needed info for tipsy there:

X

In the Tipsy module settings you would need to add the appropriate selector in the form of: a.tipsy-tooltip. The selector does not need to be unique - you can use classes instead of ids. That way you can address multiple entries with just one selector.

Selectors are not linked to the position in the table, but rather identify a particular tag. In this case the element the 'a' tag which wraps around X. If the table gets resorted, the tooltip is still attached to the Xs.

Edit 1

The Problem might just be your selector: a.views-field views-field-nothing.

CSS classes are interpreted linearly and the order is important. In this case you are telling tipsy to look for a html element views-field-nothing which itself is nested unter a link a with the class views-field. If you look at the inspector though you will see that the actual mark-up is different and probably looks close to this one:

    X

A link a nested in a element with the classes views-field and views-field-nothing. Tipsy can't convert the default tooltip to a tipsy tooltip because it doesn't find the link to start with.

The correct selector would look like this: .views-field.views-field-nothing a (The missing space between the first two classes is important, as are the dots before the names which indicate they are classes rather than html elements or ids. If you made a space between the first two, it would look for an a-tag nested in a element with the class views-field-nothing which itself is nested under the element with the class views-field.)

Since views-field is a class applied to all fields views outputs you can as well leave it out though and just write .views-field-nothing a

The Problem with views-field-nothing is that it applies to all views and not even just for fields where 'no result' applies - views also uses the same class for fields of the type custom text. To make sure you just target the links you want to turn into tooltips it is easier addressing them with a class on the link itself - e.g. with the a.tipsy-tooltip selector I suggested. It specifically looks for all links with the class tipsy-tooltip so tipsy can extracts their title attribute and uses it for its tooltip text.

You should also pick the 'HTML Attribute' option in this case (Source: 'HTML attribute', Selector: 'title'). The only time you really need to use the 'Child Element' option is when you want to use HTML in the tooltip as you can't do that with the former. With the 'HTML Attribute' option tipsy uses whatever you put as the links title as the tooltip text - no extra classes needed.


You don't have to re-invent the database abstraction layer to access external databases. You can switch the database connection dynamically.

Using Database::addConnectionInfo() you can add your database connection information dynamically. Then use Database::setActiveConnection() and Database::getConnection() with your respective target database identifiers for doing your queries with.

Entity (field) queries won't work obviously, if the external database doesn't have entity tables. But static and dynamic queries will. The latter allow for including the core pagination, if desired.

After you queried your external database, use Database::setActiveConnection() without parameters to reset the connection to the defaults. This is important for Drupal to being able to access its own tables after your queries.

Check the Database API documentation and the database class for more in-depth information. (This will also work in Drupal 7 and its database class.)


Have you tried disabling the equalheights module, perhaps it maybe causing this issue? You don't need a module to give blocks equal heights, when you can easily do that with css.

I noticed on the top screenshot there is no video, while the bottom has a video.

Anyhow, based on your screenshot, it seems that you can fix this by adding a position: relative; to the div id or class that is wrapping the blocks. Which would be #block-views-featured-resource-block and what ever the name the Grand station Resource block id is.


You want to use render() like this:

 <?php print render($page['content']); ?>

I'm not really sure what you mean by "but to work correctly with other Drupal files and components."

You should also print all the standard regions and any other variables you might need. You can find a list of the default variables available to page.tpl.php in the documentation page.

Also here's a list of the regions you probably should include:

$page['help']: Dynamic help text, mostly for admin pages.
$page['highlighted']: Items for the highlighted content region.
$page['content']: The main content of the current page.
$page['sidebar_first']: Items for the first sidebar.
$page['sidebar_second']: Items for the second sidebar.
$page['header']: Items for the header region.
$page['footer']: Items for the footer region.


Where can I find all form display options types for custom entity fields?

Those are field widget plugin IDs.

You can get all of those by querying the field widget plugin manager (service ID: plugin.manager.field.widget).

E.g. to get all the IDs in your entity class (once the service is injected):

$widget_types = $this->fieldWidgetPluginManager->getDefinitions();
$plugin_ids = array_keys($widget_types);

Same thing in procedural code in case someone wants it:

$widget_types = \Drupal::service('plugin.manager.field.widget')->getDefinitions();
$plugin_ids = array_keys($widget_types);

If your current context allows you to inject the widget plugin manager service rather than get it from \Drupal, all the better.