debug_backtrace and _drupal_error_handler_real with very high mem usage, can I disable?

_drupal_error_handler_real() is the function called from the error handler installed from Drupal (_drupal_error_handler()). A PHP error handler is called every time there is a not-handled runtime error (not an exception), including a warning.

The code execute from _drupal_error_handler_real() is the following one. debug_backtrace() is always called, if the error level is one set in PHP.

  if ($error_level & error_reporting()) {
    $types = drupal_error_levels();
    list($severity_msg, $severity_level) = $types[$error_level];
    $caller = _drupal_get_last_caller(debug_backtrace());

    if (!function_exists('filter_xss_admin')) {
      require_once DRUPAL_ROOT . '/includes/common.inc';
    }

    // We treat recoverable errors as fatal.
    _drupal_log_error(array(
      '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
      // The standard PHP error handler considers that the error messages
      // are HTML. We mimick this behavior here.
      '!message' => filter_xss_admin($message),
      '%function' => $caller['function'],
      '%file' => $caller['file'],
      '%line' => $caller['line'],
      'severity_level' => $severity_level,
    ), $error_level == E_RECOVERABLE_ERROR);
  }

Also _drupal_log_error() is called when debug_backtrace() is called, but without any module recording the error, the error is not effectively recorded. In fact, the error is recorded if there are modules implementing hook_watchdog(), such as the Database logging module, and the Syslog module. The task of watchdog(), the function called by _drupal_log_error() is pass the information about the error to the implementations of hook_watchdog() which are then free to record the error.

// Prepare the fields to be logged
$log_entry = array(
  'type' => $type,
  'message' => $message,
  'variables' => $variables,
  'severity' => $severity,
  'link' => $link,
  'user' => $user,
  'uid' => $user_uid,
  'request_uri' => $base_root . request_uri(),
  'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
  'ip' => ip_address(),
  // Request time isn't accurate for long processes, use time() instead.
  'timestamp' => time(),
);

// Call the logging hooks to log/process the message
foreach (module_implements('watchdog') as $module) {
  module_invoke($module, 'watchdog', $log_entry);
}


How to get Views Total number of records in Page.tpl.php file. (Before Views rendered)

You could use this code to print the count.

<?php

$view = views_get_view( 'test' );
$view->set_display('block');
$view->set_arguments( array( 1, 2, 3 ) );
$view->execute();
$count = count( $view->result );
print $count;

?>


Here is an idea, which I have not tried yet.

Sometimes you have tokens in combination with text formats. E.g. in commerce_checkout_completion_message_pane_checkout_form() the token replacement happens first, before the text format is applied. I am not sure if I agree with this order, but in this case it gives us some interesting options.

You could define a custom text filter which detects and evaluates markup like this:

{if true}hello{else}goodbye{endif}

and then you can use tokens to insert the true/false.

{if [token-which-returns-true-or-false]}hello{else}goodbye{endif}

This still leaves a lot in the open. Most tokens do not produce true/false, so maybe instead you want real equation formulas. But it is a direction you can explore further.


Localize nearest store to a zip code in Drupal 7

Need to use set proxmity in views and Dependencies modules are
Geolocation Field, Views.


custom hash generated password and module wise added db password is different?

Yes, that is correct: The password is always salted with a different string.

If you want to verify a password, don't hash it, just check it against the value that was stored, that does work.

You're probably asking the wrong question. Explain what you're actually trying to do.


Add multiple fields in +Add more button causes problem in sequence

The answer is - you really shouldn't try. The logic behind your form now shows one person with two Names and two SurNames. What you want, I bet, is two persons with one Name and one SurName each. So just group Name and SurName in fieldset and you're good.

If you insist on not doing it, read further. You use $form['names_fieldset']['name'][$i] and $form['names_fieldset']['surname'][$i]. It means $form['names_fieldset']['name'] is created before $form['names_fieldset']['surname'], so everything you put in it will be together and before surname. Just swap indexes and make them look like this: $form['names_fieldset'][$i]['name'], $form['names_fieldset'][$i]['surname'] and you'll be good. Of course $form['names_fieldset'][$i] can be a fieldset by itself, so we are back to first paragraph.


Why is suggested not to use symlink for sites/all and sites/default?

You'd have to ask Pantheon to be 100% sure (they even did the initial development of the module). However, the warning message in response to a situation where sites/all is a symbolic link, is:

  Avoid changing Drupal's site structure; remove the symbolic link and recreate sites/default.

So I think it's safe to assume this is just warning you not to mess with the structure of a Drupal site, which would probably cause problems or unexpected results when updated in future.


Can i create custom content type without define .yml file in module?

If your content type is fairly straight forward (i.e. using only Drupal's fields), you can create the content type within the http://localhost/admin/structure/types/add link and once you have it built the way you want it you can export it via: http://localhost/admin/config/development/configuration/single/export.

It will even give you the name of yaml file to boot!

If that avenue is not sufficient then you can follow: This tutorial about building custom drupal content entities; it is lengthy in nature, which is why I will elide the details.

And if you're going to use that tutorial, then I would suggest using drupal console to generate the boilerplate code for you.  It makes things quite simple.  Drupal Console, among other things, manages the generation of content entity boilerplate code.  It is quite helpful.


This is actually due to a change in Commerce 1.13 that we didn't have a great way to overcome initially. (More information at: https://www.drupal.org/node/2697017). The issue is with the settings for the product reference field on your node type. If you edit it, you'll find an options list limit setting that you can increase to see the more complete list of products again. Sorry for the regression. :-/


Access multiple values by index in a view

For that you need to check the Group multiple values and then set to show 1 values  and set starting from 1. see the below screenshot for clarification

if you check the rewrite output of this filed you can see the token for that filed, for your case it would probably

  [field_product_image_1]

So if you want to retrieve the image separately from the array, you have to do the above steps for each image, for example if you want the 3rd image, then you have to set starting from 2 and its tokes is [field_product_image_2], if you want 4th image, then you have to set starting from 3 and its token is [field_product_image_3].

Below screenshots will help you to understand easily.

I added each filed separately to retrieve each image

and its tokens and above method is for Drupal 6, you can do it in the same way for D7.


What does typical beginning mark in *.tpl.php files mean?

It is a placeholder, that is automatically replaced by CVS and then contains information about CVS version, author and so on of the file. For more information, see http://badgertronics.com/writings/cvs/keywords.html.

Since Drupal.org recently switched to Git as the version control system, this tag is now completely irrelevant so it can and should be removed. In fact, it has been removed automatically during the CVS -> Git migration for all modules on drupal.org


Want parent MENU_LOCAL_TASK tab to show when on a child page

You can do what you want, but you need to change the url structure a bit. If I understand you correctly:

control/jobs: List of all jobs, should be MENU_NORMAL_ITEM
control/jobs/%node (You should have a load function for the job, if not a node than something else), should be MENU_NORMAL_ITEM
control/jobs/%node/view:  MENU_DEFAULT_LOCAL_TASK (doesn't have  a callback)
control/jobs/%node/download: The download page for a specific job, MENU_LOCAL_TASK
control/jobs/%node/settings: The settings page for a specific job, MENU_LOCAL_TASK

You can take a look at the node and user module to get an idea on how create tabs in Drupal


I'm seeking clarification but I'll go ahead and add this here:

As you commented, you can use hook_field_widget_properties_alter() like this:

function important_dates_field_widget_properties_alter(&$widget, $context) {
  // kpr($widget);

  $pageCheck = FALSE;
  $formPath = 'my/form/path';
  if ($formPath == current_path() || $formPath == request_path()) {
    $pageCheck = TRUE;
  }

  if ($pageCheck) {
    // switch from options to autocomplete
    /*if ($widget['type'] == 'options_select') {
      $widget['type'] = 'taxonomy_autocomplete';
      $widget['module'] = 'taxonomy';
    }*/
    // switch from autocomplete to options
    if ($widget['type'] == 'taxonomy_autocomplete') {
      $widget['type'] = 'options_select';
      $widget['module'] = 'options';
    }
  }
}

You can not define multiple widgets for a field.  You can, however, create another field of type "Term Reference" and choose a different widget.


How to set multiple entity references as default values using the hook_form_alter()

You can use Fivestar and Voting API for rating the product

The Fivestar voting module adds a clean, attractive voting widget to nodes and comments and any entity


Here is the solution. I knew as soon as I asked the question I would find the answer!

First off, the query building code must not run pager_default_initialize, like so:

$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_find_page();

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

The pager render array should be created like so:

$content['results']['pager'] = array(
  '#pre_render' => array('CUSTOM_PRE_RENDER'),
  '#theme' => 'pager',
  '#variables' => array(
    'total' => $total,
    'per' => $per,
  ),
);

And then run pager_default_initialize in the custom pre render function:

function custom_pre_render_intialize_pager($_element) {
  pager_default_initialize($_element['#variables']['total'], $_element['#variables']['per']);

  return $_element;
}

This code will only work to add a single pager to the block and may not work if there is more then one pager on the page.


Running drush up to several sites folders at once

First off, look to the trivial solution:

#!/bin/bash
drush @site1 up -y --no-backup
drush @site2 up -y --no-backup

You don't need to install Ansible to start automating; simple bash scripts can be used to combine repetitive tasks very easily.  If you are on Windows, you can install Git for Windows, which includes a Bash shell, or, if you really don't want to install anything at all, use a .bat file.

There is also a Drush solution:  Drush can run the same command on multiple sites if you give it a list of aliases:

drush @site1,@site2 up -y --no-backup

If you have a lot of sites, you can make a site alias that is a list of site aliases:

<?php
$aliases['mine'] = array(
  'site-list' => array('@site1', '@site2')
);

Then:

drush @mine up -y --no-backup


How can I include a third party library in my custom module without using Composer Manager

General: Composer Merge Plugin

In your Drupal's main composer.json you can use the Composer Merge Plugin to scan certain directories for composer.json files and merge them into your main composer.json.

You'd then have a composer.json in your custom module requiring the 3rd party library. In your root composer.json you require the merge plugin and configure it under the extra section to include certain directories.

{
    "require": {
        "wikimedia/composer-merge-plugin": "dev-master"
    },
    "extra": {
        "merge-plugin": {
            "include": [
                "web/modules/custom/*/composer.json"
            ]
        }
    }
}

Optional: Composer Custom Type Installer

If the 3rd party library in your custom module is available on GitHub and you want to define a location where the lib should to be downloaded to (extra helpful especially for all front-end libs) you can use Composer Custom Type Installer in your main composer.json.

You'd then require the 3rd party library in the repositories section in your custom module's composer.json assigning it a package type you pre-configured in the extra section of your main composer.json to define a location where the lib should be downloaded to.

"repositories": [
    {
        "type": "package",
        "package": {
            "name": "select2",
            "version": "4.0.3",
            "type": "theme-library",
            "source": {
                "url": "https://github.com/select2/select2.git",
                "type": "git",
                "reference": "tags/4.0.3"
            }
        }
    }
]

And the corresponding extra section in the main composer.json:

"extra": {
    "custom-installer": {
        "theme-library": "web/themes/custom/MYTHEME/libs/{$name}"
    }
}

Of course, for simplicity you could also do everything (composer-merge-plugin and custom-installer and requiring the GitHub repo) just from you main composer.json. I'd recommend that.

If you do so, then run at least once composer require PACKAGENAME (in my example composer require select2) after you manually incorporated the lib into the composer.json file.

Last but not least, don't forget to bind your library with MYMODULE.libraries.yml and hook_page_attachments (latter called from MYMODULE.module). See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.


How can I turn several Fields into a menu via a View?

OK, so the only way I could do this was to adjust the Features .module file to register both a theme and a CTools plugin:

/**
 * Implements hook_theme().
 */
function mycomponent_theme() {
  return array(
    'mycomponent_links_menu' => array(
      'path' => drupal_get_path('module', 'mycomponent') . '/templates',
      'template' => 'mycomponent_links_menu',
      'variables' => array(
        'config' => array(),
      ),
    ),
  );
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function mycomponent_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner === 'ctools' && $plugin_type === 'content_types') {
    return 'plugins/content_types';
  }
}

Then, I needed to create an .inc file (mycomponent_links_menu.inc) to enable me to add the menu as a component. On that file I created the plugin, , eg:

$plugin = array(
  'single' => TRUE,
  'title' => t('Link Menu'),
  'description' => t('Displays links.'),
  'category' => t('Mycomponent'),
  'edit form' => 'mycomponent_link_menu_panel_settings',
  'render callback' => 'mycomponent_link_menu_panel_render',
  'defaults' => array(),
  'all contexts' => TRUE,
);

and rendered the panel to a block, grabbing each Field from the node's array:

function mycomponent_link_menu_panel_render($subtype, $conf, $args, $contexts) {
  $node_context = reset($contexts);
  $block = new stdClass();

  $field_text1_items = field_get_items('node', $node_context->data, 'field_text1');
  $field_text2_items = field_get_items('node', $node_context->data, 'field_text2');
  $field_text3_items = field_get_items('node', $node_context->data, 'field_text3')

  $panel_content = array(
    '#theme' => 'mycomponent_links_menu',
    '#config' => array(
      'link_to_something' => l(t('Something'), $field_text1_items [0]['safe_value']),
      'link_to_anotherthing => l(t('Anotherthing'), $field_text2_items [0]['safe_value']),
      'link_to_somthingelse' => l(t('Invision'), $field_text3_items [0]['safe_value']),
    ),
  );

  $block->content = render($panel_content);
  return $block;
}

Then I created a .tpl file that actually wrapped the rendered links in HTML, eg:

  <li class="menu__item">
    <?php print $config['link_to_somthingelse']; ?>
  </li>


I know this is a older issue but I found it when trying to do the same. Still for this exactly case maybe answer from xxx would be also helpful.

After it took me a while to figure out how to do it I wanted to share this example. Only thing needs to change is the first few lines.

/**
 * Add new property to all fields of type XXX.
 */
function XXX_update_80YY() {
  $field_type = 'XXX';
  $new_properties = array(
    'PROPERTY_NAME' => array(
      'description' => 'PROPERTY DESCRIPTION',
      'type' => 'varchar',
      'length' => 255,
    ),
  );

  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
  $field_manager = \Drupal::service('entity_field.manager');
  /** @var \Drupal\Core\Entity\EntityTypeManager $entity_type_manager */
  $entity_type_manager = \Drupal::service('entity_type.manager');
  $field_map = $field_manager->getFieldMapByFieldType($field_type);
  $schema = Database::getConnection()->schema();
  foreach ($field_map as $entity_type_id => $fields) {
    $field_manager->clearCachedFieldDefinitions();
    $storage_definitions = $field_manager->getFieldStorageDefinitions($entity_type_id);

    $storage = $entity_type_manager->getStorage($entity_type_id);
    /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = $storage->getTableMapping();

    foreach ($fields as $field_name => $field) {
      $storage_definition = $storage_definitions[$field_name];
      if (!empty($storage_definition)) {
        $column_names = $table_mapping->getColumnNames($field_name);
        $table_names = [ $table_mapping->getFieldTableName($field_name) ];

        if ($storage_definition->isRevisionable()) {
          $table_names[] = $table_mapping->getDedicatedRevisionTableName($storage_definition);
        }

        foreach ($table_names as $table_name) {
          foreach ($new_properties as $property_name => $property_spec) {
            if (!$schema->fieldExists($table_name, $column_names[$property_name])) {
              $schema->addField($table_name, $column_names[$property_name], $property_spec);
            }
          }
        }
        $definition_update_manager->updateFieldStorageDefinition($storage_definition);
      }
    }
  }
}


Remotes: Can a local Drush 8 be used to send commands to a remote Drupal 8.4 site which includes Drush 9?

I would assume install drush 9 locally to a project, but still use alias files for all your remote systems. eg, treat the local installation as a globally installed service conceptually.

if you dont like a random project on your system hosting drush this way stick it on a VM or Container and interact with drush there.


Count content types which have taxonomy term

You can use the following snippet, to get count of nodes by passing the term id

<?php
  $tids = array(1); //An array of term IDs to match.
  $nodes = taxonomy_select_nodes($tids);
  echo count($nodes) ;
?>

Edit:

You can use views to achieve this, check this similar question . It explains an example


How to place multiple blocks in one column in bootstrap theme

This approach might suit your case.

Create 2 new regions in your template info file and render them in your page.tpl.php

  If you are using a bootstrap subtheme, this file will be located in
  siites/all/themes/bootstrap/templates/system so you will have to copy
  it and put in your templates folder under you subtheme folder.
  Remember to clear the Theme Registry cache after this.

So I would do this like below

info file

regions[main_block] = 'Main Block Region'
regions[side_block] = 'Side Block Region'

page.tpl.php file

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

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

After go to the blocks admin interface and select the blocks to show on the correct region. Also for the Side Blocks render all three blocks you need in the Side Block Region and use the correct weights to sort them as you like.


The node's content isn't built when you load the node, you need to invoke it manually with node_build_content():

$node = node_load(2);
node_build_content($node, $view_mode);

// You now have access to $node->content


Drupal 7 Orphaned fields, how should they be deleted?

I recommend using drush for this type of thing and let the field crud api do the heavy lifting.
drush eval field_delete_field("YOUR_FIELD_GOES_HERE")


Category tags like drupal.org (Drupal 7)

There are a number of modules such as:

Nice Tags, here is an excerpt about it from the module's project page:

  ... improves seamlessly the UX for taxonomy tags input fields.

  No 3rd party JS libraries are required, as it works out of the box with jQ version shipped with Drupal.

Active Tags, here is an excerpt about it from the module's project page:

  ... adds a new option to free tagging taxonomies. If selected the taxonomy widget is replaced by a new jQuery enabled tag entry widget.

  Works with core Taxonomy module and Content Taxonomy module.

  This module came about through work on a site where some users found separating tags with commas confusing. Some users got it, and some didn't. This resulted in a site littered with concatenated tags. Wordpress has a similar tag entry mechanism where tags are entered separately. It has been implemented here using jQuery to rewrite the standard taxonomy entry form.

You can also use your taxonomies as tags as well if that's something you are interested in.


It is a known issue and there appears to be a patch for it: https://www.drupal.org/node/2720101


Is it possible to collect credit card info and address info on separate pages in Commerce 2?

Creating a checkout flow plugin may solve your problem. Create a Plugin in your custom module like an example shown below:

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutFlow;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowWithPanesBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @CommerceCheckoutFlow(
 *  id = "custom_checkout_flow",
 *  label = @Translation("Custom checkout flow"),
 * )
 */
class CustomCheckoutFlow extends CheckoutFlowWithPanesBase {

  /**
   * {@inheritdoc}
   */
  public function getSteps() {
    return [
      'login' => [
        'label' => $this->t('Login'),
        'previous_label' => $this->t('Return to login'),
        'has_order_summary' => FALSE,
      ],
      'card_info' => [
        'label' => $this->t('Card information'),
        'previous_label' => $this->t('Return to Card information'),
        'next_label' => $this->t('Continue to Card information'),
        'has_order_summary' => FALSE,
      ],
      'address_information' => [
        'label' => $this->t('Address information'),
        'previous_label' => $this->t('Return to Address information'),
        'next_label' => $this->t('Continue to Address information'),
        'has_order_summary' => FALSE,
      ],
      'review' => [
        'label' => $this->t('Review'),
        'has_order_summary' => TRUE,
      ],
    ] + parent::getSteps();
  }

}

After creating a plugin, you need to change the checkout flow settings for your order type.

For more information visit: https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-flow

Update

CustomCheckoutFlow

<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutFlow;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowWithPanesBase;

/**
 * @CommerceCheckoutFlow(
 *  id = "custom_checkout_flow",
 *  label = @Translation("Custom checkout flow"),
 * )
 */
class CustomCheckoutFlow extends CheckoutFlowWithPanesBase {

  /**
   * {@inheritdoc}
   */
  public function getSteps() {
    return [
      'login' => [
        'label' => $this->t('Login'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => FALSE,
      ],
      'card_information' => [
        'label' => $this->t('Card information'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => TRUE,
      ],
      'order_information' => [
        'label' => $this->t('Order information'),
        'has_sidebar' => TRUE,
        'next_label' => $this->t('Continue to Order information'),
        'previous_label' => $this->t('Go back'),
      ],
      'review' => [
        'label' => $this->t('Review'),
        'next_label' => $this->t('Continue to review'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => TRUE,
      ],
    ] + parent::getSteps();
  }

}

Then create CheckoutPanes as shown below:

BillingInformation

<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use \Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\BillingInformation;

/**
 * Provides the billing information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_billing_information",
 *   label = @Translation("Billing information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class CustomBillingInformation extends BillingInformation {

}

PaymentInformation

<?php
namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation as PaymentInformationBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides the payment information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_commerce_payment_information",
 *   label = @Translation("Custom Payment information"),
 *   display_label = @Translation("Payment information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class PaymentInformation extends PaymentInformationBase {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form = parent::buildPaneForm($pane_form, $form_state, $complete_form);

    // Add an after build callback in order to make modifications on the address form.
    $pane_form['#after_build'][] = [$this, 'paneFormAfterBuild'];

    return $pane_form;
  }

  /**
   * After build callback for the pane form.
   */
  public function paneFormAfterBuild(array $pane_form, FormStateInterface $form_state) {
    // Get billing form element. Where it is located depends on the payment method that is chosen.
    if (isset($pane_form['add_payment_method']['billing_information'])) {
      $billing_form = &$pane_form['add_payment_method']['billing_information'];
    }
    elseif (isset($pane_form['billing_information'])) {
      $billing_form = &$pane_form['billing_information'];
    }
    else {
      // No billing information found.
      return $pane_form;
    }

    // Get the address form element.
    $address_form = &$billing_form['address']['widget']['0']['address'];

    // Add element validation callback to autofill the address.
    $billing_form['#element_validate'] = array_merge(
      [[$this, 'profileSelectValidate']],
      \Drupal::service('element_info')->getInfoProperty('commerce_profile_select', '#element_validate', [])
    );

    // Set all address fields to non-required.
    foreach (Element::children($address_form) as $key) {
      $address_form[$key]['#required'] = FALSE;
    }

    // Hide the address form.
    $address_form['#access'] = FALSE;

    return $pane_form;
  }

  /**
   * Element validation callback for the profile select element.
   */
  public function profileSelectValidate(array &$element, FormStateInterface $form_state) {
    $billing_profile = $this->order->getBillingProfile()->get('address')->getValue();
    $form_state->setValue($element['address']['widget'][0]['address']['#parents'], $billing_profile[0]);
  }

}

PaymentProcess

<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentProcess as BasePaymentProcess;

/**
 * Provides the payment process pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_payment_process",
 *   label = @Translation("Custom Payment process"),
 *   default_step = "payment",
 *   wrapper_element = "container",
 * )
 */
class PaymentProcess extends BasePaymentProcess {

  /**
   * {@inheritdoc}
   */
  public function isVisible() {
    // This pane can't be used without the PaymentInformation pane.
    $payment_info_pane = $this->checkoutFlow->getPane('custom_commerce_payment_information');
    return $payment_info_pane->isVisible() && $payment_info_pane->getStepId() != '_disabled';
  }

}

After this set checkout panes for your custom checkout flow as shown in the image below:

Find full code at https://github.com/patilvishalvs/my_checkout_flow


How to update some field of all article nodes programatically and set it equal to its title?

hook_node_update - Respond to updates to a node. This is useful when you wants to update a field during node save. This will not helpful in this case because you wants to update all your exiting nodes.

1.Hope this code will helps you.
You will get an idea but this is not the exact code for copy and paste.

<?php
    // Get all nodes of 'article' type, populate the field with a value of '1'.
    $articles = db_query("SELECT nid, vid FROM {node} WHERE type = 'article'")->fetchAllAssoc('nid');
    foreach ($articles as $nid => $values) {
      $fields = array(
        'entity_type' => 'node',
        'bundle' => 'article',
        'deleted' => 0,
        'entity_id' => $values->nid,
        'revision_id' => $values->vid,
        'language' => LANGUAGE_NONE,
        'delta' => 0,
        'field_data_field_new' => 'title need to fetch',
      );
      db_insert('field_data_field_new') //data table name
        ->fields($fields)
        ->execute();
      db_insert('field_revision_field_data_field_new') //revision table name
        ->fields($fields)
        ->execute();
    }
    ?>

Another suggestion is Views Bulk Operations (VBO). You need investigate on it.
Bulk field update?
Updating a single field value for a particular content type:

 $article_nodes = node_load_multiple(array(), array('type' => 'article'));
    foreach ($article_nodes as $article_node) {
          $article_node->field_new[LANGUAGE_NONE][0]['value'] = 'title value';
          field_attach_update('node', $article_node);
        }


Exclude Items from Flat Rate Shipping Calculation

This a bit of a complex setup and would be best handled by creating a new inline condition offering the ability to compare the order total of line items of a particular product type to some value. That's really what should be done.

However, this can actually be done with Rules. (Doesn't mean that it should, but it can!)

How would you do this? Well, you'll need a couple of components and a reaction rule. Go ahead and create a free shipping discount with Discounts and then modify the rule that gets created. You'll need to disable the Free shipping action and replace it with something that looks like this: Note that you can't skip the creation of the discount altogether because it's still needed to apply the discount itself (it's down at the bottom in the final rule).

{ "commerce_discount_rule_discount_free_shipping_for_75" : {
    "LABEL" : "Free shipping for $75",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Discount", "Order discount" ],
    "REQUIRES" : [ "rules", "commerce_discount" ],
    "ON" : { "commerce_discount_free_shipping" : [] },
    "DO" : [
      { "component_rules_amount_of_hats_on_order" : {
          "USING" : { "order" : [ "commerce-order" ] },
          "PROVIDE" : { "aount" : { "amount" : "Amount" } }
        }
      },
      { "component_rules_free_shipping_if_order_total_met" : { "order" : [ "commerce-order" ], "amount" : [ "amount" ] } }
    ]
  }
}

This rule has two custom actions on it.

The first one calculates the total amount of the hats on an order (I built this on Kickstart 2.x so change to suit your needs). The title of the rule isn't as important as is that you'll need a component to calculate a new total you'll compare against.
The second action will be the one that actually does the conditional application of free shipping.

Calculating a total on a subset of products

To calculate a total, we need to loop through all of the line items on an order, and then, if the line item's product is of a certain type, add it to a running total. Since Rules out of the box doesn't have if statements, we can emulate that using another custom component inside of the loop which will conditionally the current line_item being inspected add it's value to the running total if our product conditions are met. This could actually be anything, not just product type.

{ "rules_amount_of_hats_on_order" : {
    "LABEL" : "Amount of hats on order",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "order" : { "label" : "Order", "type" : "commerce_order" },
      "amount" : { "label" : "Amount", "type" : "decimal", "parameter" : false }
    },
    "ACTION SET" : [
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0.0" },
          "PROVIDE" : { "variable_added" : { "running_total" : "Running total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_add_total_amount_of_line_item_to_total_if_product_is_of_ty" : {
                "USING" : { "lineitem" : [ "list-item" ], "total" : [ "running-total" ] },
                "PROVIDE" : { "total" : { "total" : "Total" } }
              }
            },
            { "data_set" : { "data" : [ "running-total" ], "value" : [ "total" ] } }
          ]
        }
      },
      { "data_set" : { "data" : [ "amount" ], "value" : [ "running-total" ] } }
    ],
    "PROVIDES VARIABLES" : [ "amount" ]
  }
}

Conditionally add a line item total to a running total

This is where most of the magic happens. This function is simple but could be expanded to do a lot of cool stuff. Currently, all it does is compare the product type to some value, but it could look at taxonomy terms, other fields... you name it! The gist of this rule is that it just does some comparison and then adds the line item value to the running total if it's met. It functions as an if statement. If the conditions are not met, the value doesn't increase.

{ "rules_add_total_amount_of_line_item_to_total_if_product_is_of_ty" : {
    "LABEL" : "Add total amount of line item to total if product is of type",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "lineitem" : { "label" : "Line item", "type" : "commerce_line_item" },
      "total" : { "label" : "Total", "type" : "decimal" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "lineitem" ], "field" : "commerce_product" } },
      { "data_is" : {
          "data" : [ "lineitem:commerce-product:type" ],
          "op" : "IN",
          "value" : { "value" : { "hats" : "hats" } }
        }
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "total" ],
            "op" : "+",
            "input_2" : [ "lineitem:commerce-total:amount-decimal" ]
          },
          "PROVIDE" : { "result" : { "result2" : "Calculation result" } }
        }
      },
      { "data_set" : { "data" : [ "total" ], "value" : [ "result2" ] } }
    ],
    "PROVIDES VARIABLES" : [ "total" ]
  }
}

Conditionally applying the Free shipping

Finally, now that we've gotten the product-subset total amount, we can test against that and then apply our free shipping. Note that this rule will have the comparison of the product total and that's where you'd change the amount to compare against.

{ "rules_free_shipping_if_order_total_met" : {
    "LABEL" : "Free shipping if order total met",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_discount" ],
    "USES VARIABLES" : {
      "order" : { "label" : "Order", "type" : "commerce_order" },
      "amount" : { "label" : "Amount", "type" : "decimal" }
    },
    "IF" : [
      { "data_is" : { "data" : [ "amount" ], "op" : "\u003E", "value" : "74.99" } }
    ],
    "DO" : [
      { "commerce_discount_free_shipping_service" : {
          "entity" : [ "order" ],
          "commerce_discount" : "discount_free_shipping_for_75",
          "shipping_service" : "standard_shipping"
        }
      }
    ]
  }
}


Is it possible to change the "add new comment" text on certain content types?

Check the roles/permission grid to restrict certain roles posting comments.

hook_node_view_alter(&$build) would help to replace the label with your custom one.

e.g.

 function MODULE_node_view_alter(&$build){
    if ( in_array($build['#node']->type, array('page')) )
    $build['links']['comment']['#links']['comment-add']['title'] = l('New Label', 'comment/reply/'. $build['#node']->nid);

There can be another easy way using String Overrides but it will not let you  do on specific content types.


How to disallow flags to get triggered if one of the user fields is empty?

Use the Rules module to implement what you're asking for, as detailed in the blueprint below ...

Step 1: Create a custom rule

Create a rule like so:

Event: after updating an account.
Conditions:

user does not yet have role (say) "abc".
check that none of those user fields are empty.

Action: grant access to a role (say) "abc".

For an example of a rule (in Rules export format) that is pretty close to what you need, have a look at my answer to "How to implement admin verification for selected user profile fields?".

Step 2: Tune the configuration of the flag

Adapt the configuration of your "Status" flag, so that you only authorize it to be used by ... euh ... indeed, users who have access to role "abc".

Happy flagging with Rules!


How do I disable Drupal 7 Theme Debug? "drush vset theme_debug 0" NOT WORKING

If using drush vset theme_debug 0 doesn't work. Try disabling the theme debugging on your settings.php file, adding the below line of code:

$conf['theme_debug'] = FALSE;

Don't forget clear the cache.


file_save_data() cannot save to private://

Check two things:

The private flesystem is configured: look in
/admin/config/media/file-system.
The destination directory (private://pdf) is created. The exact path
of private:// depends on where have tou configured the private
filesystem.


Drupal 8 programmatical block can't be place in "Block Place UI"

Message have say

  Fatal error:  Class 'Drupal\Core\block\BlockBase' not found in
  /vagrant/src/d8/modules/custom/pnc/pnc_block_test/src/Plugin/Block/PncBlockTest.php
  on line 23

problem here is wrong typo block not Block

replace

// Module block exit. But this class not exit
use Drupal\Core\block\BlockBase;

with

//path folder core/lib/Drupal/Core/Block
use Drupal\Core\Block\BlockBase;


These are the players :

MP3 Player
AudioField
jPlayer - I think this is a player that you want.


Move the location of "Notify user of new account" from bottom to custom section of admin/people screen?

If I recall correctly, it's $form['notify']. So you should be able to do this:

$form['notify']['#weight'] = -999;


How to set one region over the other (and not beside it) in Omega theme?

The side bars are used to create columns and not for placing it one on top of the other.

If you want a single column then you would go for one of the three. If you want two columns go with any two of them and if you want three columns go for all three.

As for placing contents one on top of the other the blocks should be used for that. Let us say you have two blocks one to show the latest articles and another to place the login box and you want the articles to be on top of the login box then you would go with one of the side bars and content and place both the blocks in the same sidebar and arrange it as you would want it.


How to create features for site configuration in drupal 7

Strongram module will allow to export system configurations and settings through features.


How to create a block view containing data from another Drupal site?

I am assuming that the view that is already in use is of type block.

You can clone the Block using the views admin UI.

1)Go to Structure -> Views

2)Click on the Edit link corresponding to your view

3)Click on the block you are interested in copying and select the option "Clone Block" from the dropdown.

4)A copy of the block gets created. Update the title of the new block , make the necessary changes to the filters etc and save.

oops!Missed out the important piece "

  The view should display the events which are currently available in a
  different site

"

From what I understand the multi-site setup is achieved using the Domain Access module. So the drupal instance and the DB are common for all the sites.

In your case you need to make the events content available in the domain where you are creating the view. To do this
1) Go to Structure -> Content Types

2) Click on the edit link corresponding to the Events content type

3) Click on "Domain Access Settings" at the bottom

4) Select the Domain where the events view is going to be added and save.

5) This domain access setting gets applied to all the new events which get added after the change.

6) The existing events might have to be manually updated to make them accessible in the different domain. Go to the edit page of each specific event and update the Domain Access options accordingly.


I can't backup my website on a shared server because memory runs out. What can I do?

According to this tutorial hostgator shared hosts can get ssh access so 2 of the solutions below assume ssh access ha been setup properly (the setup of ssh is beyond the scope of these forums)

This is also a general solution as most shared hosts nowadays have ssh access

1. using command line

# go to root directory
cd httpdocs

# dump database
mysqldump -u USERNAME -p'PASSWORD' DATABASENAME > database.sql

# zip the whole drupal directory
zip -9 -qr html.zip .

2. Using drush

setup drush (done once)

# get drush
wget http://files.drush.org/drush.phar;
# if above does not work go to and get the link to latest version .phar from
# https://github.com/drush-ops/drush/releases
# wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# make it executable
chmod +x drush.phar;

# move it to home directory or any other directory
mv drush.phar ~/drush;

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bashrc
# or
# nano .bash_profile

# add this the end of the file
alias drush='/home/your_user/drush';

# use the alias you just setup
source ~/.bashrc;

using drush

# after setting up drush
# go to root directory
cd httpdocs
# dump the database
drush sql-dump > database.sql
# zip the whole drupal directory
zip -9 -qr html.zip .

3. if no ssh present you will need to use cpanel, plesk or another control panel

database backup (one of the following)

go into cpanel and find phpmyadmin go into your database and start the export process
some panels will have under databases a way to backup a database without getting into phpmyadmin

files backup

go into file manager and find the root directory (public_html or httpdocs) and zip the folder

Notes

More on drupal backup

If memory runs out on any of the previous solutions perhaps you ought to upgrade your plan or move to a vps/dedicated/cloud hosting solution

if none of the above works and the support is not willing to help you set a way to backup your site get out of that host they are not worth the money that you spend


Maintaining the integrity of URLs while moving pages between site sections in Drupal 7

If you are referring to the normal url, like node/3, then the url is always the same.

If you are referring to the path alias, which is the pretty url you can give to a page, or configure to generate automatically with tokens via the pathauto module, then when you move a node in to a different section the alias can change (this depends on how you have the alias generation configured, for example if there is nothing related to the section in the path alias then there will be no affect).

If your alias changes when you change a node, then normally the old path will no longer work and you can end up with people linking to those pages having their links break.

A workaround for this is to use the redirect module.

If you have pathauto and redirect both installed, then on the pathauto settings page you can configure the "Update action" option to create a redirect between the old and the new alias when a node is updated. This will stop incoming links from breaking when you change a node and its alias changes.

I would also recommend configuring the redirect module to delete old redirects if they haven't been used for a period of time (say 4 months for example).
This means if no one has used the old path in 4 months then it will delete the redirect as you likely don't need it anymore. Set the period to whatever you feel comfortable with.

I recommend not using this auto-redirect on alias change feature during development if content is likely to change a lot. This is because you end up with a lot of redirects that are not needed and if you change a node so that the alias changes from alias1 to alias2 and then back to alias1 again, you can get errors. If you care to learn more about those errors, see:

http://drupal.org/node/1817976
http://drupal.org/node/1263832
http://drupal.org/node/1796596


How to check if an entity bundle has a field?

Woops, this is closely related to Get all fields defined in a bundle, but since that gets all fields, I'll post this.

Use the EntityFieldManager (entity_field.manager) service, specifically the getFieldDefinitions method, to get all field definitions, and then check for your specific field.

function doesBundleHaveField($entity_type = 'node', $bundle = 'page', $field_name = 'field_paragraphs') {
  $all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_type, $bundle);
  return isset($all_bundle_fields[$field_name]);
}


Attach JavaScript and CSS assets when render entity using Views REST export

We came up with a new module: Ajax Assets Plus.

The module provides a new render which collects all the necessary libraries during rendering. It results in an array:

return [
      'commands' ['An array with ajax commands for settings'],
      'content' => 'Rendered content(HTML)',
      'libraries' => 'all the needed assets grouped into libraries',
    ];

We had to to override the AjaxResponseAttachmentsProcessor and AssetResolver classes.

Also we implemented the hook_js_settings_build() to collect all the libraries on the page, as ajaxPageState does not contain all the dependencies.


Ideas on how to create a multi-part form, where the form requires completion/approval by another user

All you need is D7 forms API if you are comfortable writing PHP. There are several ways you could go about it. One assumes that the e-mail address of User B is the same e-mail they used to create their Drupal account. You'll need to store the result of User A's submission in a database somehow. Depends if you are already storing data from the DB or not. If not you can use variable_set() to store the e-mail address in one of Drupal's core tables and then variable_get() to retrieve it.

The idea is to save whatever user A stores to the DB after filling out the form. In your form definition, at the top check to see if that value is there. If so, you know user A has completed his part, next step is to check the user accessing this form. If their e-mail address matches the e-mail supplied during user A's part then you display user B's part of the form.


How to get values from $form_state with webform

It's a bit hackish, but I think it would it be better if you set the path to your View in $form['#action'] and post the form directly to your View. Then on your Views page you grab the posted values from the form, in a contextual filter if you need that. In that way you also completely bypass the submission handling and nothing is saved.


Implementing direction of a 1:n relation with entity-reference

Your claim that "With the first implementation (A type with a multi-value field) I give the user the possibility to sort the related entities, which is not possible with the second implementation." is false.

Some things may be easier one way. Other things may be easier the other way. But ultimately, with Views you should be able to accomplish pretty much anything with both of these approaches. So use the one that's natural for your data.


How to get Drush to use alternative php.ini

Looks like you are using the Drush Phar, which does not support php.ini selection.  You must either:

Configure your webserver php-cli php.ini correctly (may not be an option if /opt/alt/php56/etc/php.ini is not writable)

or -

Install Drush via Composer per the installation instructions


How to make custom entity type revisionable with existing content?

Yes, it is highly complicated and there is currently no easy for such a switch.

Upgrade path between revisionable / non-revisionable entities is the core issue to make this easier. You could rely on the patch there but I'm not sure if it is fully working right now.


How call a custom function after input got validated in hook_form_alter?

You can add your function in  the [#submit] key. For example :

if ( empty($form['#submit']) ) {
  $form['#submit'] = array();
}
array_push($form['#submit'], 'do_database_updation');

The submit handler is called after the validation.


I faced a similar issue while adding a new field 'Mail' in the 'user_admin_account' form.

During my search I came across this post & also this post 'https://drupal.org/node/1899708' which address the same issue. I got a solution for this as described below:

/**
 * Implements hook_form_FORMID_alter()
 * @param $form
 * @param $form_state
 * @param $form_id
 * @return $form
 */
function CUSTOMMODULE_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  // Adding User Mail Field in the 'user_admin_account' form
  $mail_header = array(
    'mail' => array('data' => t('Mail'), 'field' => 'u.mail'),
  );
  // Placing Mail at 2nd position
  array_splice($form['accounts']['#header'], 1, 0, $mail_header);

  foreach($form['accounts']['#options'] as $key =>$value){
       $query = db_select('users', 'u')
        ->fields('u', array('mail'))
        ->condition('u.uid', $key)
        ->execute()
    ->fetchAssoc();

    array_unshift($form['accounts']['#options'][$key], $query['mail']);
  }

  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

Although this post dates back in '11, but as i did not get any solution based on my search so considered to post this answer. Hope it helps.


Connecting Commerce module with registered users

Commerce Addressbook could be useful for you.


Getting current tid on taxomony/term/{id} without using arg()

From where this page is coming, from core taxonomy or views?.

By default the taxonomy module provide the taxonomy/term/## callback and views module also provide a default view with the path taxonomy/term/##.

If you haven't enabled the Taxonomy term view then this page will be the default taxonomy core page, in that case you can use menu_get_object('taxonomy_term', 2) to get the loaded term.

For arg(), the document says

  Avoid use of this function where possible, as resulting code is hard to read. In menu callback functions, attempt to use named arguments. See the explanation in menu.inc for how to construct callbacks that take arguments. When attempting to use this function to load an element from the current path, e.g. loading the node on a node page, use menu_get_object() instead.


How do I support text formats for an entity property?

You'll need another property on your entity to hold the format.

In your entity form builder, use a text_format element, and use a validate to move the desired values into place:

$form['description_placeholder'] = array(
  '#type' => 'text_format',
  '#title' => t('Description'),
  '#format' => empty($entity->description_format) ? 'full_html' : $entity->description_format,
  '#default_value' => empty($entity->description) ? '' : $entity->description,
);

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

...

function MYMODULE_entity_validate($form, &$form_state) {
  $form_state['values']['description'] = $form_state['values']['description_placeholder']['value'];
  $form_state['values']['description_format'] = $form_state['values']['description_placeholder']['format'];
}

When you render, use:

 $formatted = check_markup($entity->description, $entity->description_format);


I'll use default registration for students. Submit of second form will add different role (and register too).

Check this module too: http://drupal.org/project/user_role_field/


how to add custom additional password suggetions descriptions points in drupal 7?

Add this to your front-end theme's template.php file:

function THEME_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'user_register_form':
    case 'user_profile_form':
      $form['account']['mail']['#description'] .= "And some additional stuff.";
          break;
  }
}

Add similar to admin theme if need be.

Clear the cache when you are done.

Alternatively try Better field descriptions.

  Better field descriptions makes it possible to add themeable
  descriptions to fields in forms.

I have never tried it but it looks like it could do the job, through just adding your own form_alter hook is much simpler.


Get profile ID after using commerce_customer_profile_save()

Stupid me, it's in the $profile object itself.

commerce_customer_profile_save($profile);
$profile->profile_id;


There is String Overrides

  Provides a quick and easy way to replace any text on the site.


How to disable module warning "User warning: The following module is missing from the file system" only visible on update.php?

Probably you haven't uninstalled the module, so you've to either:

restore the module to its original location and uninstall it,
or manually remove all traces of the module in the database (not recommended) by:

using Module Missing Message Fixer (Drupal 7)
using Drush command:

Drupal 7

drush sql-query "DELETE from system where name = 'old_module1' AND type = 'module';"

Drupal 8

drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='module_name';"

When it's done, clear the site's caches: drush cr.

Or use Devel module by going to: /devel/php and execute:

$query = \Drupal::database()->delete('key_value')
      ->condition('collection', 'system.schema')
      ->condition('name', 'module_name')
      ->execute();

See: How to fix "The following module is missing from the file system..." warning messages.


You just need to create groups for these results:

you want to group the results by Year and Month, so you need to add two fields:

First field for group by Year [Content: Post date]:

Second field for group by Month [Content: Post date]:

Add filters and sort criteria:

Choose format settings:

Group yearly results:

Group monthly results:

That's it!

Your results:

- 2013
-- Jan
--- tilte #1
--- ...
-- Feb
--- title #4
--- ...
--- Mar
--- title #6
--- ...


'Edit Own Content' permission missing in custom entity

If you look at the end of the node permissions file, you'll see:

permission_callbacks:
  - \Drupal\node\NodePermissions::nodeTypePermissions

If you look at the buildPermissions method, you'll see where the rest of the node permissions are created.

And then in node.module, take a look at node_node_access implementation of hook_node_access.

Also, see: \Drupal\node\NodeAccessControlHandler and the corresponding Interface class. It seems fairly complex, but both the node_node_access method and the NodeAccessControlHandlerInterface are well-documented and seem like a good place to start for developing your custom entity permissions system.


There are a number of ways you could accomplish this. Some might be better than others depending on your specific requirements.

Since soundmanager2 and downloadfile both provide field formatters the easiest way is probably just to print the field twice, each with a different formatter.

A couple of ways you might do that (this is not an exhaustive list) are:

Create a node view with a contextual filter that takes a node ID. Set the filter to use a default value if no value is present and set the default to be the node ID from URL. Then put the field in question in the view twice with the different formatters. Then either manually print the view in your node template or use the EVA module to show the view on the node.
Set the field up to display as one of the formatters via the node display settings UI and print it manually in the node template like you would any other field. Then also add a node preprocess function to render the field a second time with the other formatter into a custom variable using field_view_field(). Then print that custom field rendering alongside the other field rendering.

I can possibly provide more detail on those solutions if you have further questions.


Invalid form POST data in AJAX Login form

short:
it should works if you disable "cache pages for anonymous users"

long:
When Drupal's core caching feature is switched on, forms are delivered to anonymous visitors from cache which results in the situation where one and the same form gets delivered more than once with the same form_build_id.

As soon as one of the anonymous users submits such a form, the record gets removed from cache.

The next visitor who is submitting the same form will potentially run into trouble because of the missing form record in cache.

The regular Drupal FAPI seems to be OK with that but if the form gets submitted via Ajax, the submission gets rejected, a watchdog entry gets issued ('Invalid form POST data') and drupal_exit() gets called.

The result of that is that the user would have to reload the page before being able to submit the form. This can be annoying i.e. if the form being used is the user login form. It seems as if just nothing is happening.

This issue arrises always when page caching for anonymous users and form submission via Drupal's own ajax mechanism get used in combination.

source:
http://drupal.org/node/1694574


submit handler not working when using hook_form_alter

If you check out drupal_goto() you can see it calls drupal_exit() which is not something you want to do in a hook. The comments for hook_user_login() discuss this a little, finishing with this snippet:

function mymodule_user_login(&$edit, $account)
{
  // Your logic will set $redirection to the desired location
  $redirection = 'node/394';

  // Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.
  if (empty($_GET['destination'])
    && !is_null($redirection)
    && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset'))
  {
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }
}

Also mentioned is the login destination module.


Node type created by custom module doesn't get updated

My wild guess is:

From hook_node_type_insert documentation:

  Respond to node type creation.
  This hook is invoked from node_type_save() after the node type is added to the database.

Because you're not "Uninstalling" the module after you disable it, the content type will be kept, but it will simply be flagged as "Disabled" in the "disabled" column in the {node_type} table.

Therefore that hook is not invoked when you re-enable the module, hence the new fields not added.

So what you need to do is after disabling the module, go to the Uninstall tab and uninstall it, or if you're using drush:

drush dis -y simplegal && drush pm-uninstall -y simplegal


@Vecta I hope this help you

function MYMODULE_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  //with a node
  if ($entity_type->id() === 'node') {
    if ($bundle == 'article') {
      if (isset($fields['title'])) {
        // change constraint id
        $fields['title']->addConstraint('UniqueCode', []);
      }
    }
  }
  //with a paragraph
  if ($entity_type->id() === 'paragraph') {
    // use the paragraph machine name
    if ($bundle == 'paragraph_name') {
      if (isset($fields['field_name'])) {
        // change constraint id
        $fields['field_name']->addConstraint('ConstraintId', []);
      }
    }
  }
}


I ended up deleting the job and recreating it again.

here is how just incase.

// job_id = the job id in job_schedule table.
// $import_status = weather we want to delete or create a job.
// $importer_type = I had 2 types of importers to switch between.
// $original value = only recreating a job if it was deleted first.

function schedule_conrtol($job_id, $import_status, $importer_type, $original_value) {
  if ($import_status === 1) {
    // Deleting a job
    $job = array('name' => 'job_name',
                 'type' => $importer_type,
                 'id'   => $job_id
                );
    JobScheduler::get($job['name'])->remove($job);
  }

if ($import_status === 0 && $original_value === "1") {
    // Inserting a job
    $job = array(
    'name'     => 'job_name',
    'type'     => $importer_type,
    'id'       => $job_id,
    'period'   => 1800,
    'periodic' => TRUE,
    );
    JobScheduler::get($job['name'])->set($job);
  }

}

and you can control this using hook_node_presave

hope this helps.


How do I create a view with a 'Content pane' display type?

Ok I found it.

I was looking for the option on the first screen where you give the view a name and select if it's a block or not. Instead you must add a new Display instead, on the 2nd screen, and select it from the drop down list that appears


Call to a member function getLoginUrl() on a non-object in fbconnect.pages.inc on line 230

You need to set up the app with Facebook. The current link for doing so is https://developers.facebook.com/apps.

See http://drupal.org/node/1944522.


Restrict permission to custom modules in drupal

Declare a permission with hook_perm(). It is recommended to somehow use your module name in the permission or something unique to your module to avoid conflicts (there is no namespacing, permission names are global).
In your hook_menu() implementation, add 'access arguments' => array('permission name here'). Since the default access callback is user_access(), the menu system will call user_access('your permission name') to check if the current user has access to that menu item. See hook_menu() documentation for more information. You can also use user_access() directly in your code, if you want to check permissions somewhere else; for example for blocks, you can use that function directly.
Then, you can create whatever roles you want to and give them the permissions of your module at admin/user/permissions. The important distinction here is that permissions are controlled in modules (which can be more or less generically written) while roles and the permissions they have are site-specific.

Then, make sure to rebuild the menu (by using devel.module or saving the modules form) and you should be good.


This is a very old question but worth solving it.

By:

  I also try to did this by simplesaml "Test configured authentication sources", but I got the same result.

It seems that @misha-from-lviv didn't configure simpleSAMLphp correctly.

  $metadata['name'] = array( 'SingleSignOnService' => 'url_login', 'SingleLogoutService' => 'url_logout', 'certFingerprint' => 'key', );

The metadata is incomplete

The process to configure the simplesamlphp is way more complex that the 5 steps described there. This Vagrant box setup simplesAMLphp (as an SP and IdP) and Drupal 7 for you and let's you start testing SAML right away.

Disclaimer: I created the box


I've finally found a solution.

I needed to go to Views/Media and add Bulk update to the Fields, but it was missing. Once I realised that I needed to restore it I found this drush command.

* drush cim --yes --partial --source=core/modules/media/config/optional && cr

Which updates the following:

+------------+--------------------------------------+-----------+
| Collection | Config                               | Operation |
+------------+--------------------------------------+-----------+
|            | system.action.media_delete_action    | Create    |
|            | system.action.media_publish_action   | Create    |
|            | system.action.media_save_action      | Create    |
|            | system.action.media_unpublish_action | Create    |
|            | views.view.media                     | Update    |
+------------+--------------------------------------+-----------+

Then clear cache and Bulk update has now been restored to the Fields section.


How to point a menu link at a View with multiple options on the same exposed filter selected?

Got it working. I set it up as a Page Manager page with an arbitrary path (e.g. options or view/options), set to "HTTP Response Code" then "301 redirect".

The problem in the question where the ampersand-seperated characters were getting eaten seemed to be caused by Drupal treating them as duplicates of each other and rejecting all except the last. To get around that, I set the redirect URL to:

  view?option[1]=7&option[2]=12&option[3]=14

Note how each one has a unique number in the square brackets.

Views doesn't seem to care about the numbers in the square brackets, and they stop Drupal merging the parameters into one.

Note you should always input the non-encoded version, like above, else Drupal will double-encode it causing it to break. Keep this in mind if you edit it - you'll need to replace the whole string with the original, non-encoded version then edit that before saving.


There are couple of module available to do this job. Hope this will be helpful

1. Masquerade

  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.

2. Role Switcher

  Role Switcher module provides with an option to change role for
  testing purposes. It creates 'roleswitcher' role and grants it
  permission to administer permissions which makes possible to switch
  back to the original role the user had. The module provides a
  roleswitcher block and a page, /roleswitcher.


Crypt::hmacBase64() versus CsrfTokenGenerator::get() and CsrfTokenGenerator::validate()

I made a quick test using the following code.

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Site\Settings;
use Drupal\Core\Access\CsrfToken;
use Drupal\Component\Utility\Crypt;

$autoloader = require_once 'autoload.php';

/**
 * Global flag to identify update.php and authorize.php runs.
 *
 * Identifies update.php and authorize.php runs, avoiding unwanted operations
 * such as css/js preprocessing and translation, and solves some theming issues.
 * The flag is checked in other places in Drupal code (not just authorize.php).
 */
const MAINTENANCE_MODE = 'update';

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->prepareLegacyRequest($request);
}
catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');

drupal_maintenance_theme();

$csrf_token = \Drupal::csrfToken();

$content[] = [
  '#markup' => t('First method: %token.
', ['%token' => Crypt::hmacBase64(123456, \Drupal::service('private_key')->get())]),
  '#cache' => ['max-age' => 0],
];
$content[] = [
  '#markup' => t('Second method: %token.
', ['%token' => $csrf_token->get(123456)]),
  '#cache' => ['max-age' => 0],
];

$renderer = \Drupal::service('bare_html_page_renderer');
$response = $renderer->renderBarePage($content, 'Test results', 'maintenance_page', array(
  '#show_messages' => FALSE,
));

$response->setStatusCode(400);
$response->send();

I then opened three different Firefox windows pointing them at the test script I wrote. This is what I got:

First window

  First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
  Second method: OndzLnnASZLsuzABJltD_HwK8dr48fEW_hdWG9Lu02I.

Second window

  First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
  Second method: J6oHkKdXeL9RUKHX4B1Sn418Yh8XD0tJbRrs459BI7A.

Third window

  First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
  Second method: TYvxZiF7xS6hD2nn8pfHu0GR9OPw0X8xT1HfVDNWkXc.

With the second method, different users are going to get different values, even in the case the input value is the same.
I would say that using the csrf_token service is preferable, in my case.


Any suggestions for Taxonomy scaling and performance with 1073 terms?

1000 terms is not so bad, really. I am inclined to believe the number of terms in your vocabulary is not what has the most impact on response time, as MySQL can handle much larger datasets out of the box.  One factor to consider is the hierarchy of your taxonomy, or the number of levels it has. A vocabulary with 3-level-deep hierarchy will be much slower than a vocabulary that is implemented as flat hierarchy.

Good-luck


Yes drupal doesn't suppport # in menu_links, You might get some clues here - http://drupal.org/node/325533


Adding validation to existing forms using #element_validate

the method that work is this

function MYMODULE_form_NODE_FORMID_alter(&$form, &$form_state) {
  dpm($form);
  $form['body'][LANGUAGE_NONE][0][['#element_validate'][] = 'MYMODULE_validate_breads_node_form_alter';
}

/**
 * Implements callback function().
 * Specific alteration for views exposed forms
 */
function MYMODULE_validate_NODE_FORMID_alter($element, &$form, &$form_state) {
  if (empty($element['#value'])) {
    form_error($element, t('Text'));
  }
}


If you bootstrap Drupal, you can just tell it to serve a particular page. Consider the content of index.php:

<?php
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

If you replace the Request::createFromGlobals with a new Request(...), you can pass explicit values for the $_GET etc parameters. The function signature copied from Symfony is as follows:

/**
 * Constructor.
 *
 * @param array           $query      The GET parameters
 * @param array           $request    The POST parameters
 * @param array           $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
 * @param array           $cookies    The COOKIE parameters
 * @param array           $files      The FILES parameters
 * @param array           $server     The SERVER parameters
 * @param string|resource $content    The raw body data
 */
public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
    $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}

So your custom script could require the autoloader, bootstrap Drupal, create a fake Request object, tell Drupal to handle it, then save $response->getContent() to a file.


Backport of hook_library() for Drupal 6?

The module that originated the patch that introduced hook_library() in Drupal 7 is the jQ module (see Allow to add JS/CSS libraries (sets of files, settings, and dependent libraries). The hooks used by that module are different, but that is the module that is closer to what you are looking for. That module requires you to call a different function, but using drupal_add_js() would require you to hack the Drupal core, which is something it is never suggested to do, in the cases where you want absolute compatibility between Drupal 6 and Drupal 7.


Wrong status after updating from 7.64 to 7.66

Try to delete the includes folder and add new includes folder from 7.66 version, bootstrap.inc defines the drupal version.


Display Signup info in custom node template

You can always built your own module and implement a hook_node_view() and put this form into the node content like:

function YOURMODULE_node_view($node, $view_mode, $langcode) {
 $node->content['signup_form'] = array(
  '#item'     => 'item',
  '#markup' => render(drupal_get_form('this forms ID')),
  '#theme' => 'my_signup_form_theme' //optional
 );
}

And to get even more configurable and cool-looking you could insert this new piece of content to the "Display fields" drag and drop form of the respective content type with

 hook_extra_fields()

like:

function YOURMODULE_field_extra_fields() {
    $extra['node']['node-TYPE']['display'] = array(
         'signup_form' => array(
            'label' => t('SignUp form'),
            'description' => t('SignUp form imported to Node Content'),
            'weight' => 10,
         ),
}

And now you have

$node->content['signup_form']

in your tpl


How to make a user choose male or female and keep a default image on a specific content?

You can do this on the display level via

hook_preprocess_field() (thx Clive in the comments, give him a thumbs up!), OR
a custom formatter, OR
a custom Display suite field

hook_preprocess_field() on the image field is the easiest.

You have the full user entity available and can use information from other fields to alter the image.

The hook is fired every time theme('field', ..) is fired, so you need to figure out if this is the correct field.

EDIT: Instead of a detailed tutorial, here is what I usually do:

Install devel
Create your custom module with an implementation of hook_preprocess_field(&$variables).
Do dpm($variables) inside that hook implementation to show the function argument (sometimes you need to refresh the page twice to see the result).
Manipulate the part of $variables that you are interested in.

With a custom formatter, you can define your own way to display e.g. the image field, while having the data from other node fields available.

Then on the user display configuration, you can choose this formatter to display the image.

With the custom DS field, you can introduce a "field" - that is, a positionable element on the entity display. This field can use data from multiple data fields on the node entity. E.g. you first check if there is an explicitly uploaded image, and if not, you show an image depending on the gender (male, female, transgender / don't say).

You can also define a form to configure display options. E.g. you could make the image style configurable.

Steps:

Enable Display suite
Implement hook_ds_fields_info() in a custom module, using e.g. DS_FIELD_TYPE_FUNCTION.
Provide the function to generate the html or render array (some examples)
Configure your user to display with a Display suite layout.
Enable your custom field.

There are more details to this. But I the main purpose of this answer is to point you in a direction.

The weakness of all these options is that you have to hardcode the field names, or at least one of them. If you want to reuse this on another site with other field names, you have to change the field names in the code.


How to find out what views page you're looking at

Use menu_get_item() to retrieve the page callback for the currently shown path, and check it correponds to 'views_page', which means you are in a view.

function mycooltheme_preprocess_page(&$vars) {
  $menu_item = menu_get_item($_GET['q']);

  if ($menu_item['page_callback'] == 'views_page') {
    $vars['is_portfolio'] = ($menu_item['page_arguments'][0] == 'path_of_your_view');
  }
}

You can also use current_path() directly, but I found interesting to know that you're on a Views page using menu_get_item().


Exporting nodes except for specific fields

Use feeds -> https://www.drupal.org/project/feeds for custom export / import of nodes, users, taxonomy terms or simple database records


How to show filtered content as suggestion of "reference autocomplete field" based on a field value of reference content

Thanks @shawn-conn
His answer is perfect but I can't give vote because of minimum reputation. See following solution in details:

Step 1:
First create one entity reference view
Note: In this view include referenced content type (e.g.: CONCEPT) and it's filter/condition field (e.g.: STATUS)

Step 2:
From MANAGE FIELDS of the required content type (e.g.: PROJECT), Add field that FIELD TYPE will be Entity Reference and WIDGET will be autocomplete then click on the SAVE button.

Step 3:
Now choose Views: Filter by an entity reference view option in MODE field and choose your views that is created in Step 1 in View used to select the entities field from ENTITY SELECTION section of the field settings page.

Step 4:
Click on the Save settings button to save changes.


How to allow user content on the front page?

For the content type you want to be promoted you need to set the options on that content type to automatically be promoted to front page.

In Drupal7 find this under admin/structure/types pick one of the content types and choose "edit".  Under "Publishing Options" choose "Promoted to front page".


The code:

$res = db_select('table', 's')
->fields('s')
->condition('type', $type)
->condition('id', $id)
->execute()
->fetch();

is not faulty in itself. The problem is probably that you don't have a record with matches both id and type. If you want to make an or query, you need to use db_or


You can add an expression:

$query = db_select('TEST_ATTRIBUTES', 't')
  ->fields('t', array('Column1', 'Column2'));

$query->addExpression('COALESCE(Column1, Column2)', 'Column3');

The above yields:

SELECT
  t.Column1 AS Column1,
  t.Column2 AS Column2,
  COALESCE(Column1, Column2) AS Column3
FROM TEST_ATTRIBUTES t


Text field will not save after moving it from commerce billing profile to account fieldset in checkout

Unfortunately, you can't move this and have it continue working as normal. Entity form submission depends on a specific "tree" hierarchy in the submitted field values, and moving it like this disrupts that. Thus when the customer profile information is saving, your custom textfield is just invisible.

If you really need to move this, then you should add a custom submit handler that populates the customer profile as before.


How can I validate exposed filter from View?

You should use hook_form_alter() to add a custom submit handler to the form like so:

$form['#submit'][] = 'my_custom_validation';

function my_custom_validation() {
  // Add the logic that you want in here
}

Then use form_set_error() to indicate if the value is wrong.


The field table collection module is kind enough to provide a specific theme function for tables that it outputs.

As such, you can implement a preprocess hook for the theme_table__field_collection_table() function and add your row numbers in there:

function MYMODULE_preprocess_table__field_collection_table(&$vars) {
  // Add a new (blank) header
  array_unshift($vars['header'], '&nbsp;');

  // Add an incremental count to each row
  $count = 1;
  foreach ($vars['rows'] as $key => &$row) {
    array_unshift($row['data'], $count++);
  }
}


Change URL to meaningful name when I use hyperlink target

The Block Attributes module will let you add a meaningful id attribute to any Drupal block.

  The Block Attributes module allows users to specify additional HTML
  attributes for blocks, through the block's configuration interface,
  such as class, id, style, title and more.


You can use $_SERVER['HTTP_REFERER'] with PHP to get the URL of the last page you were on. This is not a reliable solution because not all user agents support it. plus users can manually intervene with the previous page and mess things up.

If a client side solution is sufficient for you, you can use javascript's document.referrer.

You could use a querystring as well and append that to the URL and read it from the page you're going to.

website.com/secondPage?refer=lastPageIWasOn

// then grab the value from the second page
$last_page_value = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';

// or use drupal_get_query_parameters()

// Then do something with it

Or you could use cookie/session to do this

if (!isset($_SESSION)) {
    session_start();
}
if (!isset($_SESSION['referrer'])) {
    $_SESSION['lastpage'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
}

// second page
$referer = isset($_SESSION['lastpage']) ? $_SESSION['lastpage'] : '';

This is a very common use case and StackOverflow has several questions on it with PHP. I suggest googling it. Translating it to drupal will depend on what you're doing with it.


How to add missing data selector in "Create new entity" rules action?

Looks like you're starting to hit the limits of the most recent (beta2) release of the Statuses module. Have a look at this variation of a custom rule, which is included in Comment nr 13 of issue nr 1693620:

{ "rules_user_commented_on_status" : {
    "LABEL" : "User commented on a status",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Statuses" ],
    "REQUIRES" : [ "fbss_rules", "rules", "fbss_comments_rules" ],
    "ON" : [ "fbss_comments_save" ],
    "DO" : [
      { "fbss_rules_load_action" : {
          "USING" : { "sid" : [ "comment:sid" ] },
          "PROVIDE" : { "status_loaded" : { "status_loaded" : "Loaded status" } }
        }
      },
      { "mail" : {
          "to" : "[status-loaded:sender:mail]",
          "subject" : "[comment:commenter:name] commented on your status",
          "message" : "Hi [status-loaded:sender:name],\r\n\r\n[comment:commenter:name] commented on your status [status-loaded:message-formatted]\r\n\r\n\r\nRegards,\r\n[site:name]"
        }
      }
    ]
  }
}

Even though this is not really the rule you're looking for, pay attention to the "to" field in the eMail being constructed. That to-field uses token ...sender:mail, which is close to the uid (I believe) of the "sender".

That very same comment in that issue also includes a patch (which I believe is committed to the current DEV version), clearly an improvement (not a bug fix ...) because it makes extra data available for subsequent Rules processing. This patch appears to be a prereq for the above rule to work: I tried to import that rule in a site using the beta2 version, but that import failed (and "I" do not want to use a DEV version, even using beta-versions is exceptional to me).

I suggest you either try to apply that patch in your current setup, or switch to the DEV version of that module. After you do so, continue with these extra steps:

Try to import that same eMail example, so that you have a sample rule that is close to what you'll need.
Expand your own rule, to also add such "load action" and then check if you have a similar token like that [status-loaded:sender:mail], which in your case should become something like [status-loaded:sender:name] or [status-loaded:sender:uid].

If you get that import of the eMail sample to work, then I would assume (have not tested it myself and leave that to you) that this comination of your rule with part of the eMail sample here is what you're looking for:

{ "rules_posted_statuses_comment" : {
"LABEL" : "Posted a statuses comment",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "statuses" ],
"REQUIRES" : [ "fbss_comments_rules", "fbss_rules", "rules" ],
"ON" : { "fbss_comments_save" : [] },
"IF" : [ { "NOT fbss_comments_rules_on_own" : { "comment" : [ "comment" ] } } ],
"DO" : [
  { "fbss_rules_load_action" : {
      "USING" : { "sid" : [ "comment:sid" ] },
      "PROVIDE" : { "status_loaded" : { "status_loaded" : "Loaded status" } }
    }
  },
  { "entity_query" : {
      "USING" : {
        "type" : "user",
        "property" : "uid",
        "value" : [ "status-loaded:sender" ],
        "limit" : "1"
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "message",
        "param_type" : "status_comments",
        "param_user" : [ "entity-fetched:0" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:arguments:status-comments-user" ],
      "value" : "[comment:commenter]"
    }
  }
]

}
}

Note the status-loaded:sender in the above rule! Which should be a token you can use because of the very first Rules Action added now.

Disclaimer: I have NOT (repeat NOT) tested this last rule (since I never use DEV versions of a module). Though chances are that by copy/pasting relevant parts of your original (exported) rule and the (exported) eMail rule it does work as it should.

Note: I'm about sure that the integrity check you got (when trying to import my updated rule, as you wrote in a comment to this answer) is because "status-loaded:sender" is not returned as a "User entity". While the Message module wants/expects the "param_user" to be a "User entity".

You might be able to "convert" that "status-loaded:sender", by adding a Rules Action "Fetch entity by property", whereas you would use "status-loaded:sender" as the property to do so. The entity type to be fetched should be, for sure, a "user" entity (not a "message"!). This Rules Action should be inserted after the first "fbss_rules_load_action".

The result of performing that extra Rules Action is then an actual "user entity" (a real entity), and that is what you might then use for that "param_user" (which should avoid the integrity check error).


Have a look at hook_menu(). It's the cornerstone to define pathes and who has access to them.

In drupal you define a path by implementing hook_menu in a custom module. There you define what php functions are called and what user roles do have access to it. This way you can route your AJAX calls through drupal autentication and authorisation.


Terms for cities and state to build dependent selects

You can use the module Taxonomy CSV import/export which is very handy to import and create taxonomy terms or vocabulary.


I would say use the User Points module along with the User Points Login add-on module to handle to recording of points for users logging in.

Then you can use the Views module to build reports for yourself to see which users have the most points for a given period.

It would also be possible to use the Rules module to automatically email you a report of the winners at the end of every month and then reset all user points to zero (I'm making an assumption that there is a rules action you could use to remove existing user points).


Do I need to indicate where is my js file?

Of course, js files do not auto magically get loaded.
You need to tell Drupal about them, There are various ways, see Adding JavaScript to your theme or module.
function draws_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'bets_node_form':
      $form['field_possible_returns']['und'][0]['value']['#process'] = array('my_custom_process');
      // Load JS File
      $form['#attached']['js'] = [
         drupal_get_path('module', 'draws') . '/draws.js',
      ];
      break;
  }
}


Use a custom install profile for Nightwatch tests?

As you understood it's been hardcoded. if you want to make it dynamic you can  create your custom parameter.

you can do it in a way like the following  :

https://www.drupal.org/project/drupal/issues/3017176

this patch help you to know what you can do : https://www.drupal.org/files/issues/2019-11-11/3017176-16.patch


How to hook into core's "log in to comment" link

I found the solution with the help of this SE post. Using MYMODULE_node_view_alter(&$build) and MYMODULE_comment_view_alter(&$build) in my custom module, I was able to change the values using:

$build['links']['comment']['#links']['comment_forbidden'] = str_replace('%23','#', $build['links']['comment']['#links']['comment_forbidden']);


Open login form in popup iframe? Using Colobox module?

I can confirm that the http://drupal.org/project/colorbox module is one of the easiest (and most supported) ways to have a lightbox for the login form.

There is also other benefits like being able to load AJAX content in the lightbox as well using 'colorbox-load'


Route parameter upcasting and route access?

Entities can be upcasted with these methods:

Note: to use _entity_access requirement, you must implement one of these options this information. See \Drupal\Core\Entity\EntityAccessCheck for internals.

Controller reflection

Type cast the entity object as a parameter of the controller.

For your form controller, replace:

 buildForm(array $form, FormStateInterface $form_state, $file = NULL) {

with:

 buildForm(array $form, FormStateInterface $form_state, \Drupal\file\FileInterface $file = NULL) {

This works with any entity type, not just files.

See EntityResolverManager:setParametersFromReflection.

Using _entity_view or _entity_form controllers

Entity types found in the path are upcasted automatically if the route definition has _entity_view or _entity_form as a default.

See EntityResolverManager:setParametersFromEntityInformation.

Add upcasting info to your route

Add the following to your route YAML

options:
  parameters:
    my_slug_name:
      type: 'entity:my_entity_type_id'

Replace my_slug_name with whichever text you used in your route within the {}. Usually this is exacly the same as the entity type Id.

Then replace my_entity_type_id text with the entity type Id.

I have written something similar for Views Advanced Routing in its README.


Address book not visible to registered users

Ok, after checking a bit the commerce module, it looks like this is tied to profile view permissions and also addresses are linked to customer profiles.
I made it work by enabling the following Profile permissions under /admin/people/permissions:

Customer: Create profiles (enables to create new addresses)
Customer: Delete own profiles (enables to delete addresses)
Customer: Update own profiles
Customer: View own profiles (enables the address-book tab for registered customers)
View own profiles (just in case)


How to Restrict Content OVerview to certain content types for user roles

Administration Views will replace the admin listing pages with views, and then you can tweak it.

But looking at your question in the greater context what you really need is Contextual Admnistration. With it you can create a admin UI for your athletics role to manage content. There is a video tutorial series on Youtube.


How do I use drupal_mail() without the $to value?

You do this by putting the string 'undisclosed-recipients:;' (notice the colon and semicolon at the end) is the $to parameter you pass to the drupal_mail function. E.g.:

drupal_mail('mymodule', 'send', 'undisclosed-recipients:;', $language, $params);

You can now add the list of bcc-recipients to the header.


What is the encoding for JSON:API operators?

Thanks to Hudri, here's the list:

= %3D
<> %3C%3E
> %3E
>= %3E%3D
< %3C
<= %3C%3D


How can I change the file system from public to private?

I have no idea why the UI prevents from doing that. It's not actually anything in the storage, it's just the default for new files.

What you need to do is edit the config file directly, which is named field.field.$entity_type_id.$bundle.$field_name, for example field.field.node.article.field_image.

You can do that using drush cedit, or single export and then import it again from the UI, or do a full config export and import it again after changing that file.


drupal_static and cache_set combo , is this overkill?

I don't see this a overkill.

drupal_static() caches results over the lifetime of a single request.  It is typically used for things that may be needed several times during page generation, but will (likely) not change.  For example, if a node is loaded, it gets saved in memory in case multiple functions need it.

cache_set() / cache_get() caches things in the database (or another storage backend with the proper module), so the data persists (up to the TTL) between page requests.  This gets used for things that change infrequently, and is global for all requests.  As far as I can remember, the normal implementation always goes out to the cache backend and doesn't store results in memory with drupal_static() or static.

Given the overhead, I would be judicious as to whether caching really improves things.


Which host do I need to fill in the database connection?

It will depend on your hosting setup and where the DB is located. The host value can be:

A reachable hostname where the PHP code is running (e.g. localhost for your local server)
An IP address (e.g. 127.0.0.1, the ip address normally used for localhost),
A fully qualified domain name (e.g. my-data-base-host.example.com)

Consult your hosting provider on retrieving your DB host connection credentials.


How do Organic groups and virtual sites relate to each other?

I am not sure about openscholar but what organic modules can do about virtual sites-

With help of organic group you can declare an entity as a "group" or call it context, an example could be a sports site with group as "cricket"
With help of og you have permission granularity in context to group, so a user can have access to all post which comes under a "group" in our example "cricket" being totally unaware of other groups, can say "hockey"
With in group you can have group specific roles, a user who can admin cricket group but still can not do anything on hockey group.

So each group can be seen as fully functional site in itself - virtual site

Note: Domains have nothing to do with og, it's just a matter of context switching


You need to check the "manage display" section of the entity you're rendering and make sure the images are set as visible items in the selected "entity view mode". By default it takes "default".


How do I install modules using a module?

If there are modules from which your module depends, your module should declare them as dependencies, in its .info file. Supposing that your module is my_secret_module.module, and it depends from first_module, and second_module, my_secret_module.info should contain the following lines.

// Drupal 5
dependencies = first_module second_module

// Drupal 6, Drupal 7, and next releases
dependencies[] = first_module
dependencies[] = second_module

In this way, your module cannot be enabled of the other modules are not enabled too.


Create a percentage discount coupon with a maximum value

If you're using the latest version of Commerce Discount and Commerce Coupon, you can accomplish this with just two rules connected to a single coupon code.

Create a Coupon Code by going to Admin→Store→Coupons->Create Coupon Code. Save it.
Create a new Discount (Admin→Store->Discounts->Create). Set it to Order Discount and add a Total amount condition. Set the condition to less than and the amount to 2000. Set the percentage discount as you desire. Finally, add the coupon code from step 1 to this discount and save it.
Create a another Discount. Set it to Order Discount and add a Total amount condition. Set the condition to greater than or equal to and the amount to 2000. Set the flat discount as you desire. Finally, add the coupon code from step 1 to this discount and save it.

Now, when a customer checks out, the coupon will attempt to apply both discounts, but because of the condition, only one will apply: $200 if the order is $2000 or over, and 10% if the order is $1999.99 and under.


How can change RealName / User account link destination in D7

Did you try hook_username_alter in Drupal 7.

  Alter the username that is displayed for a user.

  Called by format_username() to allow modules to alter the username
  that's displayed. Can be used to ensure user privacy in situations
  where $account->name is too revealing.

I've used this occassionally, but I find sometimes there are instances where I felt it should have been called/used already and then wasn't (the Webform module submission report tables come to mind ...)


How do I change value of a boolean field on a node when a user clicks a button?

There is a ready contrib module: Wishlist.

  Other site users can indicate their interest in purchasing an item from a wishlist. When that happens, everybody can see that somebody purchased the item and duplicated gifts are eliminated (or reduced - the wishlist module does rely on people playing nicely together).

If you just want the job done, that's your way to go. If you want to learn, read about node_save() and Form API.


Dynamic select list in the form API (dependent dropdown list)?

Basically, in your form declaration, you have to add

In your form['state'] :

'#ajax' => array(
  'callback' => '_ajaxfunction',
  'wrapper' => 'divaroundseconddropdown'
);

Then in your form['town'] :

'#prefix' => '
',
'#suffix' => '
',

Now in your _ajaxfunction :

function _ajaxfunction($form, $form_state) {
  return $form['city'];
}

Now, back to your form['town'], you simply have to build your $options with the $form_state['values']['state'] variable, which will contain what has been filled in the first dropdown.

Everything is documented here.

[EDIT]

First replace $state_record in your $query_city by $form_state['values']['state']; *You can check if the value is formatted the right by dpm($form_state); in your _ajaxfunction.

Then :

$form['state']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

$form['city']= array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#prefix' => '
',
  '#suffix' => '
',
  '#required' => TRUE,
  '#states'=>array(
    'visible'=>array(
      ':input[name="state"]' => array(
        'value'=>$options_state))));

Close your function, open a new one :

function _ajaxfunction($form, $form_state) { return $form['city']; }