You should try to write each join on a new line, not as an array. See Joins and public function SelectQuery::join.

So try it like this:

$nids = db_select('node', 'n');
  $nids->join('field_data_field_show_block_carousel', 'fc', 'n.nid = fc.entity_id');
  $nids->join('field_data_field_poster_film', 'fp', 'n.nid = fp.entity_id');
  $nids->join('field_data_field_film_link', 'fl', 'n.nid = fl.entity_id');
  $nids->fields('fp', array('field_poster_film_fid'));
  $nids->fields('fl', array('field_film_link_url'));
  $nids->fields('n', array('nid', 'title', 'uid',))
    ->condition('n.type', 'vodeo_library')
    ->condition('fc.field_show_block_carousel_value', 1)
    ->execute(); // returns an indexed array
  $result = $nids->execute()->fetchAllAssoc('nid');

Depending on what your module attempts to achieve, you might also want to have a look at the default Drupal functions for attaching fields to nodes (you only have a condition on one field):

field_attach_load()
field_get_items()
field_view_value()

You can get a rendered field value like this:

$node = node_load($nid);
$poster= field_get_items('node', $node, 'field_data_field_poster_film');
$output = field_view_value('node', $node, 'field_data_field_poster_film', $poster[0]);

And if you don't mind a little overhead, you might want to try an EntityFieldQuery. It will give you all fields and is a little slower then a regular SQL query, but is much easier to read and change.

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'vodeo_library')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_show_block_carousel_value', 'value', 1, '=');

$result = $query->execute();

if (isset($result['node'])) {
  $news_items_nids = array_keys($result['node']);
  $news_items = entity_load('node', $news_items_nids);
}


script-src 'unsafe-inline' is required by CKEditor 4 included in Drupal 8 core, so a newer WYSIWYG editor may not require it.  Drupal 9 will hopefully include CKEditor 5, which will not require 'unsafe-inline'.
CSP Level 3 also introduces the script-src-attr and script-src-elem directives, which can be used to allow only scripts in element attributes and not <script> elements, which will enable CKEditor 4 to work and reduce risk.

Drupal 7 also requires inline scripts be allowed for drupalSettings, though there is a patch available.

Hashes and nonces have some downsides and challenges

CSP Level 2 only allows hashes on inline <script> elements, not element attributes like onclick.  CSP Level 3 introduces 'unsafe-hashes' to allow hashes for attributes, but it can't really be used at this time because of a lack of browser support.
CKEditor 4 would require a 1.5KB CSP header for all of the hashes it would require.
Nonces are only applicable to <script> elements.
Nonces must be regenerated on each page load, preventing the page cache or other front-end caches from being able to cache the page.


Disable Panels Preview when adding new Panes in Layout Editor

I had same problem in one of my project. Then what I did, I added a custom code to remove all the js files except drupal core js, Panels js, Token Js, Ctools js and Views Js. And it is only for the panel pages so it solve the issue of jquery version.
We also have a drupal module jqmulti for this. But in some cases it also do not work well. That is why I removed all the unwanted js files from panel page.
Here is the sample code for this.

function custom_module_js_alter(&$js){
  if(arg(0) == 'admin' && arg(1) == 'structure' && arg(2) == 'pages'){
    $allow = array('modules/filter/filter.js', 'modules/field/modules/text/text.js', 'modules/file/file.js');
    foreach($js as $key => $value){
      $pos =  strpos($key, 'misc');
      if(strstr($key, 'misc') == '' && $key != 'settings' && strstr($key, 'ctools') == '' && strstr($key, 'panels') == '' && strstr($key, 'views') == '' && strstr($key, 'token') == '' && strstr($key, 'admin_menu') == '' && !in_array($key, $allow)){
        unset($js[$key]);
      }
    }
  }
}


Solved this problem by correcting the fourth argument of pager_query function i.e $product_count_query.

Pager query takes the fourth argument as an SQL query to count the number of matching records.It should a valid sql query.


I've never had this problem and I use Webform in pretty much every project.

I would suggest your problem is based on the fact you're using a dev version of the module. Webform has a stable release of 7.x-3.18 whereas you're using 7.x-3.17+3-dev. The first thing I'd do is upgrade to the stable version, clear the caches, and see if the problem persists.

If it does, or you want to stick with the dev version for whatever reason, then you should report any problems to the module issue queue in the first instance.


Recoverable fatal error when trying to run hook_query_TAG_alter()

I used Drupal\Core\Database\Query\AlterableInterface $query as argument.

It solved the problem.


Is this possible to allow creating nodes only for Administrator via interface but for others in custom code?

If what you are asking is...

How can I allow nodes of a certain type to be created programmatically by everyone, but, at the same time, disallow everyone but the Administrator from creating them from the UI?

...the quickest way might be for you to use Rules to create a redirect away from node/add/custom_type for everyone but the Administrator.

However, if you are already creating custom module code, you could also do this pretty simply in hoot_init(), eg, something along the lines of:

global $user;
if ($_GET['q']=='node/add/custom_type') {
   if ($user->uid != 1) { // or whatever logic you want to use to determine the Administrator
     drupal_goto('somewhere else');
   }
}

In either case, you'd have to set up permissions to allow any user to create these types of nodes.


Variable available everywhere in template?

$variables are unique for each template. So if you implement hook_preprocess_html() and add something, then it is only available for html.tpl.php and nothing else.

I think the easiest way to achieve your goal is to create a new function in your template.php which sets the random color them the first time you access it and the returns the them on following calls. Then you can simply call that function from any template you want and it will return the same value on the same request. Such a function would look like this:

function yourtheme_get_color() {
  static $color = NULL;

  if (!$color) {
    // First call, define $colors here and then set $color.
    $color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
  }
  return $color;
}


Indexing the term of unpublished entities

For anyone who might encounter the same issue:

It looks like that it's a common issue in D7 and unfortunately going to be in D8, but hopefully the fix will be in core for D9.

Right now we have to use TEI module as a workaround for D7 and D8.

If you are installing this module into an existing site, visit admin/config/system/taxonomy-entity-index to rebuild the Taxonomy Entity Index.

Also note that in Views there will be some new fields/filters to work with, for instance instead of Content: Has taxonomy terms in filters section of views, you should use Taxonomy Entity Index: Has taxonomy terms on Nodes and for exposing the taxonomy terms also you should use Taxonomy Entity Index: Has taxonomy terms on Nodes not the default Content: Has taxonomy terms.


Have you tried rules module. You can trigger custom action on some event. What you need to do :

create an event "when the node being viwed"
create a condition "when node is equal to some node"
Fire a action "redirect to login page"
Fire another action "show a message"(this is set drupal_set_message for you)


how can i get Drupal webform confirmation message on popup?

Here is an example using a custom module (called it wcm_overlayer). Basically, this will show the confirmation message in an overlayer using the jQuery Fancybox library. For the webform configuration (under form settings), you need to set the redirection location setting to No redirect (reload current page).

wcm_overlayer.module

/**
 * Implements hook_init()
 */
function wcm_overlayer_init()
{
    // Add library & js file
    drupal_add_library('wcm_overlayer', 'fancybox');
    drupal_add_js(
        drupal_get_path('module', 'wcm_overlayer') . '/js/wcm_overlayer.js');
}

/**
 * Implements hook_node_view()
 *
 * @param type $node
 * @param type $view_mode
 * @return boolean
 */
function wcm_overlayer_node_view($node, $view_mode)
{
    // Verify if webform is attached to a node
    if (!isset($node->webform)) {
        return false;
    }

    // Retrieve confirmation message
    $confirmation_message = check_markup(
        $node->webform['confirmation'], $node->webform['confirmation_format']);

    // Retrieve all status message
    $messages = drupal_get_messages('status');

    // None is found, don't do anything
    if (!isset($messages['status'])) {
        return false;
    }

    // Loop through all messages and get confirmation message
    foreach ($messages['status'] as $message) {
        if ($message !== $confirmation_message) {
            drupal_set_message($message);
            continue;
        }

        $found = true;
    }

    // Confirmation message is not found, don't do anything
    if (!isset($found)) {
        return false;
    }

    // Confirmation message is found, pass this as a setting
    drupal_add_js(array(
        'wcm_overlayer' => $confirmation_message,
    ), 'setting');
}

/**
 * Implements hook_library()
 *
 * Define the jQuery Fancybox 1.3.4 as a library
 * @return string
 */
function wcm_overlayer_library()
{
    $path = drupal_get_path('module', 'wcm_overlayer');

    $libraries['fancybox'] = array(
        'title' => 'jQuery Fancybox',
        'version' => '1.3.4',
        'js' => array(
            $path . '/js/vendor/jquery.easing.js' => array(),
            $path . '/js/vendor/jquery.mousewheel.js' => array(),
            $path . '/js/vendor/jquery.fancybox.js' => array(),
        ),
        'css' => array(
            $path . '/css/vendor/jquery.fancybox.css' => array(),
        ),
    );

    return $libraries;
}

js/wcm_overlayer.js

(function ($) {
    Drupal.behaviors.wcm_overlayer = {
        attach: function(context, settings) {
            if (!settings.hasOwnProperty('wcm_overlayer')) {
                return false;
            }

            this.showOverlayer(settings.wcm_overlayer);
        },
        showOverlayer: function(message) {
            $(window).load(function() {
                $.fancybox({ content: function() {
                        return $(message);
                }});
            });
        }
    };
}) (jQuery);

Hope it helps.


How to get the front page title in page.html.twig?

You should really try using the blocks for this, but here's how to do what you asked:

function YOUR_THEME_preprocess_page(&$variables) {
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
  $variables['current_page_title'] = $page_title;
}

This code should go in YOUR_THEME.theme file. You can use it then in page.html.twig this way:

{{ current_page_title }}

See this for more information.


You can try to use the Highlight module. From its project page:

  Highlight the keywords from referrer search engine
  Highlight the keywords from local search

And I think that you should read this posts:

Highlight searched keyword using exposed filter views?
Add Keyword Highlighting using Search API in Drupal 7


Its trickier to 'remove' the template on sites you don't want it on because Drupal will always recognize the file format as a valid template and add it to theme suggestions. An easier option would be to affirmatively add it using a custom module only on the sites you want it on. For example, following this answer, here's how you would register a particular template file only on the subsites you want by just selectively enabling the module where you need it:

/*
 * Implementation of hook_theme().
 */
function YOUR_SUBSITE_MODULE_theme($existing, $type, $theme, $path){
  return array(
    'YOUR_SUBSITE' => array(
      'variables' => array('content' => NULL),
      'file' => 'page--front', // place your file in 'theme' folder of you module folder
      'path' => drupal_get_path('module', 'YOUR_SUBSITE_MODULE') .'/theme'
    )
  );
}

function YOUR_SUBSITE_MODULE_page(){

  // some code to generate $content variable

  return theme('YOUR_SUBSITE', $content); // use $content variable in moon.tpl.php template
}


Taxonomy menu limited to certain number of terms

I believe the easiest way to do this is to create a view that block displays a set number of items in a list (HTML or unformatted list), with a global text field that will link to your term page. You can then style this with css to look like the rest of your menus (if you require to).

This unfortunately will mean that it will not go through the drupal core menu system. You will have to create your own "Admin" view to manage this "menu". I would suggest Draggable Views if you require a webmaster to control the sort order.


IEF = Inline Entity Form; you should find what you're looking for in that module. If you're new to Drupal the layers of abstraction might make it difficult to understand what's going on though. If there's something in particular you're looking to find out how to alter or understand just update the question.

If you install the Devel module and add

dpm($form['customer_profile_ip_info']['field_company_ip_customer_info']['und']['actions']['ief_add']);

to your alter hook you should find the #ajax property.


This is a just a follow up to @googletorp's answer, you can use the following code to export an existing field instance definition to PHP code which you can then alter as you need to for your new instance:

$entity_type = 'node';
$field_name = 'field_name';
$bundle_name = 'node_type';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

That will give you both the field_create_field and field_create_instance code for the field.


How do I hide bulk operations form for a specified user role?

To remove the bulk operations "form element" use ViewExecutable->removeHandler in hook_views_pre_view():

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_view().
 */
function rgr_main_views_pre_view(ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() === 'content') {
    $account = \Drupal::currentUser();
    $is_employee = in_array('employee', $account->getRoles());

    if ($is_employee) {
      $view->removeHandler($view->current_display, 'field', 'node_bulk_form');
    }
  }
}

This will hide the dropdown form elements, the checkbox in the row and the submit buttons.


How to Clone a production site locally for testing?

Most probably the problem is in your settings.php, what you can do:

Open your settings.php files and search for the folowing code:

$databases = array
'default' =>
array (
'default' =>
array (
'database' => 'your-db-name',
'username' => 'your-db-user',
'password' => 'your-db-user-password',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
If you are not sure if you have the correct code for your database, please post your code back in here and i will take a look on it
Last thing, if all you need is making changes to your website using a test website and then push all changes back to the production website, my suggestion is to create a subdomain on your webshost (Ex: dev.yourdomainname.com) and completely clone your entire website from dev.yourdomainname.com so you can work on your dev website without touching your production one.

I can help you with that also but first tell me what your need and answer the following:

_ You have access to Drush console ?
_ You have access to the webhost server ?

waiting your response...

Update # 1: Clone your production website for testing purposes on your webhost

1) Create a subdomain for your domain name (ex: dev.yourdomain.com)

2) From your cpanel, create a new empty database (don't forget to prefix your db name at end by _test to distinguish it from the original one) (Ex: db_name_test)

write down the name of the database

3) create a new user for your test database and also (don't forget to prefix your user name at end by _test to distinguish it from the original one)

Write down the name of the user & password

4) Grant the test user all privileges for the new database.

5) goto your production site and do the following manually or by using the drush command:

Clear all caches. (drush cc all)
Disable clean URLs. (/admin/config/search/clean-urls)(drush vset clean_url 0 --yes)
Disable cron job. (/admin/config/system/cron)
Put site in maintenance mode. (drush vset maintenance_mode 1 --yes)

6) Copy the entire site's drupal root directory to the new test website root directory and make sure the settings.php file is copied as well.

Manually:
Click on the site root directory and choose copy and type the destination path.

drush command:

cp -rp /home/cpanel-user/public_html/your-original-site-root-directory /home/cpanel-user/public_html/your-dev-site-root-directory

7) Goto your phpMyAdmin, Select your original database, Choose operations, under the copy database to section, write down your test database name as it is, make sure the structure and data is selected, and uncheck create database before copying, leave everything else as it is, click Go and wait for the confirmation message.

8) Make sure the permission given to the deb-site root directory is: 0755

9) navigate to your new test website directory, edit settings.php and edit the database settings to fit the new database name, new database user & new user password

10) open new tab browser and navigate to: dev.yourdomain.com

11) Voila, all should be good.

12) goto your dev site and do the following manually or by using the drush command:

Clear all caches. (drush cc all)
Enable clean URLs. (/admin/config/search/clean-urls)(drush vset clean_url 1 --yes)
Enable cron job. (/admin/config/system/cron)
Don't remove the site from the maintenance mode since it is a test website.

Note, you can do the exact steps above to have a copy of your website locally, but i will just stick with this method since it is more reliable. easier and faster.

If you insist of cloning your website locally to acquia dev desktop:

1) Get a fresh copy of your prod-site database and file, manually or using drush

drush ard --destination=/home/cpanel-user/create-a-directory-for-backup/choose-a-name.tar.gz

The above command using drush 7, will get you a copy of your database and your files/folders.

2) Download the archive backup folder to your desktop and unzip.

3) Goto Acquia dev desktop, click on + and import local drupal site

4) Choose the local codebase folder from the unzipped folder you just downloaded.

5) choose a local site.

6) leave the create a new database and give it a new name of your choice.

7) when finish importing, visit your website and complete a new fresh installation from your website.

8) when all go good and you will have a fresh new Drupal website up and running, goto your local database (phpMyAdmin), click on Structure, Scroll down to the button, Check all tables, with selected choose drop, make sure there is no any left tables in the database.

9) Goto import, select you .sql database, leave everything as it is, click Go

10) no need to change anything inside the settings.php, just visit your site and voila.


How to make an existing website responsive using zengrids?

I have found the Superfish module plays well with the Zen theme. By default, it will toggle wide dropdown menus to accordion style menus at 768px.

The superfish library includes sass and css template files you can drop into your theme's scss or css folders.

I am using a custom theme based on Zen 7x-6x starterkit.


Service module user update request payload

To update a user with the Services module, utilize these:

HTTP Method: PUT

URL: ?q=[endpoint-name]/user/123.json

Headers

Content-type: application/json
X-CSRF-Token: use value available from ?q=services/session/token

Data payload:

{
  "uid":"123",
  "mail":"new-email-address@example.com",
  "current_pass":"superSecret"
}


Apparently cron api dosn't work with Drupal 8 at this time. What I did to fix my issue was to create one new module to handle only the cron job that I wanted. Then from the UI of Ultimate Cron I would add the rule to schedule my cron job.

use Drupal\MODULENAME\Controller\ClassName;

/**
 * Implements hook_cron().
 */
function NEW_MODULENAME_cron() {
 generate_excel_files_callback();
}

function generate_excel_files_callback(){
 $obj = new ClassName();
 $obj->generateXLSX();
}


Sending email notifications to all editors the content's editorial section on content state change

I don't know what the "editorial access control" is but if you don't find any easier solution you can always write your own rules action for generating the list of people you need. In my case I am sending a message to the reviewers that are provided in one of the fields of the content. It should be easily adaptable to any other porpoise.

/**
 * Implements hook_rules_action_info().
 */
function mymodule_workflow_rules_action_info() {
  $items = array();
  $items['mymodule_workflow_reviewers'] = array(
    'label' => t('Get reviewers'),
    'group' => t('Windbench'),
    'parameter' => array(
        'node' => array('type' => 'node', 'label' => t('Node')),

    ),
    'provides' => array(
      'reviewers' => array('type' => 'list<user>', 'label' => t('List of reviewers')),
    ),
  );
  return $items;
}
function mymodule_workflow_reviewers($node){
  $reviewers = array();
  foreach($node->field_workflow_reviewers['und'] as $reviewer){
    $reviewers[] = user_load($reviewer['uid'],true);
  }
  return array('reviewers' => $reviewers);
}

And then use that action in your rules


Get the form to add a term to a vocabulary programmatically

$vocab_machine_name = 'tags';
$values = array('vid' => $vocab_machine_name);

$term = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->create($values);

$form = \Drupal::entityTypeManager()
  ->getFormObject('taxonomy_term', 'default')
  ->setEntity($term);

$term_form =  \Drupal::formBuilder()->getForm($form);

Shorter way
$vocab_machine_name = 'tags';

$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => $vocab_machine_name,
]);

$term_form = \Drupal::service('entity.form_builder')->getForm($term, 'default');


How to optionally redirect to a payment page after adding a node?

Step 1a: Optional redirect to payment page

Add a Boolean field to each content type for which you want to offer such "Promoted" option, say its allowed options are Yes or No.

Then use the Rules module like so:

Event: After saving a node
Condition: (both conditions must be true)

Entity has field "Promoted"
Data Comparison "Promoted" = "Yes"

Action: Perform a page Redirect to your Payment Page

Step 1b: Limit node access while payment is not completed

To wait for the payment to be completed (and not "submit" the node yet), you could use the Content Access module, and the Content Access Rules Integrations module.

So that "After saving content" (= Event), you "Give 'authenticated user' the permission to 'view own content' for the specific node" (= Action). This additional "Action" can be added is a 2nd action to the same rumle suggested above.

This would be a variation of what is explained in this article also (within "Access Control Customized for Your Needs").

Step 2: Promote the node (after payment)

After the payment is received, you could use that "Event" to trigger another rule, which basically consists of these actions:

Mark the node as "Promoted".
Remove the node access restriction, so that all appropriate roles can view the node.

Step 3: Stop the promotion of the node

If at some point in the future the "Promoted" node no longer should be promoted, then you could use the Rules Scheduler ( a sub-module of the Rules scheduler) to trigger a rule to no longer mark the node as "Promoted.

Note: If you're not familiar (enough/yet) with Rules, the checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.


Can I temporarily stop update notifications for one project only?

See Update Advanced module:

  Extends the administrative interface for Drupal core's "Update status"
  module. In particular, the per-project settings to ignore certain
  projects or even specific releases, is absent in the core version of
  the module. The "Update status advanced settings" module restores
  these settings, and might eventually provide additional functionality
  for the core "Update status" module.


The issue is caused by the insert module. The latest version (1.4) switched from using click to mousedown events, in this issue https://www.drupal.org/node/2295507

The patch submitted here (https://www.drupal.org/project/fancy_insert/issues/2955599#comment-12571625) should solve your issue, it basically switches from triggering click to triggering mousedown events as a way to connect to the insert module's functionality.

Here is the code change for reference:

diff --git a/fancy_insert.js b/fancy_insert.js
index 8325c96..0b99824 100644
--- a/fancy_insert.js
+++ b/fancy_insert.js
@@ -21,7 +21,7 @@ Drupal.behaviors.fancy_insert = {
-            $(this).parent().next().find(".insert-button").trigger("click");
+            $(this).parent().next().find(".insert-button").trigger("mousedown");

Good luck!


The reason that the route in system.routing.yml works is that it gets help by an inbound path processor service, which stores the filepath to a query parameter in the request:

PathProcessorFiles.php

<?php

namespace Drupal\system\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Defines a path processor to rewrite file URLs.
 *
 * As the route system does not allow arbitrary amount of parameters convert
 * the file path to a query parameter on the request.
 */
class PathProcessorFiles implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;
  }

}

This service is registered in system.services.yml:

system.services.yml

  services:

    path_processor.files:
      class: Drupal\system\PathProcessor\PathProcessorFiles
      tags:
        - { name: path_processor_inbound, priority: 200 }

And the controller gets the file path from the query parameter added by the processor:

FileDownloadController.php

  public function download(Request $request, $scheme = 'private') {
    $target = $request->query->get('file');
    ...

You can implement the same approach for your route to match everything after /example/.


IIS problem with Drupal - Update manager: Update failed! Directories are locked by php-cgi.exe

The reason for php-cgi for having the Lock is because of the "peculiar" way windows handles file access, and php/iis handles "caching".
Basically you just created the directory and tried to access it, but the handle that created it was not released (so it was still locked).
This is not a drupal issue, its an IIS/PHP issue
And there is no known workaround that I could find.

Basicly, do the base advise of not using IIS is the best, I have seen this problem in more than just drupal with IIS that I solved by moving to apache HTTPD (on win32).
Mind you that was for back at school, with a project where I was required to use windows 2000.

the best way I know of running drupal on windows is through apache (because of the internal handling of php).


Show menu links for anonymous users only

Tried all the options to hide the menu item from authenticated users irrespective of the role, but admin always sees it. Did that using CSS and Menu Link Attributed module. Using the module I added a class to the menu link and then using the body class user-logged-in hid the menu item for logged in user.

I am still open to any other alternative and a better solution.


how do I load a single page in a sub theme?

Take a look at the ThemeKey module.  From the project page:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties.


In order to accomplish this task you need to create two attachments and tie them to your page.
First attachment should display 'Global: Result summary' result with all answered questions.
Second attachment should display Global: Result summary' result with all unanswered questions.


What is the difference between drupal/drupal and drupal-composer/drupal-project packages?

drupal/drupal

This is the main repository for the Drupal project and is used to generate the tarball which is available for download on Drupal.org. This package is not used (directly) if you are using Composer to manage your codebase.

drupal/core

This is a subtree split of drupal/drupal repository which contains everything in the parent repo's /core directory. This is the package that is used if you are using Composer to manage your codebase.

drupal-composer/drupal-project

This is a "scaffold" project and serves as a starting point for your root composer.json file. This package isn't maintained by the Drupal Association, but it has become the de facto standard for assembling a Drupal codebase with Composer. It does a few things:

It brings in the drupal/core package and couple other requirements needed to assemble and run a Drupal site (composer/installers, cweagans/composer-patches) and a few nice-to-haves (drupal/console, webflo/drupal-finder, ...).
In addition to the packages listed above, it requires the drupal-composer/drupal-scaffold package which is responsible for assembling all the stuff normally provided as part of the tarball that's needed to run a Drupal site that lives outside of the /core directory (index.php, update.php, etc).
Contains instructions for composer/installers that tells Composer where to put stuff like modules and profiles.
Defines the Drupal-specific packagist repository.

Typically, you don't require or clone scaffold projects. They are intended to be used as starting points for projects of your own. You would use the create-project command instead:

composer create-project drupal-composer/drupal-project

There are other scaffold projects out there with more opinions or different focuses (BLT, Drupal CI) and most D8 Distributions provide a scaffold project (Open Social, Lightning, Thunder, etc)


How do I setup multi sites in Drupal 7 using xampp

Thanks @Sumit Madan for your suggestion. My issue has been resolved now. I just append these lines in test/sites/default/settings.php:

  $sites['trial1.com'] = 'trial1.com';
  $sites['trial1.localhost'] = 'trial1.com';

  $sites['trial2.com'] = 'trial2.com';
  $sites['trial2.localhost'] = 'trial2.com';


Can you make a node title \ heading link to it's NID?

There are possibly few ways to do this.

Not sure if this actually works, but I think it does, you can install Display Suite and go to Manage Display tab and apply one of display suite's layouts to your "Full" view mode. After you do that, Display Suite will give you all the fields (including Title) on the Manage Display tab of that view mode. From there you just need to configure the fields and config the "title" field and check the option "Link title to node".

You could also do it from template files, I guess it qualifies as non-modular? For example in node.tpl.php or page.tpl.php (wherever the page_title is being printed) one can easily create a link to the current node if the $node object is available or if not the node ID's available from the URL always. From there it should be a pretty easy call to l():

<?php print l($page_title, 'node/'.$node->nid); ?>


EntityMalformedException: Missing bundle property on entity of type commerce_customer_profile

When you declare an entity and function entity_get_info($entity_type = NULL) is called, the next function cache_set("entity_info:$langcode", $entity_info)  is also called which stores the entity info in the cache table, so probably your change is cached in the database.

If you're  executing drush cc all and you have the same message error again, you can try several more things:

You can call this function entity_info_cache_clear()
https://api.drupal.org/api/drupal/includes!common.inc/function/entity_info_cache_clear/7.
Try executing SELECT cid FROM cache WHERE cid LIKE 'entity_info%' from MySQL command line and then DELETE FROM cache WHERE cid="entity_info:en" -> "en" or whatever depending or your language config.
Try truncating the cache tables:

You can do:

drush sqlc with

SHOW TABLES LIKE 'cache_%';

TRUNCATE cache_tablename;

in order to remove the cached data where entity info is stored. The content of this tables are regenerated programatically when you make a request.

That probably should works


REST Services module - Access denied for user anonymous

You need to make the user login who have the permission to view the list of user details using following Service API

http://yourdomain/endpointname/user/login

with follwing json data as arguments

{
"username":"username of the user who have the permission to view the users list",
"password":"password which matched with username"
}

After the successful login you need to get the CSRF token which will play the key role in all authenticated request. To get the token call the below mentioned API,

http://yourdomain/endpointname/user/token

You will receive a token, then add the token to your postman header for the key named X_CSRF_TOKEN. Then you can start to make the authenticated requests.


Is there a base module that implements the slide in, slide out behaviour like the Admin module?

Superfish is a great option for drop down menus, and you can customise the effects: http://drupal.org/project/superfish

or Nice Menus: http://drupal.org/project/nice_menus

You can also customise the admin menu to add common tasks, by editing the actual links list.


Rather than using a module, you can accomplish this via httpd's mod_rewrite as detailed here, here and elsewhere. The appropriate rules can be incorporated into the .htaccess file in Drupal's root. Once you are done, make sure that you check all the various components of the site - CSS & JS files, images, directories, clean URLs on/off, path aliases on/off and so on.


How to display a view link in another view?

You can use either of these modules:

Views Field View

  There are a lot of cases in views where you want to embed a list
  inside each row. One example could be, you have a list of groups, and
  for each groups you want to list the first and last name of all of
  their members.

Viewfield

  Viewfield provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.


How to display the profile page in Modal window

This tutorial might help you:
http://drupion.com/blog/10-steps-creating-ctools-modal-window-drupal-7


Yes, that's expected behaviour. From the hook_menu() docs:

  If there is no other registered path that fits the requested path better, any further path components are passed to the callback function.

Here's the bug report that was closed as "works as designed":

https://www.drupal.org/node/1091068


How to set blog post under event section in Drupal commons

Entity reference

Not sure if I correctly understand the question, but it sounds to me that using the Entity Reference module might be the solution you are looking for. Here's a quote from the module's project page:

  Provides a field type that can reference arbitrary entities

References

Another option is to consider the References module, which provides D7 versions of the 'node_reference' (and 'user_reference') field types, that were part of the CCK package in D6.

Recommended tutorials

If these module don't help for what you're trying to achieve, then reviewing the amazing set of videos to Learn Organic Groups might help somehow.


CKEditor configured MediaEmbed button doesn't appear in toolbar

I managed to resolve my problem but didn't have time to post it in here. It was simply misconfiguration...

First you need to install Widget, Lineutils and oEmbed plugins in CKEditor's plugin folder.
Then you need to specify the path to the plugins folder in CKEditor's module configuration.
Finally, in each of CKEditor's profile, you need to enable the plugins and move the oEmbed icon to the profile's toolbar.
Clear Drupal and browser cache and it should be working.

That's it!


There are typically 2 ways of Rules debugging, as further detailed below.

1. Rules Evaluation Log

Within the Rules settings (located at admin/config/workflow/rules/settings in your site), experiment a bit with the debugging facilities that come with the Rules module. More specifically, within the "debugging" section of that page, you should change the value of "Show debug information" to "Always". Be aware also of what's mentioned at the end of that same debugging section, i.e.:

  Debug information is only shown when rules are evaluated and is visible for users having the permission Access the Rules debug log.

So double check (at admin/people/permissions#module-rules) that for the userid you're using you've granted the required permission.

Example of a Rules evaluation log

Here is an example of such Rules Evaluation Log:

URL to view the Rules Evaluation Log

There is not really "an" URL you can go find this log. Such Rules Evaluation log only gets displayed whenever "some Rules event happens" (for a rule that is enabled, disabled doesn't count ...). Like in my sample screenprint: that log is shown right after some user performed a login (because in this site there was an enabled rule that used event "User logged in"). Also, assume you just have 1 enabled rule, using a Rules Event X, then you need to "make something happen" in your site that triggers that Rules Event (if the event is not triggered, then you wouldn't see any logging data).

2. Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value". That's not within Rules Conditions (as in your question), but if you add that as your first Rules Action, then you can be sure that the values displayed are identical to the value of these variables at the end of the Rules Conditions.

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

3. Resources

Community documentation: Tools for testing & debugging Rules contains the official community documentation about Rules debugging.
Video tutorial: Refer to the (great!) video "Debugging rules configuration" for way more details about these 2 debugging variations.

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


Yes, it is possible.

If you want to use PHP in views header, you can go to configure header, select "Global: Text area" and have to change text format to PHP code; you have to first install the PHP filter module.

If you want to use PHP in view fields, you can use the Computed field module.

If you want to use PHP in a view itself, you have to customize your views and then you can easily add PHP code to it.


From where the execution starts in Drupal

index.php inside Drupal root folder is the starting point of execution. It calls the bootstrap functions. Please see the code inside drupal 7 index.php file below.

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();


Colors to my header and footer not applying by using color scheme options in my theme

I am able to apply css for my header and other things, I found an alternative way to include the css.Even though I can't find a way through drupal_add_css(), the following helped me in adding css.

This is the way I included dynamically generated css file which is located at sites/default/files/color/theme-768/color.css

In the theme folder in the html.tpl.php after <?php print $styles;?> include this

<?php
       print '<style>';
       print '@import url("' . $filepath . '")';
       print '</style>';
?>

This includes the css file and provided colors for header, footer etc.


You listed all the elements you need. You just need to swap out the set and get you were originally using with the ones you provided.

This:

$loop = $_SESSION['loop'];

Will become this:

$loop = Drupal::service('user.private_tempstore')->get('mymodule_name')->get('loop');

And this:

$_SESSION['loop'] = $loop + 1;

Will become this:

\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('loop', $loop + 1);

For your other elements, you can do the following.

This:

$_SESSION['code'][$loop] = $code;

Becomes this:

\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('code', [$loop => $code]);

And this:

$_SESSION['price'][$loop] = $price;

Becomes this:

\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('price', [$loop => $price]);


Better understanding of Drupal behaviors

In short, the advantage of Behaviors over document.ready() is that they are automatically re-applied to any content loaded through AJAX. mymodule is your namespace, which needs to be unique. context is the part of the page for which this applies, for example a part of a form that has been updated with AJAX. You can attach multiple behaviors, but I think you need to use a unique name (mymodule) for each of those.

Have a look at the following resources for more information:

Drupal behaviors
Drupal Javascript API
Changes in the Drupal JS API for D7


Add on domain does not have access to "../privatefiles" at public_html level

OK, I figured out what was going on and how to fix it.

The problem was indeed with the "../privatefiles" declaration for the private files directory. Just like for the old DOS files, the "../" means "one level up" and that is okay when the core file are in the www directory.

But when they are below or way below, the "../privatefiles" has to be replaced with the full path: "/home/whatever/privatefiles"

Now it works well.


Change directory where MySQL saves its data

Stopping the Acquia Dev server and moving/copying the files form the original data directory to the new data directory appeared to address the issue - thanks to cilefen for help

The following lines were updated to reflect the new location of the data directory

[mysqld]
pid-file="<<new path>>/data/mysql.pid"
log-error="<<new path>>/data/mysql.err"

and

#Path to the database root
datadir="C:/Program Files (x86)/DevDesktop/mysql/data"


Followed the How can I link an image of a jCarousel to a certain link? page but need further help

The field 'link' you have added is configured as a simple Text field from Content type field manager.

You need to choose Field Type as 'Link' while creating it. Then only you can find those options in views.

My suggestion would be to create a new field 'link' and add it to views.

Let me know if you still find issues. :)


How to use one field with different settings

Set the maximum number of values to unlimited.

Then using hook_form_alter change the categories select to only allow 1 value on the user profile form:

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

    //drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'user_profile_form':

            //dpm($form);
            $form['field_category'][LANGUAGE_NONE]['#multiple'] = false;
            break;

    }
}

If need be you could also add an additional validation handler here to add some custom server side validation to make sure that the user is not selecting more than 1 department.


Showing fields or content with Views - which is faster?

In D7 it is the same, because the node (or any other parent entity) needs to be loaded in order for a field to be displayed (that's how Field API works in D7).


show messages of drupal_get_form loaded forms in custom module

I'm posting the solution in case anyone else faces the same issue.

This was finally related to the template file.
The messages were printed in a section that was not rendered when inside my module page. This tricked me because doing it as admin was actually showing the relevant section but for registered users didn't.

So I just had to add an extra printout of the $messages var in a section of the template that was always rendered to all users.


What is the best practice to upgrade Drupal core without breaking the Git repo and the production website

It seems from discussion above that your question isn't about fixing your git repo, but about maintaining a Drupal site in git, and how that works with core updates.

I think that standard practice is in fact keeping all files in your repository, including Drupal core. The separation of Drupal code from custom code seems like a nice idea, but I don't think it's necessary, and I don't see what advantages it gives you. It also seems to assume that you will never want to patch core (or have to do it as a part of your deploy), which, while it isn't best practice, is definitely something you want to be able to do if something breaks in production.
Keeping your commits nice and focused also helps to get this kind of separation.

The solution I've used is to keep all code in the same repository, put as much as possible in Features or other kinds of exports/code/configuration, and maintain a list of patches that need to be applied to out-of-the-box core and contrib.

When you update core, start in your dev environment:

Make sure working directory is clean
Dump latest database (drush sql-dump). Either make a commit with the dump or save it somewhere safe.
Update core (drush up drupal)
Commit all changes.
Check patches file. If any patches need to be applied, apply them, and make another commit
Run update.php if necessary (already done if you used drush for the update)
Test your dev site. If everything is fine, push code to production. Run drush updb on production.
If there's a problem and you need to revert, either revert or reset your repo (git reset --hard HEAD~2 should do it), or revert the two commits if you want to keep the history. Replace your database with the dump.

The database dump is necessary because you otherwise can't undo changes made to the database by updates. You can also do the updating in a branch, in which case reverting just means checking out master. It's slightly inadvisable if you're working on one dev site because you can't really switch back to master and keep working there in parallel because of the database.

Using this more simple git-side workflow will allow you to use git's full power when you need it without the complication of submodules, etc. If this doesn't seem adequate, could you explain why you need further separation of code?


Render database values using 'markup tags' other than 'table tags'

As you do not like table.html.twig, I suggest to write your own table theme. As a reference, you can look how this is done for field_ui_table in core.

Or you use inline_template:

$content['table'] = [
   '#type' => 'inline_template',
   '#template' => '{%- for row_value in row -%}
 time {{ row_value }}
{%- endfor -%}',
   '#context' => ['row' => $row],
 ];


This could be solved by creating a simple view with VBO. Try this steps:

Create a view of content, without any filter criteria.
Add a relationship to the view of the reference field in the 'student' content type. Say 'field_invoice'.
Add a filter to the view of "content type", select 'invoice'. Use the relationship in the filter that was created in step 2.
Add a filter of "content title". Expose this filter. Use the relationship in this filter too.
Add a VBO field of type  "Bulk operations: Content (Content)". Select 'delete' from the operations.

From this view, you should be able to filter by name of any student. It will list the invoices. And using VBO, you should be able to delete them.


How to allow a block on a page to load another block on same page in Drupal 7?

As i understood from your problem, i think you can benefit from this lesson
Ajax node reader in drupal
http://www.youtube.com/watch?v=zyLmQtiSXgI

and there is a module called Ajax Blocks, can benefit u if u wnt to creat ur own module.

and as alternative solutions u can use
 http://drupal.org/project/colorbox_node
so the user profile loads in colorbox modal dialog


As far as I understand, you need to provide these values manually before the save, for example:

$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
$entity->uid = $user->uid;

or copy them directly from $form_state['values'].

I've found entityFormSubmit method from Inline Entity Form module which is manually copying all fields which are not fields to entity properties, so gave me the idea for this code:

$form_id = $form_state['build_info']['form_id'];
$entity = $form['#entity'] ?: $form_state['build_info']['args'][0];
$entity_type = $entity->entityType();
$entity_info = entity_get_info($entity_type);
$entity_values = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
list(, , $bundle) = entity_extract_ids($entity_type, $entity);

$values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values;
foreach ($values_excluding_fields as $key => $value) {
  $entity->$key = $value;
}
if ($entity_info['fieldable']) {
  field_attach_submit($entity_type, $entity, $form, $form_state);
}
$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
entity_save($entity_type, $entity);


How to catch username or password using hook_form_alter

You can use in VALIDATE function like

$form['#validate'][] = 'mymodule_user_validate';

In this you can all values even if there is no successful values in it.
But remember to call your function first before default validate function.


Although it is not a good idea to hide the errors (you may want to solve it; by watching the error log, debugging etc.), there is a way you can do it.

You can do it at theme level in template_process_page() function, in your theme's template.php file. (It should be placed in your admin theme's template.php)
Code: Edited according to @Chapabu 's comments :)
Used path_is_admin() and current_path().

<?php

function MYTHEME_process_page(&$variables) {
  if (path_is_admin(current_path())) {
    unset($variables['messages']);
  }
}

?>


Global Submission validation based on a select item

If I understood your question correctly, Webform supports this out of the box.

Edit the "app name" field and under "Validation" select the "Unique" checkbox:

  Check that all entered values for this field are unique. The same value is not allowed to be used twice.

This will make sure that each webform entry has a unique value for this field, meaning that duplicates will not be allowed.

UPDATE

Here is a sample code that will allow you to validate the webform submissions.

Create a new folder called custom in sites/all/modules, and then another folder called sample in custom.

Place the following in sample.info file:

name = Sample
description = Sample custom module that provides custom webform validation rules.
package = Custom
core = 7.x
version = 7.x-1.0

Place the following in sample.module file:

/**
 * Implements hook_form_alter().
 */
function sample_form_alter(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}

/**
 * Sample validation callback.
 */
function sample_webform_validate($form, &$form_state) {
  // Replace this with the name of your field, cid (webform component ID) and
  // nid.
  $field_name = 'select_something';
  $cid = 1;
  $nid = 4;
  // Check if this is a duplicate.
  $is_duplicate = db_select('webform_submitted_data', 'd')
    ->fields('d')
    ->condition('nid', $nid)
    ->condition('cid', $cid)
    ->condition('data', $form_state['values']['submitted'][$field_name])
    ->execute()
    ->fetchObject();
  if ($is_duplicate) {
    form_set_error($field_name, t('Duplicate value, please select something else.'));
  }
}


How can I concatenate two fields in a view?

Let's say you have field A, and field B.

Make sure A, comes before B in the fields list.
Edit field A, and check "Exclude from display". The field will now no longer show up.
Edit field B, find the checkbox for "Re-write the output of this field".
Below the new textbox, find "Replacement patterns." There you should now be able to find something that looks like [field-A], and [field-B], with possibly many more options.
Enter "[field-A] [field-B]" as the replacement pattern.

And you should have the fields concatenated.

There are some situation, where the markup generated by Views with this configuration is not desirable, as you will now have A "inside" B. If that's a problem, one can add a completely new dummy field, of type "Global: text", and to steps 3, 4 and 5 on that field instead.


How to change the field name in the url when using views exposed sort?

For order_by filter you can just set the filter identifier:

Although there is no option to set the identifier for sort_by filter, you can achieve your goal by altering the form.

Example

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

  if ($form['#id'] == 'YOUR-FORM-ID') {

    // fields which you want to rename
    $form_state['my_custom_names'] = array(
      'field_rating_value' => 'rating'
    );

    // rename option values
    foreach ($form_state['my_custom_names'] as $name => $new_name) {

      $form['sort_by']['#options'][$new_name] = $form['sort_by']['#options'][$name];
      unset($form['sort_by']['#options'][$name]);

      if ($form_state['input']['sort_by'] == $name) {
        $form_state['input']['sort_by'] = $new_name;
      }
    }

    // the custom submit handler need to be fired before the original one
    array_unshift($form['#submit'], 'my_custom_exposed_form_submit');
  }
}

/**
 * An additional submit handler for exposed filters.
 */
function my_custom_exposed_form_submit(&$form, &$form_state) {

  // set the form state values to their original names.
  foreach ($form_state['my_custom_names'] as $name => $new_name) {
    if ($form_state['values']['sort_by'] == $new_name) {
      $form_state['values']['sort_by'] = $name;
    }
  }
}

Make sure to replace YOURMODULE and YOUR-FORM-ID with proper names.


Using compass in Aegir limited shell (user o1.ftp)

For me it didn't work in combination with RVM. I needed to install it the normal way:

- apt-get install ruby
- apt-get install rubygems
- gem update --system
- gem install compass

I think that because of the isolated gem installs that RVM creates, the limited shell user has no access to the commands.


Views Better exposed filter, input required

Solved it by adding condition which yields no result.

hook_views_query_alter($view, $query) {
    // Don't show any result if exposed filter empty.
    $exposed_input = $view->getExposedInput();
    if(!isset($exposed_input['field_partner_address_country_code']) || $exposed_input['field_partner_address_country_code'] == 'All') {
      $query->addWhere(NULL, 'node_field_data.nid', 0);
    }
}


Set site URI for drush uli without 'default'

I'm writing this up for posterity, since the Slack is relatively ephemeral. Here's the current method, following Providing custom environment variables to a container:

In e.g. .ddev/docker-compose.environment.yml put the following:

version: '3.6'

services:
  web:
    environment:
      - DRUSH_OPTIONS_URI=http://my.ddev.local

Then ddev rm and ddev start to prove to see it working. (This works for drush uli inside the container, after ddev ssh.)


When using Entity Translation and the Title module, how can I get the translated term from the term ID programmatically?

The proper way to do this without circumventing the core API would be:

$tid = 322; // put here your term id
$term = taxonomy_term_load($tid);
$langcode = $GLOBALS['user']->language;
$translated_term = $term->name_field[$langcode][0]['value'];


Why are the Recent log messages not shown within admin/reports?

The "Recent log messages" is one of the submenu options located within admin/reports/dblog.

It becomes available after the core module dblog (Database Logging) is enabled.

If that core module is enabled, and it still isn't showing up, then it is probably because permission "View site reports" (within "System") has not been granted to the user trying to access that report.


How can I display 2 or more fields horizontally?

By using the Display Suite module you should be able to do this.

By default Drupal core wraps fields in multiple HTML elements. Display Suite allows you to override this markup via the user interface by using field templates. You can add CSS classes to the fields and start styling them in your CSS.

For more details, refer to the Community Documentation about Control markup with field templates.


Drupal 7 Faceted Search: Always show Facets

Under admin/config/search/search_api click “edit” on your search index and select “Facets”. Then for all facets that need the described behavior for their items, follow these steps:

Click “configure display”.
In the “Global settings” section, change the “Minimum facet count” to 0 (zero). Arguably this input field should rather be called “Minimum facet item count” …
“Save configuration”.

Now all non-matching facet items should remain in your facet list (with a zero count). As you have already mentioned, clicking such a facet item will return no search results anymore.


Error in php snippet using tokens: Show profile field if it isn´t empty

You must refer to the actual field in your snippet. Try something like:

<?php
global $user;
if (isset($user->profile-curso-basico[LANGUAGE_NONE][0]['value'])) {
  echo $user->profile-curso-basico[LANGUAGE_NONE][0]['value'];
} ?>


Show menu item to all users, prompt for credentials for anonymous

As you know, Drupal excludes menu links that the user doesn't have permission to view.

One way around this is to build a menu specifically for anonymous users using the same titles as your other menu, but all pointing to the /user/login?destination=my/view/path path. Once the that menu is built, you can create a menu block from it that only displays for the anonymous user role.

After adjusting the original menu block such that it only displays for the authenticated user role, you will effectively have menu items that display for both roles and prompts a user to login when viewing anonymously. For good measure, you might want to set your Basic site settings such that 403 requests are redirected to /user/login in case the user navigates to the views page directly.


How can I use the web service with one or none arguments?

Do you have an 'index' operation?
Take a look at the services.services.api.php file in services module, docs folder.

In the node resource, you have several different 'operations' ( retrieve, create, update & index, .. ).
Here's the snippet you should look at:

$node_resource = array(
    'node' => array(
      'operations' => array(
        ..
        'index' => array(
          'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
          'callback' => '_node_resource_index',
          ..
        ),
      ),
    ),
  );
  return $node_resource;

GET request to endpoint + resource will trigger 'index'. Read more about it here https://drupal.org/node/783254


Setting up Content Synchronization module

$app_root is the top directory of your website. The one where your index.php is located.

Therfore the ../content/sync is a location like this:

- content
    - sync
- public_html
    - index.php
    - (all the Drupal 8 files)

To add to that — this is probably done out of security reasons. Not to store your data from DB with the code. Same reasoning was followed for the Config Management core module.

And lastly - you have to make sure there is such a location on your server. Locate index.php, go one directory up and locate or create the content/sync path and try again.


Is it possible to customize site status messages?

The status type can be customised so you're covered with that one.

Assuming you're setting messages using drupal_set_message, you could check if the message should be set based on the status of the user. To make it a bit cleaner, you might want to write a module so you can set a specific permission to show this message to certain roles.


How can I remove items from the allowed values list of a select field that has data for the values?

I did something like this recently with the following approach.

Add the new allowed values.
Add a setting to configure "active" values.
Filter out the "inactive" values from display on the form.

e.g:

/**
 * Admin settings form
 */
function MODULE_admin_settings(){

  $form = array();

  // Select active preferences for display
  $field = field_info_field('field_preferences');
  $preferences = list_allowed_values($field);
  $form['field_preferences_active'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Active preferences'),
    '#options' => $preferences,
    '#description' => t('Select the preferences available for user selection.'),
    '#default_value' => variable_get('field_preferences_active', array()),
  );

  return system_settings_form($form);

}

/**
 * Implements hook_field_attach_form
 */
function MODULE_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {

  // Filter out inactive preferences
  if(isset($form['field_preferences'])){
    $preferences = variable_get('field_preferences_active', array());
    foreach($preferences as $key => $preference){
      // If this preference isn't checked, but is set in the field values, unset it.
      if(empty($preference) && isset($form['field_preferences'][LANGUAGE_NONE]['#options'][$key])){
        unset($form['field_preferences'][LANGUAGE_NONE]['#options'][$key]);
      }
    }
  }

}

This way the legacy data is preserved for reference, the form validates, and the data integrity is intact.


Having a look through the code of the module, the function that checks if the url parameter exists is this:

/**
 * Rules condition callback.
 *
 * Checks if the specified URL argument is set.
 */
function rules_url_argument_argument_exists($argument) {
  return !empty($_GET[$argument]);
}

This will return false if the argument is 0.

I think it should really be this:

/**
 * Rules condition callback.
 *
 * Checks if the specified URL argument is set.
 */
function rules_url_argument_argument_exists($argument) {
  return isset($_GET[$argument]);
}

Might be a good idea to submit an issue (and maybe a patch) in the modules issue queue.
I'm not exactly sure why the function gets the argument argument and doesn't use it
I have never used this module BTW.

EDIT:
There is also if (!empty($_GET[$argument_name])) { on line 71 of the module file that might need changing to isset.


Uploaded images broken with secure site turned on

This is because of Imagecache functionality, first URL is your actual size image, the second is your Imagecached image, Imagecache creates seperate image sizes depend on your image-styles that you defined so it can loads the proper image when you print it.

about the login issue, it must be because of your Secure Site module configuration


Invalid translation language (fa) specified

Basically, this error appears when some translation methods like $entity->getTranslation('LANGUAGE_CODE') or $entity->addTranslation('LANGUAGE_CODE') are called and there is no translation of the entity in the specified language.

The solution is to check if the entity hasTranslation using $entity->hasTranslation('fa') before calling the getTranslation or addTranslation like this:

if ($entity->hasTranslation('fa')) {
  $translation = $entity->getTranslation('fa');
}


Create a custom module and use the hook hook_menu_link_insert. Get the active user with global $user; and save the user + link id in a separate table.


Reset password via Services by email, and not by uid

It would be better if this was externalised into a custom module instead of 'hacking' the services module.

This is fine on my system

$definition = array(
  'user' => array(
    'operations' => array(
       ...
       'actions' => array(
          ...
         'password_reset_email' => array(
         'access callback' => 'services_access_menu',
         'callback' => '_user_resource_password_reset_email',
         'args' => array(
          array(
                'name' => 'email',
                'optional' => FALSE,
                'source' => array('data' => 'email'),
                'type' => 'string',
                'description' => 'The email of the user whose password to reset.',
        ),
    ),

Function is

function _user_resource_password_reset_email($data) {
  global $language;

  $mail = _services_arg_value($data, 'data');
  $account = user_load_by_mail($mail);

  if (empty($account)) {
    return services_error(t('There is no user with email @email.', array('@email' => $mail)), 404);
  }

  // Mail one time login URL and instructions using current language.
  $mail = _user_mail_notify('password_reset', $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  }
  else {
    watchdog('user', 'There was an error re-sending password reset instructions mailed to %name at %email', array('%name' => $account->name, '%email' => $account->mail));
}

  $result = "success";
  return $result;
}


How to link a view to the current language with a no results fallback to the default language?

Check out http://www.webomelette.com/drupal-views-pre-render-alter-display, u should be able to use hook_views_pre_render() in a custom module and check your result set before rendering.

In the case of no results, change language to sites default in the view object, although im not sure that this hook will trigger your new query to run and bring the default lang contents, but its a start!

http://drupalcontrib.org/api/drupal/contributions%21views%21views.api.php/7


How to get firstname in autocomplete when adding new members in og group?

I didn't get a clear idea, anyway please Check This.


User uid incrementing in non sequential manner

If it is exactly 10 then it might have to do with MySQL's Auto Increment value
https://stackoverflow.com/questions/1686327/change-the-step-auto-increment-fields-increment-by

drupal.org currently uses this feature for master slave replication. Right now all users and nodes being created have a odd value. If you look further back this value was EVEN at one point.


How do I add inline JavaScript to the footer?

Until Add support for inline JS/CSS with #attached is resolved, you should add a JavaScript file normally as a library defined in a MYMODULE.libraries.yml and then pass your module's config as Drupal settings from PHP to this JavaScript file.

foobar:
  version: VERSION
  js:
    js/myscript.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

Then in MYMODULE.module add the JS file and pass the config over to JS.

/**
 * Implements hook_page_attachments().
 */
function MYMODULE_page_attachments(array &$attachments) {

  $attachments['#attached']['library'][] = 'MYMODULE/foobar';

  // Pass values from PHP to JS.
  $attachments['#attached']['drupalSettings']['MYMODULE']['lorem'] = \Drupal::config('MYMODULE.settings')->get('lorem');
  $attachments['#attached']['drupalSettings']['MYMODULE']['ipsum'] = \Drupal::config('MYMODULE.settings')->get('ipsum');
}

Then in the JS file access them like following.

(function($, Drupal) {
  'use strict';
  Drupal.behaviors.MyBehavior = {
    attach: function(context, settings) {

      $('html').once('MyBehavior').each(function() {

        var lorem = settings.MYMODULE.lorem;
        var ipsum = settings.MYMODULE.ipsum;

        // Do whatever you need to do.
        // ...

      });
    }
  };
})(jQuery, Drupal);

I just found Inline JavaScript that is in an integration module in the docs. But it also says

  Using any inline JavaScript is highly discouraged. If you can use one of the examples above, please consider those before attempting to
  do this.


It seems like you are running a Drupal that was installed with the minimal profile. That profile does not create the Article and Basic Page content types. So, they are simply not there, clearing the cache will not help.

In order to get the content-types back you need to either:

a) Create them manually
b) Use the parts of the standard_install() function from profiles/standard/standard.install file that are additional to the minimal_install() function from profiles/minimal/minimal.install file to add the missing configuration. Kind of tricky, but not too much code there all in all.
c) Use the Features module to transfer the configuration of the content-types you are missing from another site installed using the standard profile.

N.B.: You know that already, but still, you should keep backups all the time, this may need a couple of try-n-error runs.

Good luck!


.inc files in Features - how are they being included?

Most include files exported by features are included on-demand by the modules that define that type of component.  For instance, example.views_default.inc is included by the views module when loading default views.  This is a common pattern in Drupal, not something that is specific to Features.


Remove 'Your Name' field from comments display

The name input is not a required field,  so the easiest thing would be to hide it using CSS.

Try the following:

.comment-wrapper .form-item-name { display: none; }

You could also use hook_form_alter().  Check for the $form_id  for the comment form,  then set:
$form['FIELD NAME GOES HERE']['#access'] = FALSE;


Setting values for custom display fields in Views

There are a couple of ways to go about this, if I understand your goals correctly:
1) If your view is set up to use Fields, you can customize the Subtitle field to include additional content along with what is coming from the Node's field.
To do this, Edit the view, Select the field, Expand "Rewrite results", and then you can use a Replacement Pattern token along with your additional text:

The subtitle is [field_subtitle], yes it is!

2) If your view is set up to display as a Node, you would create a Node template override, named like node-contenttype_with_subtitle.tpl.php, and you can format your layout specifically for your need here:

echo 'The subtitle is '.$node->content['subtitle']['#value'].', yes it is!';

Note that the 2nd approach would affect the appearance of that content type everywhere, not just in the view. So, if you want this special treatment of the subtitle only in your view, then the 1st approach may be preferable.

A third option would be a field-level override template, where you would create a file named something like views-view-field--subtitle--page.tpl.php and control your output there. Here is an in-depth look at that approach: https://drupal.org/node/352970

(Please let me know if I misunderstood your question, and I'll be glad to take another stab at answering.)


Is it possible to return form, themes, content in an array for my page callback function?

Remember that theme('table'.. returns HTML markup, so you are assigning a HTML string to the my_table key. In the example you linked drupal_get_form was being used which returns a renderable array, so it would have functioned correctly. Since render() doesn't know what to do with an HTML string, you must pass the render function the information before it has been turned into HTML:

return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_table' => array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
  ),
);


Drush db connection issues after upgrading to MAMP 4?

Figured this out by adding the following to my .bash_profile file and modifying the PHP versions to match what's in MAMP. Working just fine again.

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.4.45/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.5.38/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.6.25/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php7.0.10/bin:$PATH"

After this run:

source ~/.bash_profile


Create two nodes with url aliases on one submission

Use hook_node_insert() where you can additionally create another node. I am not sure that the url alias will already be available.
If not use the following code, found at Programmatically create alias using pathauto for node, to get the original URL alias and then edit it to match your criteria:
module_load_include('inc', 'pathauto'); // include the inc file for Pathauto module

/*
pathauto_create_alias($module, $op, $source, $data, $type, $language)
@param $module: Your module name
@param $op: The operation (insert, update, return, bulkupdate)
@param $source: Internal Drupal path (i.e.: node/1)
@param $data: Addition data used to generate a pathalias, in this case the node object
@param $type: Type of content that will be used to match a pattern, defined in the backend url alias patterns
@param $language: If you have a multlingual website, you need to pass the language for which you want to generate the url alias
*/

pathauto_create_alias('your_module_name', 'insert', 'node/1', array('node' => $node), $node->type, $language->language); // Language is optional

Set the node alias and create a node with node_save().


It means replace $_SERVER['REQUEST_URI'] with request_uri().

So module_get_url() needs to change slightly.

function module_get_url() {
  $uri = request_uri();
  return "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . "{$_SERVER['HTTP_HOST']}{$uri}";
}


How to let a role to change field formatter under view mode?

Your question was a bit unclear.
But for what I understood, try in this page:

  yourwebsite/admin/config/content/formats

To edit permissions of roles, go here:

  yourwebsite/admin/people/permissions


Join a select form with the number of the database to check

Change your options to this:

$options = array(
      '20' => '20',
      '100' => '100',
      '500' => '500',
      '1000' => '1.000',
...
  );

Then you can use the value directly. It'll be a number. Also you need a #default_value:

#default_value => variable_get('number_select', '20')


libraries-override:
  MODULE_NAME/LIBRARYNAME: false
  MODULE_NAME/LIBRARYNAME: false


How can I set a flag to be flagged unlimited number of times?

As Triskelion mentioned, the Flag module might be the wrong tool for your use case. Despite that, if you're looking to allow multiple flagging (instead a flag/unflag toggle) you can add a Unflag a Node action (or whatever your flagged entity is) to the other action you have on a flag event.


displaying taxonomy term as a header in a view

You should probably try to create a Taxonomy term View and not a Content View. Then, you could add a relationship (Taxonomy term : content with term) to fetch your node fields (or rendered entities). Add a taxonomy term filter to select your certain taxonomy term. Add a sort criteria based on descending post date (relationship with content). Display only 3 items. Finally, the taxonomy term name will become your View title and I guess you're done.


Which external frameworks does Drupal use, if any?

Theme-wise there are a couple of very good base themes that make use of SASS/Compass (and therefore Ruby) such as

Omega, and
Zen

(I prefer Omega, having just discovered its power).

There are some good integration modules such as LDAP for single sign on, and loads of third party service integrations from paid services such as MailChimp.

But, when it comes to handling the database and rendering pages, the core system really shines.  I'd really recommend learning Drupal's database API because it does an excellent job of defusing potentially unsafe queries and is quite easy to use once you get the hang of it.

[edit] Another resource I keep going back to time and again is the form API.


You should use like below:

$form['field_popin_text']['#states'] = [
  'visible' => [
    'select[name="NAME_OF_SELECT_LIST"]' => ['value' => '27'],
  ]
];


How to display custom field using Views module at front end

Views has the option of adding a custom field.
You need to search for global custom text field in the views
You can add a global custom text field as custom text field and alter the value using hook_views_pre_render(&$view)

function YOUR_THEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
      //  override the global custom text field value
      $view->field['nothing']->options['alter']['text'] = 'My custom text';
    break;
  }
}

Click on the add as shown in the Image

Then search for Global custom text field as shown in the Image

You will see global custom text field which is custom text for views and you can alter it using above code or u can alter by entering html text into configure option for the field as shown in the image below :


Display only selected term from content type in Views

Under your Views,

Add filter criteria > Has taxonomy term > apply

Vocabulary: your vocabulary in question > Apply

Is one of: Yes > Reduce duplicates > Apply

Save your Views.

HTH


Is there a module to create incentivized social media marketing conditionals?

I've never seen a module that does this.

You're going to have to be pretty familiar with Drupal, Commerce, PHP and the APIs of the platforms you'd like to use.

Because this question is so huge, it's not a good fit for this forum.  This forum is only for asking direct questions, with clearcut answers.


html--user.html.twig would be the template file used instead of html.html.twig when viewing a user profile (for example, for http://example.com/user/1). It is not the template file that shows the content of a user profile, but it's the template file that contains the basic structure of a Drupal page; in fact, its default content is the following one.

<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ attributes }}>
    <a href="#main-content" class="visually-hidden focusable">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

page.html.twig is the template file for a generic page; that is why you are getting a white page for user profile pages.

The template file for a user profile is user.html.twig, and its default content is the following one.

<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>

As you see the variable it receives are completely different from the ones the other two template files (html.html.twig and page.html.twig) receive. That is why using the wrong template gives you a blank page.


how to limit view to just show each type one time?

You can achieve this by following the steps given below:

Enable aggregation under Advanced Accordion of the view
Add Nid field & set aggregation type as Count Distinct
Exclude Nid field from display
Add news type field & set Aggregation type as Group results together, in Group Column select Value option from dropdown
Remove Publishing Date from sort criteria

Please check attached screenshot for reference

and for more information you can check this question


How to programmatically get the difference between two entities of same content type?

Either look at:

https://www.drupal.org/project/diff
https://www.drupal.org/project/html_diff

To easily "see" if changes exist. Or look at Migrates module track_changes implementation and implement it in code between revisions. All track_changes does is hash the fields of a content type together to get a unique ID. Different revisions of a node with changes between the body field will of course hash to a different value. Be sure to exclude node fields such as NID, vid, updated_at and other fields that (may) chnage between revisions.

Sample hash code from class MigrateSource:

// When tracking changed data, We want to quietly skip (rather than
// "ignore") rows with changes. The caller needs to make that decision,
// so we need to provide them with the necessary information (before and
// after hashes).
if ($this->trackChanges) {
    $unhashed_row = clone ($row);
    // Remove all map data, otherwise we'll have a false positive on the
    // second import (attempt) on a row.
    foreach ($unhashed_row as $field => $data) {
      if (strpos($field, 'migrate_map_') === 0) {
        unset($unhashed_row->$field);
      }
    }
    $row->migrate_map_original_hash = isset($row->migrate_map_hash) ?
      $row->migrate_map_hash : '';
    $row->migrate_map_hash = $this->hash($unhashed_row);
  }
  else {
    $row->migrate_map_hash = '';
  }


General architectural approach to Drupal for a project

This is a common grey area for new developers to Drupal. The root for every "page" is index.php. There is no "page" per se, every dynamically generated "page" is a container. Regions (found in either /themes/bartik/bartik.info file in Drupal 7 installations without any changes or additions to Drupal core yet) establish the sections of the container that you can add different types of content (i.e., blocks, menus, views, etal.) I would recommend reading about the bootstrap process for Drupal, it is during bootstrap that everything gets called on a url by url basis. Using the Drupal interface and adding modules adds ways to "generate" or "contain" different types of content. There are over 10,000 modules (and counting) to add functionality to the Drupal enviroment. There are, generally, a handful of recommended modules that provide the most cohesive and robust ways to develop almost anything within your Drupal site that are recommended.  This ultimate flexibility takes a little time to grasp and work with but once you do, you never want to go back.


Taxonomy term view with number of items for parent and child terms

I now have worked out a solution. You need to implement the taxonomy edge module. With that you can define a new relationship: Taxonomy term: child term. After that it's possible not only to count the number of nodes tagged with one term, but also the number of nodes tagged with the child terms of this term.

My nodes are always tagged with terms from the deepest level. So I have to consider the number of nodes tagged with the considered term OR the number of nodes tagged with the childs terms of the considered term (if available).

Completing my initial post, I add two relationships:

Taxonomy term: Child terms (Identifier = Childs)
(Childs)Taxonomy Term: Content with term (Identifier = node_childs)

I further add one field:

(node_childs) COUNT (Content: Nid)

In the field settings, i set these fields inline:

Taxonomy Term: Name
(node) COUNT (Content: Nid)
(node_childs) COUNT (Content: Nid)

The field (node) COUNT (Content: Nid) is excluded from display.
In the field (node_childs) COUNT (Content: Nid) I set the No-results-behavior to the token [nid].

The effect is that either the considered term has child-terms, then the number of nodes tagged with the child terms is counted. Or the considered term has no childs, than the number of nodes tagged with the considered term is counted.


Mainteance Mode Causes CSS to be removed

Create a maintenance template file and place it in your theme folder. It's probably using a parent theme maintenance template or just the regular core one.


How to permit one sub admin to change passwords of other certain users?

Thanks to arpitr and my coworker J., I finally did it with a form on a page which is accessible only to selected roles via hook_permission(). The desired array() of uid=>name of that certain role to pass on as select list #option comes from db_select(), which definitely was the most difficult thing to get:

function _get_users_by_role($role_name) {
  $query = db_select('users', 'u')
    ->fields('u', array('uid', 'name'));

  $query->innerJoin('users_roles', 'ur', 'u.uid = ur.uid');
  $query->innerJoin('role', 'r', 'ur.rid = r.rid');
  $query->condition('r.name', $role_name);

  $result = $query->execute()->fetchAllKeyed();

  return ($result) ? $result : array();
}

For those interested in the custom block approach arpitr proposed, check the accepted answer on How can I display a change password form on its own? for a even more detailed description.


You are in your own namespace, that means PHP by default tries to load the class from your current namespace.

To load a non-namespaced class, you need to explicitly refer to the global namespace with a :

\PHPExcel_IOFactory::load($excel_filepath);


Link to create a node, save it, and then go to the edit page

I think the simplest way is to save the node right after you've created it in a custom version of NodeController::add():

  public function add(NodeTypeInterface $node_type) {
    $node = $this->entityManager()->getStorage('node')->create([
      'type' => $node_type->id(),
    ]);

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;
  }

Edit:

Because building the form directly with the saved node doesn't work, return a redirect response for the node edit form:

    $node->save();
    return $this->redirect('entity.node.edit_form', ['node' => $node->id()]);


Looking for either "Date Field Popup Widget (Views Filtering)" or "Date Field Reference (with Popup widget)"

Date Restrictions provides restrictions on allowed values based on several criteria. It still doesn't implement filtering by views results, but you may give it a try.


Perform "Add to cart" through web services

I have found a similar post on stackexchange, which is little bit helpful.
Click here!

But there, they have used commerce line item's ids which will not available in my case because how could we know the lineitem's id before submitting it to cart ?.

Found the below solution for my above query.  But I am not sure, what are the standard way to implement this.

1) First I have to create an cart order using commerce services module.
http://localhost:8080/drupal7/serviceendpoint/cart

2) Second I have to create new line item and attach it to the order created above using the same module.
http://localhost:8080/drupal7/serviceendpoint/line-item

In that way I am able to create a new order with line items.  But I will appreciate if anyone could suggest me a clean, better and a proper way.


Upload image to server using FTP or via some file manager module, like IMCE, elFinder, etc.
I strongly suggest put it in somewhere inside /sites/default/files (sub)directory.
Navigate to admin/structure/block/add to start creating new block
Set empty title
For body field select format 'Full HTML' and enter code
<img src="/sites/default/files/YOUR_IMAGE_NAME.jpg" alt="IMAGE_DESCRIPTION"/>
From region selection list, select 'Sidebar second' or similar
Below you can set the details of where block will be displayed (optional)
Click 'Save' button


how to make a custom module that has three forms on one page

Yes you can create as many as forms in one page.
One method is using drupal render function.
Example:

$f = drupal_get_form('call_your_form');
$f1 = drupal_get_form('call_your_form1');
echo  drupal_render($f).drupal_render($f1);

Like this you can display any number of from in one page.


Drupal 8 Image Styles Not Generating - LEMP on CentOS 7

I finally found a solution to this problem! As it turns out, systemd is configured to give php-fpm a private /tmp. I had to edit the .service file to set PrivateTmp=false. It is worth noting that if you're running multiple sites on of the same server, PrivateTmp should be set to =true for security reasons.

For reverence, here is the thread that saved my rump in the end.

Thanks again.


The body contains tokens set when you press an embed button in ckeditor.

This raw body content is processed by this filter:

http://cgit.drupalcode.org/entity_embed/tree/src/Plugin/Filter/EntityEmbedFilter.php

 public function process($text, $langcode) {
    $result = new FilterProcessResult($text);

    if (strpos($text, 'data-entity-type') !== FALSE && (strpos($text, 'data-entity-embed-display') !== FALSE || strpos($text, 'data-view-mode') !== FALSE)) {
      $dom = Html::load($text);
      $xpath = new \DOMXPath($dom);

      foreach ($xpath->query('//drupal-entity[@data-entity-type and (@data-entity-uuid or @data-entity-id) and (@data-entity-embed-display or @data-view-mode)]') as $node) {
        /** @var \DOMElement $node */
....

You would have to build a view mode in ui with only the body field or apply the filter in code.


How to use the "Render Views filters as select list" option in an Entity Reference field?

1.  "Entity selection Views" helps you to deal with options list in the entity reference widget (on node add/edit form). E.g. if you want to reference some nodes that have specific term reference. Entity reference view can help you you.

As I see you want to reference "child" Trait nodes of special category to one "parent" Trait node. (At list your View shows it). In this case you don't have to use contextual filter. You can use ordinary "filter criteria" and set target category value.

2. "Render Views Filter as a select List" - it's not a widget for your content type add/edit form. But it's a widget for exposed filter in views. If you want to use this field as an exposed filter in views by default it's an autocomplete. But this option makes filter as select widget. If you read the "Render Views Filter as a select List" description, you might see that developers advice you not to use this option if you have more that 100 referenced entities. Just imagine a select widget with 100 options and query with WHERE condition. Just mind it.


Add an item to a checkbox in a content type

Click on "field settings" in the top right hand corner of that screen. That's where storage specific options are held.

If you can edit the options there then it's a simple text list. But it may be that field is referencing a taxonomy term or content/entity but that tab will lead you in the right direction to add an item


It's not a Drupal error it's a MySQL error. CAST() won't accept INT as a valid type but does give you a choice between SIGNED and UNSIGNED to cast to an integer type.

The following query runs fine for me in Drupal:

SELECT * FROM node ORDER BY CAST(nid AS UNSIGNED)


Content type 'Product Display' not available when creating new View

For D7, Commerce 1, unless you use Commerce Kickstart, you have to manually create it. Follow this tutorial.


Yes, use hook_entity_bundle_field_info_alter and when you add a constraint to the field (and not to a item or property), your constraint gets the entire field item list, so you can check how many items you have of which type, see FieldConfigInterface::addConstraint:

function mymodule_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && $bundle == 'page') {
    $fields['field_paragraph']->addConstraint('MymoduleParagraphTypes');
  }
}

Example for a constraint restricting the field to four paragraph items of a specific type:

  public function validate($items, Constraint $constraint) {
    $paragraphs = array_filter($items->referencedEntities(), function ($paragraph) {
      return $paragraph->bundle() === 'image';
    });
    if (!empty($paragraphs) && count($paragraphs) != 4) {
      $this->context->addViolation($constraint->errorMessage);
    }
  }

You can generate the constraint with the Drush command:

drush generate plugin-constraint


Disable or remove permissions for Scald page display

This is a partial answer, simply blocks non-logged in visitors:

function MYMODULE_init() {
  // Prevent public users from seeing the atom pages
  global $user;
  if(arg(0) == 'atom' && !$user->uid) {
    drupal_not_found();
    exit;
  }
}

I would really like it if there was a permission on the scald module, logged an issue on d.o for that https://www.drupal.org/node/2512692.

Edit: there is a patch on that d.o issue which adds a permission to 'access atom page view', which is a better solution to the use of  hook_init() above.


how to add a class div on drupal 7 webform element?

You are using the incorrect keyword, the correct way to add a prefix to the webform field is:

$form['submitted']['chinese_name']['#prefix'] = '
';
$form['submitted']['chinese_name']['#suffix'] = '
';


How can I set node/entity references automatically using rules?

For what it's worth, you can do this with entity references & rules alone. Nodeone.se has a video covering exactly this scenario.
Relation has great potential, and is a much more intelligent way to go about relationships, but it can be tough to use (especially for non-devs) because it lacks a strong way to make new references.


What is the feasibility of using Entity Reference instead of Taxonomy?

Is there really a performance difference?

For sure! Totally different and independent pieces of code was used for it, so there must be.

  Can it be quantified?

You can measure it, but because taxonomy is pretty well defined, and references are open to configuration, your mileage will vary. Overall, taxonomy is older, and optimized for speed - a lot of terms on one node is common. Also, it's easier to optimize something that works only one way.

  I need hierarchy support. Is there a good option? Searching around, the land of Entity Reference hierarchy options exists but seems like a wild west at this point.

Exactly! Everyone consider different things good, so implementations vary. I don't know what your "good" means, so I can't tell if it happened to be similar to one of already implemented "good".

  Are there better solutions if my only complaint is site admin UX?

Again - it depends on what exactly you consider better. There are things like Taxonomy Manager, but it addresses things it's creator considered that need to be addressed, in a way that's better - for him.

  Taxonomy is the best-practice, as it is in core, for the general use case.

Not really... But that was a claim, not a question anyway.

  I'm wondering what else I haven't considered in going off the beaten path here.

And this is simply too broad for Q&A


How to create a content type that incorporates a batch upload and body field, with a gallery output

You could make an image field accept multiple values and set its display to be gallery using one of that two modules galleryformatter, field_slideshow

And build a view list nodes ordered by the date field selecting one image image from the image field as a thumbnail (using relationships) by setting the delta to be just 1

take a look at how-control-display-multi-value-fields-drupal


Sum of integer vaules of a multi value field using Computed Field Module

I don't have computed field installed anywhere so I can't test this, but the logic should be something along the lines of:

$field_items = field_get_items($entity_type, $entity, 'field_calories');

$total = 0;
foreach ($field_items as $item) {
  $total += $item['value'];
}

$entity_field[0]['value'] = $total;

Or if you absolutely need a one-liner:

$entity_field[0]['value'] = array_sum(array_map(function($a) { return $a['value']; }, field_get_items($entity_type, $entity, 'field_calories')));


"Notice undefined index" for an existing element in $form array

Your function is called for all forms in your Drupal. $cartId = $form['product_id']['#value']; is called outside if, so it's also executed on all forms. And most of them does not have $form['product_id'] defined at all. Move that part inside if block.


how to index unpublished nodes to apache solr

By default, with the Search API, it indexes unpublished nodes unless you specify it not to. There is a patch to change the behaviour in the workflow tab of the search api: https://drupal.org/node/1507882

Can you please clarify your setup? Are you using the Search API?


How can I add the +0430 timezone to Drupal 6?

I think this looks like a problem in PHP. The timezone is being used by the Date module, and that contains date_timezone_abbr(), which uses PHP's timezone_abbreviations_list().

Only the keys are stored, and the PHP function is being used. I am afraid there is no way out of this, unless there is a way to convince PHP.

When I tried the following code, I get 4, not 4.5.

$a = timezone_abbreviations_list();
echo $a['aft'][0]['offset'] / 3600;