File upload ajax and Radio Buttons not cooperating in registration form

If I understand you right you'll need to write a small custom module to hook into the registration form using hook_form_alter(), and add the #limit_validation_errors property to the correct radio group. This should stop the validation from running on AJAX calls, but still let it run when the form is submitted.

The code might look something like this:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['radio_button']['#limit_validation_errors'] = array();
}

It's quite likely that the particular radio group you're after will be buried in the nested $form array somewhere so you'll probably need to use the dpm() function (part of of the Devel module) to inspect the form and determine the correct element to alter.


How do I use webform tokens in my PHP code for the form submission page?

These won't show up in the results page.  I think these are only useable when the form is submitted.  One thing that confused me for a while was the [fieldset].  If the value you are trying to access is not in a fieldset it is [Root].

Name:  __

%value[Root][name]  would be most likely way to access that value after the form is submitted by the user.

(%email works also if you are going to send an email, but that also shows the label)

Hope this helps and is actually what you need help with.

-Marc


How can I add CSS variables to the HTML head?

To do this from hook_preprocess_html like in accepted answer to the duplicate question it works like in the snippet below.
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_html(&$variables) {
  $style = [
    '#tag' => 'style',
    '#value' => ":root {\n  --test-var: pink;\n}",
  ];
  $variables['page']['#attached']['html_head'][] = [$style, 'foobar-my-id'];
}


Views rewrite output for image url add divs

Found out, to have unique items for my display


The only way to do that is to actually NOT refresh the page each time but rather use ajax or something similar to refresh only certain areas of the page while leaving the player area intact.

An example of this is pitchfork.com.  It has a player in the upper right gutter.  When you click on a link, what happens is the main content area of the page is reloaded but the page stays the same, so the player keeps on playing.

But, if you hit the reload button on your browser, it stops and starts all over again because the page itself was reloaded.

Of course, you could always put the player in a pop-up/under window and then you wouldn't have to worry about it as much.


Can we move a module from the directory "/modules" to the directory "/modules/contrib" without uninstalling it?

As with most things, I suggested testing it out on a development/test site before trying on the live site. It's likely that the specific set of contribs and the libraries they use will affect the success of this operation.

How did you install the modules? Do you use a composer workflow?

In general, some paths stored in different places are going to be wrong. To fix that, you will need to edit those paths or have Drupal figure out the new paths. I believe doing a cache rebuild (e.g. drush cr) will fix that problem.


An EntityFieldQuery just returns IDs, you need to load the entities manually:

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node'));
  foreach ($nodes as $node) {
    if ($items = field_get_items('node', $node, 'field_foo')) {
      // ...
    }
  }
}


You can use Salesforce module.

  This suite of modules supports integration with Salesforce by
  synchronizing Drupal entities with
  Salesforce objects

please refer to this link.


Use the Forena module to create a "report" that includes the data that you're interesting in (Post title, Post URL, Author, publish Date). As part of the report design, indicate which export formats you want to allow for exporting the data included in it. XLS is one of the typical formats that are supported, but their could be other formats enabled also, such as CSV,  XML, HTML, etc.

Have a look at the Simple Table of States example, and think of it as the equivalent of your "posts that you want to export". And note the hyperlinks in the upper right, which are:

CSV.
XLS.
HTML.
XML.

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.

Disclosure: I'm a co-maintainer of Forena.


How can I override date field validation?

You can achieve this by prepending your own custom #element_validate function before Datelist::validateDatelist().

As in your question, you have to add an after_build function to access the individual parts (year, month, day) of the form element:

function MYMODULE_form_MYFORM_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#after_build'][] = 'MYMODULE_date_remove_day_after_build';
}

You can make the form element disappear by setting '#access' to FALSE.
Then prepend your custom #element_validate function to the array #element_validate on the element.

function MYMODULE_date_remove_day_after_build($form, &$form_state) {
  $form['field_MYFIELD']['widget'][0]['value']['day']['#access'] = FALSE;
  array_unshift($form['field_MYFIELD']['widget'][0]['value']['#element_validate'], 'mymodule_date_set_day');
  return $form;
}

Then in your custom element validate function, unset everything if Year or Month are unset, otherwise, set the day.  Notice you have to create the object before passing it to Datelist::validateDatelist().

use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Datetime\DrupalDateTime;

function mymodule_date_set_day(&$element, FormStateInterface $form_state, &$complete_form) {

  $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

  if (empty($input['year']) || empty($input['month'])) {
    $form_state->setValueForElement($element, []);
  }
  else {
    $input['day'] = "15";
    $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
    $input['object'] = DrupalDateTime::createFromArray($input, $timezone);
    $form_state->setValueForElement($element, $input);
  }
}


How can I use Drush 8 command to enable the site set up bin the Acquia DevDesktop to online mode?

You are talking about maintenance mode. If you had use the correct term, you would have been pointed to for example the following question which has the info you need:

drush sset system.maintenance_mode 0


Cache-Control: no-cache despite allowing cache for anonymous users

Inspect your HTTP headers and see if session or other cookies are being set. This is the most common cause of Varnish "not working." Also make sure you are not logged in, and you can test using http://www.isvarnishworking.com/ to see what headers are outputted. If you could paste the headers would be helpful.


Is there a way to conditionally change the state of a collapsible field group in admin, ie without changing a template or module file?

If you want it to be open on page creation, you can target the page using the node-add-CONTENTTYPE class on the body. Using some jQuery in document ready you can set it open.

Something like:

jQuery('body.page-node-add-<YOUR-CONTENT-TYPE> fieldset.#YOUR-ID-HERE').removeClass('collapsed').children('.fieldset-wrapper').show();


Why does the Login Destination module not redirect to page?

You can use Rules module.
Events: User has logged in.
Condition: User has role.
Actions: Page redirect.
Other Way through coding:
You can use hook_user_login
function hook_user_login(&$edit, $account) {
 if($account->uid == 1)
  drupal_goto('cms');
 else
  drupal_goto('cms/{$account->uid}/dashboard');
}

Updated rule:
{ "rules_after_login_rule" : {
    "LABEL" : "After Login Rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "cms\/[account:uid]\/myhomepage" } } ]
  }
}

Look at these post as well.
How to rediret to specific page depends upon user roles
I want to redirect the user to profile page after they log in
Redirect user based on role and node content


In Drush 6 and earlier, the rsync command did make some attempt to operate on site alias lists; however, we recently decided that this feature was not useful enough to continue to maintain it, so we removed it from Drush 7.  Truthfully, I'm not even sure that it's working right in Drush 6 -- casual tests showed inconsistent results.

Therefore, the best way to do this would be to just call drush rsync once for every destination site.  You could do this with a simple script.

#!bin/bash
for site in $(drush sa @setA --format=csv --fields=name)
do
    if [ "$site" != "site1" ]
    then
        drush --yes rsync @site1 "@$site"
    fi
done


You could add a fieldset for each person, something like this should work:

for ($i = 0; $i < $num_names; $i++) {
  $form['names_fieldset']['person_' . $i] = [
    '#type' => 'fieldset',
    '#title' => $this->t('Person ' . $i),
  ];

  $form['names_fieldset']['person_' . $i]['name'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
  ];
  $form['names_fieldset']['person_' . $i]['surname'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Surname'),
  ];
}

And then alter your remove callback and a few other bits to match


There isn't a published date out of the box.

You can try using Publication Date module.

  The Publication Date module adds a "Published on" date for each node,
  containing the date when it was first published.


Can customizable products work out price based on the number of uploaded files?

The answer is "yes"

I originally posted the answer here: https://drupalcommerce.org/questions/16291/can-customizable-products-work-out-price-based-number-uploaded-files

Export of the rule that proves it's possible:

   { "rules_files_price_multiplier" : {
      "LABEL" : "Files Price Multiplier",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
      "ON" : { "commerce_product_calculate_sell_price" : [] },
      "IF" : [
        { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
        { "entity_has_field" : {
            "entity" : [ "commerce-line-item" ],
            "field" : "field_upload_all_the_files"
          }
        },
        { "list_count_is" : {
            "list" : [ "commerce-line-item:field-upload-all-the-files" ],
            "op" : "\u003E",
            "value" : "0"
          }
        }
      ],
      "DO" : [
        { "variable_add" : {
            "USING" : { "type" : "integer", "value" : "1" },
            "PROVIDE" : { "variable_added" : { "file_multiplier" : "file_multiplier" } }
          }
        },
        { "LOOP" : {
            "USING" : { "list" : [ "commerce-line-item:field-upload-all-the-files" ] },
            "ITEM" : { "list_item" : "Current list item" },
            "DO" : [
              { "data_calc" : {
                  "USING" : { "input_1" : [ "file-multiplier" ], "op" : "+", "input_2" : "1" },
                  "PROVIDE" : { "result" : { "result" : "Calculation result" } }
                }
              },
              { "data_set" : { "data" : [ "file-multiplier" ], "value" : [ "result" ] } }
            ]
          }
        },
        { "commerce_line_item_unit_price_multiply" : {
            "commerce_line_item" : [ "commerce_line_item" ],
            "amount" : [ "file-multiplier" ],
            "component_name" : "fee",
            "round_mode" : "1"
          }
        },
        { "drupal_message" : { "message" : "[commerce-line-item:line-item-id]: File Multiplier = [file-multiplier:value]" } }
      ]
    }
  }

NOTE: This will still not update the price as the person is uploading files.


How to display exposed sort in views using one drop-down widget?

You can use Better exposed filters module for that purpose. It has such option to combine sort field and directions in one select list.


How can the divs added by default by Views be removed?

On the contrary, you NEED to select the boxes for field, label and wrapper, and select None in the drop down menu. This will get rid of the <div>.

The Add default classes has nothing to do with the HTML elements - only with the css classes it adds to the tag.

Additionally you can deselect Provide default field wrappers under Format > Settings

EDIT: So, testing confirms that there are NO divs for fields anymore if you uncheck Provide default field wrappers. See image. Why modify a tpl file if you can do this with the interface? The only divs you see in the image are the ones that separate rows in the Unformatted list output. "See, mom, no divs!"


hook_menu to change menu button item by checking group membership

Here is a sample code close enough to your question. It may need some modifications to its parts in order to meet your needs, but more or less you got the idea.

/**
 * Implements hook_menu_alter().
 */
function foo_menu_alter(&$items) {
  $items['alter/%gid/path']['access callback'] = 'og_user_role_callback';
  $items['alter/%gid/path']['access arguments'] = array(1);
}

/**
 * Determine if logged-in user has access to menu or not.
 */
function og_user_role_callback($gid) {

  // Get OG role of the user. Could be 'member', 'non-member' or 'Group administrator'.
  global $user;
  $group_type = 'node';
  $uid = $user->uid;
  $member = og_get_user_roles($group_type, $gid, $uid, $include = TRUE);

  switch ($member) {
    case 'member':
      return TRUE;
    case 'non-member':
      return FALSE;
    case 'Group administrator':
      return TRUE;
  }
}


How to disable the title field in a content type?

I think the Automatic Nodetitles module is what you're after:

  "auto_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.


how to change a theme through themekey on the contact page in drupal 7

I think setting drupal:path to contact should do the trick.


How to populate select field from View result like in

I don't have time to provide an exact answer, but something along these lines.

// Programmatically execute view
$view = views_get_view('sel_selistes'); //  view machine name
$view->set_display("entity_reference_1"); // view display name
// $view->set_arguments($arg) // looks like you don't have arguments.
$view->execute();

$view_results = []; // create array
// loop through results
foreach ($view->result as $row_id => $row) {
  // some php magic so you add to array like this $view_results[$nid_value] = $some_field_row_value;
}

$form['my_select_field'] = array(
  '#type' => 'select',
  '#options' => $view_results,
  '#title' => $this
    ->t('whatever'),
);


Follow these steps. From these steps I think your query may solved.

Clear caching from the drupal.
Clear caching from the database.
Clear browser caching.

& check. If the menu again shows then
Goto

Admin -> Structure -> Menu -> Management -> list links

& check

Clear Caching from the database (local server)

TRUNCATE TABLE cache;
TRUNCATE TABLE cache_advagg_aggregates;
TRUNCATE TABLE cache_advagg_info;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_update;
TRUNCATE TABLE cache_views;
TRUNCATE TABLE cache_views_data;


Manually invoking Ajax Commands when an ajax callback is not an #ajax form callback

Like @Gaius I don't know exactly what @Jaypan wants to achieve. This example might help to make this clearer:

        var response = JSON.parse(content);
        // Create a Drupal.Ajax object without associating an element, a
        // progress indicator or a URL.
        var ajaxObject = Drupal.ajax({
          url: '',
          base: false,
          element: false,
          progress: false
        });
        // Then, simulate an AJAX response having arrived, and let the Ajax
        // system handle it.
        ajaxObject.success(response, 'success');

Normally you set an URL in Drupal.ajax() and then use ajaxObject.execute() to run the Ajax request. This example from big_pipe.js only simulates the Ajax request and then runs the Ajax commands contained in content.


Alter the access of menu links before rendering

After some trial and error an researching and researching I found out how to get it done.

Case:
The aim is to avoid that any other user than the admin can access administration pages starting with path "/admin/config/*". The point is that we have a administrator role in our project who should have access to the menu administration pages (they need the permission "Use the administration pages and help" to get to this administration page). With this permission they also see the "Configuration" menu item in toolbar and all sub menu items like "System" but these pages are empty.

How to achive that by altering the access checks

First define your own RouteSubscribe class in folder/file your_module/src/Routing/AdminRouteSubscriber.php:

namespace Drupal\your_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class AdminRouteSubscriber extends RouteSubscriberBase  {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    $path = '/admin/config';
    foreach ($collection->all() as $routename => $route) {
      if (substr($route->getPath(), 0, 13) == $path) {
        $route->setRequirement(
          '_custom_access',
          '\Drupal\your_module\AccessChecks\CustomAccessChecks::access'
        );
      }
    }
  }
}

What we did here is to check the path of every route and if it starts with "/admin/config" it gets added our custom AccessCheck class defining the method "admimAccess" to be called.

Than go ahead and define your own access check class in folder/file your_module/src/AccessChecks/CustomAccessChecks.php:

namespace Drupal\your_module\AccessChecks;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResultAllowed;
use Symfony\Component\Routing\Route;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAccessChecks implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
    return AccessResultAllowed::allowedIf((int) $account->id() === 1);
  }
}

This access method has to return an implementation of AccessResultInterface. We say that access is allowed if the current user has the id 1.

Lastly you need to add these classes to the service container by defining your your_module.services.yml in your module's root folder:

services:
  your_module.route_subscriber:
    class: Drupal\your_module\Routing\AdminRouteSubscriber
    tags:
      - { name: event_subscriber }
  your_module.access_checker:
      class: Drupal\your_module\AccessChecks\CustomAccessChecks
      tags:
        - { name: access_check }

After rebuilding your cache it works.


Facet API and views contextual filters (facets block on non-search page)

OK, worked this out myself:

Use the contextual filters prefixed "Search:" in the list (not "Indexed node:". There are 2:
"Search: Fulltext search" and "Search: Indexed taxonomy term fields"

Not sure if Search: Fulltext search is ideal as I'm using it for place names and there are a few with more than one word.


How can override the title markup on a node page?

As expected as soon as I posted this question I found the solution..

If you use the template region--main-heading.tpl.php you can override title markup.


How do you build an auto-generating menu for forums?

Looking back at this, I realize I was asking two questions:

1) How do you configure a URL alias pattern for a forum topic in the format: [forums]/[container_name]/[forum_topic_name]?

Install and enable Pathauto. Then configure a URL alias pattern at admin/config/search/path/patterns in this format [node:taxonomy-forums:parents]/[node:taxonomy-forums:name]/[node:title].

2) How do you then add this Forum topic to a menu underneath a specific parent automatically?

Install and enable Menu Position. Add a Menu Position rule at: admin/structure/menu-position/add for Content Type: Forum topic and select the menu parent item for Forum topics.


Show WebForm Block through a link on a Page

This isn't possible at present, not automatically any way.

You could write some javascript to find all "/contact" links and append "/lightbox2" to it so it's "/contact/lightbox2". You would also need to add a rel="lightframe" to the anchor link. This would open the contact form in a lightbox when the contact link is clicked, and you could style the form with a page-contact-lightbox2.tpl.php template file in your theme's directory.

However, this will open the form in a iframe, rather than treating it like modal content which is what is done to the login form. The disadvantage to using an iframe is that the form isn't closed upon form submission, like with the login form. The advantage is that the iframe will add a scrollbar to accommodate the size of the content. If you want, you can treat it as modal content (just use rel="lightmodal"), but you'll need to specify the height and width of the lightbox container (see lightbox2 docs).

I'm not adding it to lightbox2 module at this time because there are too many modules that modify the contact form content, e.g. advcontact, contact_forms, content_attach, captcha, mollom, etc. These potentially could modify the size of the content, making it difficult for lightbox2 to estimate the outputted form size.

If enough other people request it, then I'll add the ability for lightbox2 to open the default contact form in a lightbox, but for now, this feature won't be implemented for the reasons outlined above.


I get success with this. It needs to be improved though, especially the '#language' bit. What I found to be important was to wrap the link field in a container and set '#tree' to true to group it under its key. And the link field is a multi-value field with a link title and url, so you have to take care of that.

function MYMODULE_block_configure($delta='') {
  $form = array();

  switch($delta) {
    case 'my_module' :
      // Text field form element
      $form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
      );

      //link field
      $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
      );
      $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und', // how to fix this??
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
          'title' => variable_get('link_title', ''),
          'url' => variable_get('link_url', ''),
        ),
      );
      break;
  }
  return $form;
}

/**
 * Implements hook_block_save().
 */
function MYMODULE_block_save($delta = '', $edit = array()) {
  switch($delta) {
    case 'my_module' :
      // Saving the WYSIWYG text
      variable_set('text_variable', $edit['text_body']['value']);
      variable_set('link_title', $edit['link_container']['link']['title']);
      variable_set('link_url', $edit['link_container']['link']['url']);
      break;
  }
}


Contextual filter in Views for taxonomy browsing

Since that moment I have messed with my views to a fubar state. But looks like I pinpont the rule of thumb that I haven't heard anywhere: when you set up a context filter, eg. for "Content: nid", you don't add it to the regular filter list on the left hand side. And you don't have to bother with %-style placeholders.
At any rate, thanks JoeS for your readiness to help. I bet you will have a bunch of chances to help me out, as I seem to attract all kind of Drupal surprises ;-)


is there a place in the .info file to set a url to check for updates?

Yes, you can use project status url:

  Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

See Writing module .info files (Drupal 7.x) for full details.


Trying to pull phone number and combine it with carrier, cannot find phone number variable

if you don't already have it, get DEVEL module. In your tpl file, use dpm($account); this will output the array. From there you can determine the proper element names.

it would be $field_phone_number[0]['value']; a trick to figuring out the exactly lineage is to progressively use dpm, ie: dpm($account), dpm($field_phone_number), dpm($field_phone_number[0]), etc. this is an easy one, but arrays can get in depth and complicated within Drupal

Devel:

  Helper functions for Drupal developers and inquisitive admins. This
  module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries).
      Also a dprint_r($array) function is provided, which pretty prints arrays. Useful during development. Similarly, a ddebug_backtrace() is
  offerred.


/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  // If your field is link field
  $form['the_field']['widget'][0]['uri']['#states'] = [
    // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
    'required' => [
      ':input[name="field_of_type_radio"]' => ['value' => '1'],
    ],
  ];
  // If your field is text field
  $form['the_field']['#states'] = [
    // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
    'required' => [
      ':input[name="field_of_type_radio"]' => ['value' => '1'],
    ],
  ];
}


You can pipe it to render:

{{ attributes.storage['data-quickedit-field-id']|render }}


how do display 404 while the url didn't exits

You can create two views. In one, using questions as URL, you add "Content: Nid" as contextual filter, and use the following settings for that contextual filter.

In When the filter value is NOT in the URL

Select Display all results for the specified field

In When the filter value IS in the URL or a default is provided

Select Specify validation criteria
As Validator, select Content
As Action to take if filter value does not validate select Show "Page not found"

The other view, using questions/mine as URL, would use "Content: Author uid" as criteria, and use a default value taken from the user currently logged-in.


Go to admin/structure/block and configure the Main Menu block

You want to go further you can Install Menu block module

So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!


Drupal Commerce: Set Order as Paid in Full

If you want to trigger the paid in full event you just need to make the order balance 0. You can do that by adding a payment transaction for the full amount to the order. The event is then triggered when that new successful transaction is saved.

The relevant Commerce function is

commerce_payment_commerce_payment_transaction_insert

/**
 * Implements hook_commerce_payment_transaction_insert().
 *
 * When a new payment transaction is inserted that is already completed, check
 * the order balance and invoke a Rules event if the order is paid in full.
 */
function commerce_payment_commerce_payment_transaction_insert($transaction) {
  // If the inserted transaction was marked as a success and placed against a
  // valid order...
  if ($transaction->status == COMMERCE_PAYMENT_STATUS_SUCCESS &&
    $order = commerce_order_load($transaction->order_id)) {
    // Then check to make sure the event hasn't been invoked for this order.
    if (empty($order->data['commerce_payment_order_paid_in_full_invoked'])) {
      // Check the order balance and invoke the event.
      $balance = commerce_payment_order_balance($order);

      if ($balance['amount'] <= 0) {
        // Invoke the event including a hook of the same name.
        rules_invoke_all('commerce_payment_order_paid_in_full', $order, $transaction);

        // Update the order's data array to indicate this just happened.
        $order->data['commerce_payment_order_paid_in_full_invoked'] = TRUE;

        // Save the updated order.
        commerce_order_save($order);
      }
    }
  }
}

The key part is here:

// Invoke the event including a hook of the same name.
rules_invoke_all('commerce_payment_order_paid_in_full', $order, $transaction);
// Update the order's data array to indicate this just happened.
$order->data['commerce_payment_order_paid_in_full_invoked'] = TRUE;

// Save the updated order.
commerce_order_save($order);

In any case, you'll need to create a valid transaction for the order to trigger the commerce_payment_order_paid_in_full event. Rules reacting to that event will expect the transaction object as an assumed parameter.


Populate article field based on user login

I dont think you need to assign the location for the user.

When a person adds a content that content is automatically assigned the author. So if manager A creates a content then its author field is populated with Manager A.

Now you can use this information in views.

If you are creating a view with all the information related to the location you could create a view with all the contents added by the particular person.


Show menu only when user ticks the checkbox

Go to admin/config/people/accounts/fields and add a boolean field.
In your MYMODULE_form_alter() add a '#type' => 'checkbox' form field and a custom submit handler.
Inside that custom submit handler save the checkbox value into the user's boolean field from step 1.
Inside your MYMODULE_menu_alter() call global $user and check that field's value $user->field_sell_themes and build the access control accordingly.


You can achieve that by using hook_form_alter function.

I've tested the following code on my instance. It's working fine.

Use the following code in your custom module.

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
        if ($form['#form_id'] == 'YOUR-CONTENT-TYPE_node_form') {
         $form['YOUR-FILED-NAME']['und']['#options'] = array (
       'Group1' => array(
          1 => 'Option1',
          2 => 'Option2',

        ),
        'Group2' => array(
          3 => 'Option3',
          4 => 'Option4',
        ),
    );
    return $form;
        }
    }


Try the following:

/**
 * Implements hook_drush_command().
 */
function mymodule_drush_command() {
  $items['list-site-users'] = array(
    'description' => 'Does a database cleanup.',
    'examples' => array(
      'list-site-users' => 'Retrieve list for all users',
    ),
    'aliases' => array('lsu'),
  );
  return $items;
}

function drush_mymodule_list_site_users() {
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $result = $query->execute();
  while($record = $result->fetchAssoc()) {
       print_r($record['name']);
  }
}

NOTE: Make sure you write the above code in mymodule.drush.inc file of any module.
Clear the cache and your drush command should work.


Commerce: query products and product variations

Commerce Products are entities, so you can query them exactly like any other entity (like you're already doing). You may consider the commerce API docs for entities to be poor, but that's simply because there aren't any - you can apply standard Drupal entity logic.

It seems the only thing you're missing is the platform filter that you mention; that's just a matter of adding a field condition to the EntityFieldQuery:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_product')
  ->propertyCondition('status', 1)
  ->propertyCondition('type', 'games')
  ->fieldCondition('field_platform', 'value', 'PS3')
  ->fieldOrderBy('commerce_price', 'amount', 'ASC');
$result = $query->execute();

Your mileage may vary if field_platform isn't a text field. For example, if it's a taxonomy term reference, you'll need to find the ID of the taxonomy term and use something like

  ->fieldCondition('field_platform', 'tid', 123)

Or if it's an entity reference field you'll need the entity ID and to use something like this

  ->fieldCondition('field_platform', 'target_id', 123)


As stated at the top of that documentation page, everything there is legacy and is no longer supported.

The feature request for being able to use commercial certificates with Aegir HTTPS (the officially supported way of running HTTPS now), is Add a 'manual' Certificate implementation.

So your options are either:

Write a patch yourself (and upload it to the issue), or
Pay us, the maintainers, (or someone else) to do it for you.


Why does max_allowed_packet need to be increased?

When your server is processing big queries, then you have to increase the value of the max_allowed_packet (or to shorten your queries if possible ?).

Big queries makes me think of Views. One way to find those queries is, to enable the "Show the SQL query" under admin/structure/views/settings edit a view and see how big its query is.

It is possible that if your content has been increased, your queries will have been increased as well (will return a large result row).

You can increase the max_allowed_packet, if needed, as MySQL says:

  It is safe to increase the value of this variable because the extra memory is allocated only when needed.


How to incorporate AMP in an existing theme?

The AMP project for Drupal has three parts. The AMP module, the AMP PHP Library, and the AMP Theme work together to provide valid AMP markup for nodes with AMP-enabled content types at paths with ?amp at the end of the URL.

From the AMP module page:

  The AMP module is designed to convert Drupal pages into pages that comply with the AMP standard. When the AMP module is installed, AMP can be enabled for any node type. At that point, AMP content becomes available on URLs such as node/1?amp or node/article-title?amp.

  The AMP PHP Library analyzes HTML entered by users into rich text fields and reports issues that might make the HTML non-compliant with the AMP standard. The library does its best to make corrections to the HTML, where possible, to make it more compliant with the AMP HTML standard.

From the AMP Theme page:

  The AMP Theme is designed to produce the very specific markup that the AMP HTML standard requires. The AMP theme is triggered for any node delivered on an ?amp path.

Some additional reading, an article describing the three in more detail on the official AMP blog: AMPing up Drupal.


Image uploading button is not appearing for authenticated users,only for admin

I just had the same issue and this is what I found to fix it.

If you have IMCE to control your file browser you must create a profile for each user role. For example, the website administrator (owner of the website) will have access to the file browser no matter what, but if you have another authenticated user with the administrator role, they will not have access to the file browser unless you add a profile to the administrator role. So to do this go to 'admin/config/media/imce' or if you would prefer the interface way, log in as administrator and click on "Configuration" -> "Media" -> "IMCE".

Create a new profile by clicking on "Add New Profile" link and configure the profile to your needs. Save the profile.

Then next to the administrator role (or whatever role you need this for), select that profile you just created and click save.

Now test on a sample administrator (or whatever role you configured) account.


There is two options using a custom module:

Disable access to this path using hook_menu_alter()

function MYMODULE_menu_alter(&$items) {
  unset($items['user/register']);
}

This option will send the user to an access denied page.
Redirect the user to the home page (or another one)

function MYMODULE_module_menu_alter(&$items) {
  $items['user/register']['page callback'] = 'MYMODULE_go_home';
}
function MYMODULE_go_home() {
  drupal_goto('/');
}

Inspiration: Disabling /node view and other hidden views in Drupal?

PS: I'm not sure why you want to remove /user ? For this special path you can also use hook_user_view().


Show User Information in Block from View

Go to /admin/people/permissions and tick the "View user profiles" permission for anonymous users:


Cannot print View title in View template


How to require one of two fields to be filled out?

Have a look at the Conditional Fields module.


Where can I put helper functions for my theme?

Helper functions is a bit vague for a description (so there may be better places where to put this, like a custom module), but theme functions are usually put into the template.php file of your theme.

It is not generally adviced to put much php code into your templates however (save for printing variables) - best practice usually calls for the use of alter hooks or other preprocess functions. Get a (small) overview here: template.php


Using #attached to attach js to form by a custom module

@NoSssweat is it possible only load for add/edit node and webform(not
  search form)? – CocoSkin

You can by utilizing hook_form_BASE_FORM_ID_alter

For node's add/edit form:

/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';
}

For Webform:

/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function mymodule_form_webform_client_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';
}


Answered in comment by Dimitris B:

Found answer, in administrator -> configuration at performance section i disable Aggregate JavaScript files which i had enabled, so i realize that i had a problem in my js code so i need to check it up, but after i disable it everything works perfect.


How to add an exposed filter to a view programatically?

Depends on the filter you need, but, let's say you want to filter by Node type, then you would use the following in a views.inc file included into your module within a hook_views_default_views() function.

$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
    'news' => 'news',
);
$handler->display->display_options['filters']['type']['expose']['operator'] = TRUE;

For a sample of what this file may look like, pull up the node.views_default.inc file in the views module. You can also create a view and choose to look at what the code behind it if you need the particular syntax for a filter. The option to export is found at the top right of the view within the edit screen. I would search hook_views_default_views() for additional information.


Simulate submission of custom form as a webform

Here's how to create a Webform submission programmatically:

global $user;
$node = node_load(YOUR_NODE_ID);

// Prepare the data. Do note that the keys in this array must match the elements
// in your webform.
$data = array(
  1 => array('Field one value'),
  2 => array('Field two value'),
  3 => array('Field three value'),
);

// Create the submission object.
$submission = new stdClass();
$submission->uid = $user->uid;
$submission->nid = $node->nid;
$submission->submitted = REQUEST_TIME;
$submission->remote_addr = ip_address();
// This is necessary to mark the submission as complete.
$submission->is_draft = FALSE;
$submission->data = $data;

// Store the submission.
module_load_include('inc', 'webform', 'includes/webform.submissions');
webform_submission_insert($node, $submission);

// If necessary, invoke the email sending for this Webform.
webform_submission_send_mail($node, $submission);

Hope this helps.


Get the latitude and longitude from the user ip

Converting an IP to a latitude and longitude isn't a good idea since the user could be using a proxy. A better way would be to use HTML5 geolocation, which tries to get a location based on a couple of parameters: IP, wireless connection, cell tower location, GPS ...

Try:

navigator.geolocation.getCurrentPosition(show_map);

function show_map(position) {
  initialize(position.coords.latitude, position.coords.longitude, 'title');
}

More info on HTML5 geolocation here, make sure you have a fallback in case the browser doesn't support geolocation or the user declines your request to share his/her location (graceful degradation).


Stop Mini Panels adding --1/2/3 etc to blocks

Drupal blocks aren't particularly aware of other blocks on the page, and you could legitimately have a mini panel block added with Panels and another  of the same added somewhere else with Drupal's regular block system or some other display module -  they would be completely unaware of each other and therefore without the appended numbers could end up with the same ID. Certain things in Javascript can break if two elements on a page  have the same ID, so it's pretty important to make sure this can't happen.

The best way to get a good stable clean ID for styling purposes is to add the mini panel block using  something with the panels/context interface (panels or page manager (comes with ctools, under Structure > Pages in menu) or panels everywhere etc), and use the block settings option to set an id that is specific and semantically relevant. It takes slightly longer in the short term, but saves a lot of trouble in the long term and gives you cleaner, more readable, more manageable HTML.

Generally speaking, replacing Drupal's default generated markup with clean lean semantic markup is a good idea (if somewhat tedious and time consuming).  Remember that Drupal's default auto-generated markup is intended for stability and flexibility in development more than it is for best practices in production. See also this similar common complaint about messy markup: Changing the HTML produced by Panels: Is it possible?


I think you are trying to add anchors to a node's alias to define multiple sections in a node, which is impossible since an anchor destination is not part of a path and therefor not part of an alias. For more information, see the W3 introduction on links in HTML.

Creating a anchor: If you would like to subsection your node's body, you should use anchors in your code:

 ...

If you're using the WYSIWYG module, make sure you've got the Anchor plugin enabled, so you can create the anchors through the nicely builtin anchor plugin's GUI, which makes it that much easier.

Linking to an anchor: After creating an anchor, you can link to that section by making a hyperlink as follows:

Link text

To build the above link in the Drupal-way:

<?php print l('Link text', 'path/to/node', array('fragment' => 'anchorOne')); ?>

Or to only build the URL including the anchor destination:

<?php print url('path/to/node', NULL, 'anchorOne'); ?>


When in admin overlay, submitting form over 400 times

Not sure what is exactly causing this, but maybe you can use a static variable as a workaround for this issue.

function mvp_form_test_test_form_submit($form, $form_state) {
  $sent =& drupal_static(__FUNCTION__);
  if(!$sent) {
    watchdog('mvp_form_test', 'Form submitted with text '.$form_state['values']['sometext']);
    drupal_set_message('Form submitted with text '.$form_state['values']['sometext']);
    $sent = true;
  }
}


Routes that need CSRF tokens have the _csrf_token: 'TRUE' route option. That's how URLs pointing to those routes automatically get a CSRF token.

So we need to look at \Drupal\Core\Access\RouteProcessorCsrf:

public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
  if ($route->hasRequirement('_csrf_token')) {
    …
    if (!$bubbleable_metadata) {
      $parameters['token'] = $this->csrfToken->get($path);
    }
    else {
      // Generate a placeholder and a render array to replace it.
      $placeholder = hash('sha1', $path);
      $placeholder_render_array = [
        '#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
      ];

      // Instead of setting an actual CSRF token as the query string, we set
      // the placeholder, which will be replaced at the very last moment. This
      // ensures links with CSRF tokens don't break cacheability.
      $parameters['token'] = $placeholder;
      $bubbleable_metadata->addAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]);
    }
  }
}

So there we can see that if $bubbleable_metadata is NULL, then we generate the CSRF token right away. $bubbleable_metadata being NULL signals to the CSRF route processor that the URL is being generated in a context where no cacheability metadata and attachments can be bubbled (e.g. when generating a URL to be sent in an e-mail). The downside is that the HTML containing this URL will then be uncacheable (well, very poorly cacheable), because the CSRF token is depends on the session.

That's why in the other case, where $bubbleable_metadata is a BubbleableMetadata instance, that signals to the CSRF route processor that the URL is being generated in a context where cacheability metadata and attachments can be bubbled (e.g. when generating a URL to be rendered in some HTML). So there we generate a placeholder token that will be replaced with the CSRF token, and specify a "placeholder" attachment that will ensure that placeholder token is replaced with a CSRF token at the last possible moment. Consequently, the HTML that this URL ends up in is still perfectly cacheable, because the URL is cacheable.

Now that problem has been confirmed. If this happens in a preprocess function, as the following one, then you end up with $variables['url'] = GeneratedUrl(…). Twig ought to bubble the cacheability metadata and attachment metadata in that object, but it does NOT, in all versions of Drupal 8 before 8.1.2. We're fixing this for Drupal 8.1.2 at https://www.drupal.org/node/2575519.

function hook_preprocess_HOOK(&$variables) {
  $variables['url'] = \Drupal::url('mymodule.test');
}


Ignore parts of the url or dynamically rewrite/alias the url

Subpathauto might do what you need even if it wasn't written for that exact use case. https://www.drupal.org/project/subpathauto

Subpathauto was written to handle the case where those extra arguments at the end of the string are meaningful and the first portion of the string is an alias. For that to function it must use hook_url_inbound_alter (you were on the right track!) to look up the first section of the string.

Even if this module isn't an exact fit the code within it is a good starting point.


Drupal 7 - How to apply Image Styles to a User uploaded logo for a theme

You should be able to alter the logo-path in hook_preprocess_page and replace the logo path with the path of the transformed logo:

function mytheme_preprocess_page(&$variables) {
  $variables['logo'] = image_style_url('my_image_style', $variables['logo']);
}

Didn't try it out, but it should work somehow this way.

edit: there is a LOT of "logo" in my first sentence ;)


How can I affect a custom block to a custom page/view in Drupal 8?

Of course that you can restrict on which pages you want to show block. When you edit block you can select specific pages where block will show up.
But if you want more control you should consider to use Panels module. I recommend you to check that module and see if that will help you.


In Method 2 you want to add the form as an element in the $build array.

Should be something like this:

$build['my_form'] = \Drupal::formBuilder()->getForm(Drupal\myModule\Form\myModuleForm::class);

Also you don't need to return anything, $build is passed by reference, so anything you add to it will stick.


Drupal 7 Captcha in all webforms or per content type webforms

You could add the following code to your template.php

if (strstr($form_id, 'webform_client_form')) {
        $form['my_captcha_element'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'image_captcha/Image',
        );
    }

this should be placed inside the yourthemename_form_alter


View display plugin "entity reference" not using translation

Comparing TermSelection::getReferenceableEntities and ViewsSelection::getReferenceableEntities it seems like the Views entity reference selection plugin doesn't translate the entity before returning the entity labels. It should work with a core patch adding one line:

/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php:

public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
  $display_name = $this->getConfiguration()['view']['display_name'];
  $arguments = $this->getConfiguration()['view']['arguments'];
  $result = [];
  if ($this->initializeView($match, $match_operator, $limit)) {
    // Get the results.
    $result = $this->view->executeDisplay($display_name, $arguments);
  }

  $return = [];
  if ($result) {
    foreach ($this->view->result as $row) {
      $entity = $row->_entity;
      // add this line to translate the entity
      $entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity);
      $return[$entity->bundle()][$entity->id()] = $entity->label();
    }
  }
  return $return;
}

Edit:

This won't be necessary anymore, when https://www.drupal.org/project/drupal/issues/2174633 is fixed, then resolving the underlying problem, that the selection plugin ignores the views output.


How do I programmatically remove a block?

You can use hook_preprocess_html(). For example, to remove the system navigation block from the "sidebar_first" region, define the following hook in your MODULE.module:

function MODULE_preprocess_html(&$variables) {
  if($variables['page']['REGION']['BLOCK'])
    $variables['page']['REGION']['BLOCK']['#access'] = FALSE;
}

with REGION = sidebar_first and BLOCK = system_navigation.


Add html5 placeholders to node_add inputs

To add placeholders, or any custom attributes, you need to dig deeper: implement appropriate hook_form_FORM_ID_alter. For node add/edit form, it will be mymodule_form_node_form_alter. First parameter is &$form - as you can see, it is taken by reference, so changes made to it are carried outside the function. Use dpm($form) to find appropriate element. Once you do, use #attributes to add attributes you want.


How do I get the menu title via the menu name, Drupal 7 API

menu_load('menu-name');

Returns title, description and menu_name for this menu.
https://api.drupal.org/api/drupal/modules!menu!menu.module/function/menu_load/7


What function/method should I use for file_directory_path()?

You can use the following code.

$real_path = \Drupal::service('file_system')->realpath(file_build_uri(''));

On my test site, it returns '/Library/Server/Web/Data/Sites/avpnet/sites/default/files'.

You can also pass a filename to file_build_uri().

$real_path = \Drupal::service('file_system')->realpath(file_build_uri('file.jpeg'));

With this code, I get '/Library/Server/Web/Data/Sites/avpnet/sites/default/files/file.jpeg'.


Views and contextual filter as user id from url

Create a new Views view with Format, Fields, and Filter criteria configured as needed.

Then do the following:

Under Advanced, add a new Contextual filter for Content:
Author uid.
Choose Provide default value and select User ID
from URL.
Under Page settings, set Path to user/%/myview.

Now when you navigate to user/1/myview you should see content from user 1.

For Flags you need to add a relationship for the flag and filter by it. I believe this answer would help with that.


How can I listen for drupalOverlayBeforeClose in custom jQuery?

You need to use the following code,

jQuery(document).bind('drupalOverlayBeforeClose', function(event) {
   // your code
   return false // This will prevent the overlay from closing.
});

click, dbclick and other methods are shortcut methods for bind('click', function(){}), bind('dbclick', function(){}) respectively. However there is no shortcut method called drupalOverlayBeforeClose, that's why the following code didn't worked,

$(document).drupalOverlayBeforeClose(function(event) {

});

So you need to bind drupalOverlayBeforeClose explicitly using bind. If you return false in your callback, then the overlay won't be closed.

Hope this clarifies the answer.


Leveraging field_get_items variable in a custom field template

You need TEMPLATE_preprocess_field() function at template.php

You can use this preprocess function in same way as you are doing for NODE. Like -

function MYTHEME_preprocess_field(&$vars) {
  if ($node = menu_get_object()){
    $node = $vars['node'];
    $field_image_items = field_get_items('node', $node, 'field_image');
    $vars['alt_caption'] = $field_image_items[0]['alt'];
  }
}

Then go to your TPL made for your particular field and print it where ever you like just like you have mentioned --

<?php print $alt_caption; ?>

And it will work like charm!! I have implemented like this several times.

But yeah...don't forget to clear your cache after this implementation.


Error when aggregation is turned on in Views

I finally found the answer for this. My view had a group picture; removing the group picture, turning the aggregation on, and putting back the group picture field solved the problem.

It's a problem others have had and that's how they all fixed it; See https://drupal.org/node/1809584.


using hook_form_FORM_ID_alter with #states

Okay, I figured it out. Here is what I ended up with:

    function lodestar_form_user_profile_form_alter(&$form, &$form_state) {
    dpm($form);
    $form['field_your_nonprofit_connections']['und']['#states'] = array(
        'visible' => array(
            ':input[name="field_affiliation_type[und][Nonprofit]"]' => array('checked' => TRUE),
        ),
    );
}

This code got the element to toggle appropriately. Whew! I'm glad I finally solved it. Hopefully this question and answer will help someone else. It looks like the main thing I did wrong was having the incorrect ":input[name." The way I finally figured it out was by looking in the HTML itself via the element inspector. I should have tried that a long time ago.

Interestingly, the #states element never did show up in my dpm($form) output. I'm not sure why that is the case, but, apparently it doesn't need to show up there, because it is working fine without it.


Prevent the loss of EXIF using imageCache does not work

Drupal (7 by itself, 6 via ImageCache) uses GD library. GD cannot handle EXIF, so if EXIF are ever kept during operations, it's more by accident than by design. If you need to keep EXIF, either avoid any processing based on GD (and that means any Drupal and ImageCache provided operations, both in Drupal 6 and 7), or save EXIF to text field on first upload, for example with EXIF Custom, and then add it back on download.


How to access current amount of earned userpoints in a Rules Condition?

There doesn't seem to be some Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn Execute custom PHP code condition, e.g. to do some type of comparison):

global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

However, there is a Rules Action "Load user points of a user", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.

If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules event that you want):

{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Use the Rules UI to import the above rule in your own site if you want.


SelectQuery row_number won't work with PDO

In order to count the number of occurence you can use groupBy and having cluases but as you mention above your format is completely different. So it is not feasible to you. Try this one may be it'll helpful to you.

$query = db_select('temp', 't');
$query->fields('t',array('a','b'));
$query->orderBy('t.a');
$result = $query->execute();

$field_sum = 1;
$prev = NULL;
foreach ($result as $record) {
   if ($prev ==  $record->a) {
      $field_sum++;
   }
   else {
   $field_sum = 1;
   }

   echo "\n a " . $record->a . " | b " . $record->b . " | Counter ". $field_sum;
   $prev = $record->a;
}

Also ensure that these list of function can't be chained:

addExpression()
addField()
addJoin()
extend()
innerJoin()
join()
leftJoin()
rightJoin()


How do you implement text color on taxonomy terms

Here are steps you need:

Install jQuery Colorpicker module.
In the vocabulary for terms for which you want to add colours, add a jquery color picker field.
So when you create each term, you also select a colour for it while creating. in this way each taxonomy term will have a colour.
now in the taxonomy term preprocess template, write something like this to grab the color and pass it as variable.

function themename_preprocess_taxonomy_term(&$vars) {
  $colour_code = $vars['taxonomy_term']->field_yourcolorfieldname['und'][0]['value'];
  $vars['colour_code'] = $colour_code;
}

Then copy the taxonomy-term.tpl.php to your theme folder, and you will be having $colour_code variable giving you the colour code of the term. you it to provide an inline css.

Remember, if overriding taxonomy term template is not what you need, or you want to have it elsewhere, whenever you get $term object, you can get the colour code through $term->field_yourcolourfieldname['und'][0]['value'].


How to sort terms in Views by their weight

I've done same setup and working fine. Might be you've missed something. Import the below code into your view.

$view = new view();
$view->name = 'List of Tags';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Tags List';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'List of Tags';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Filter criterion: Taxonomy term: Vocabulary */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  1 => '1',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'tags-list';
$translatables['sdf'] = array(
  t('Master'),
  t('List of Tags'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);


The fact that the stable release has an unusual version number doesn't mean there is anything wrong with it.

It's just the way they are doing there releases.

If you look at all the crm core releases you can see that the first stable release was 0.9.

I would guess they have done this so that they may be able to get more people using it and fix any issues that arise before having a 1.0 release.

So 1.0 will be the next major release.

Then they use versions 0.91, 0.92, 0.93, ... as the intermediate level releases and for minor releases in between those they use numbers like 0.911, 0.912, 0.913, ....

When choosing a version of any module this would be my advice:

Use the latest stable release.

If you encounter any problems with latest stable then check the issue queue for possible fixes and if you need a patch to apply to latest dev or latest dev has already fixed the problem then try using it.

Remember though to test to make sure everything still works as it should as the dev version may have introduced new issues even though it fixed your previous issue.

Also take a database backup before updating module versions in case the newer version is broken and you need to roll back.

Another reason you might want to use dev would be if you know that there are new features in dev that you want that aren't in the latest stable.

But really, if there is a stable release (especially a recommended stable), don't use the dev version instead of the stable release unless you have a good reason to.

Unusual version numbering is not a good reason.


Your only defining the function, your not calling it.

   print theme('vimn_article_template', $vars);

Think you also have to implement hook_theme_registry_alter() for Drupal to pick up your template.

Maybe you can use a process function to assign this to a variable for the template.

function YOURMODULE_preprocess_HOOK($variables) {
   $output = theme('vimn_article_template', $vars);
   // etc, etc...
}


LimeSurvey RemoteControl JSON_RPC API from Drupal

SSL certificate in the Lime Survey test server was expired. Renewed the SSL cert.


How do I create an exposed filter for a localized taxonomy term?

you need to install i18nviews module
and then use one of these:

Content: Has taxonomy term (translated)
Content: Has taxonomy terms (with depth, translated)

instead of regular filters


Can't get values from $form in submit handler?

Please check your submit handler signatures once ... Ideally submit function should be something like below... You can try using drupal set message for same like code given below !

function form_example_tutorial_7_submit($form, &$form_state) {
  drupal_set_message("I am inside submit handler. Printed form values below");
  drupal_set_message("
" . print_r($form_state['values'], 1) . "
");
  // $form_state['values'] is used to extract submitted values !
  drupal_set_message("Printing Form Structure Below !");
  drupal_set_message("
" . print_r($form, 1) . "
");
}


How to change OG "subscribe to group" link text?

You don't necessarily need to use the string overrides module. You can add string overrides directly in your settings.php.
$conf['locale_custom_strings_en'][''] = array(
  'Subscribe to group' => 'Join this Tribe',
);

For more information, see Change default strings (text) without using full translation system.


Just figured it out.

After installing all above modules, we still have to visit the page defined by the routing and switch it to another language (non-English).

Then system would automatically pick up all strings in the page needed to translate, including the title.

The source string is case sensitive.


How do I show a 403 error page when the server returns a 403 error code?

What you need to do is to configure nginx to serve a drupal page that generates a 403 page. There are severals ways to do this.

The easy solution is to route the traffic to Drupal (the index.php file), which would generate a 404 since the page doesn't exist in Drupal.

I think doing

location ~* \.(txt|log)$ {
  try_files @rewrite
}

should accomplish this for .txt and .log files. It should try to serve the file from Drupal. By default this will be a 404, but you can add the a route for specific files and return 403 instead.


jQuery slideshow behaving oddly in Drupal

This because you have two slider block in your durpal website. The second one is hidden in the footer section. Block id is : block-multiblock-7.

Both of these block are having same DOM structure, so in the following scenario your slider will break.

Breaking Scenario:
Main slider -> 5th Image is active.
Footer Slider -> 3th Image is active

Then your condition fails:

if (nextImg.length == 0) {
            nextImg = $(".header-slideshow-image:first");
            }

Hope you are clear with my point.

Thanks


How to filter content by a specific taxonomy term when vocabulary allows multiple values?

To solve the problem:

Removed the relationship with "Places" vocabulary and used the field "Places to play" to create the field groups, checking the "Use rendered output for a group of rows" option.
Unchecked the "Display all values in the same row" option for "Places to play" field.
Created a contextual filter for "Places to play" field to receive the value via URL.

As a result I now get what I was expecting.


Always wrap all strings in t() so that it can be translated. And always use english for strings in the source code because Drupal assumes that it is english. Even if your site is in a different language (You can translate it afterwards through the UI or create .po files).

The other one doesn't matter. Technically, it's an integer, so without quotes but it will be converted to a string when displayed anyway.


That module provides a very basic API only; no UI, no methods to display/format data, and no integration with the Views module.

It currently provides developers with:

A database connection class for Oracle
A simple Oracle-specific version of db_query
A simple Oracle-specific version of db_query_range

and literally nothing else.

So yes, in order to see any data using this module, you're going to need to create your own module which uses the couple of query functions it provides, and displays the results in whatever way makes sense.

For something more automated, you could try the technique mentioned here to hook into Views and force it to use a different database for certain tables (which can theoretically be in an Oracle DB). I've never tried that so I can't comment on its effectiveness, or if it's genuinely even an option. Something tells me that you'd need a PDO connection to Oracle for that to work, but I might be wrong.

As an aside, the line you quoted from the readme looks like a TODO note; the maintainer is probably saying that the functionality hasn't been implemented yet, but that developers who want to make proper use of the module will probably find it beneficial to implement that per their requirements.


How to create new group for products in drupal commerce?

I guess you need to create a new product type (since you want to add "parameters", which I assume are "fields") :

/admin/commerce/products/types/add

Then add fields to your new product type (picture, size, screen resolution for phones...), choose chich fields will be used as attributes (like size for shirts), then create products using this new product type, then create a new product display (which is a regular node with a multiple product reference field) for this product type and reference your products with the product reference field on the product display. You can also use an existing product display to display all your types of product (in this case you have to allow the product display's product reference field to reference products of the new product type first).

Note that if you have several attribute fields, you need to create as many products as there is possible combinations. Say you have 3 sizes (S, M, L) and 2 colors (red, blue), you need to create 6 products :

S blue
S red
M blue
M red
L blue
L red

You may consider using Commerce Product Option or similar module for your use case.

It can be confusing at first, but the Drupal Commerce way of dealing with products is really effective.

Good luck

EDIT

To make a field act as an attribute on your add to cart form (i.e shirt sizes : a drop down with XS, S...), you need to define a field on your product type (see my URL), then on the manage field form (admin/commerce/products/types/your_product_type_machine_name/fields/your_field_machine_name), you need to check the checkbox "Enable this field to function as an attribute field on Add to Cart forms".

Then you create your product, one with size S, one with size M, one with size L (so you have 3 products, one per size), on your product display you set up references to the 3 product variations (S, M, L), and there it is, on your product display page you'll find a drop down allowing to choose the size in the add to cart form. When selecting a size, the node fields are refreshed with AJAX (you can see it as an AJAX product selector).

This system allows you to have different SKUs and prices for each variations. Typically, everything that needs to be different across products variations (SKU obviously, but maybe price, maybe the product picture) needs to be represented by a field on the product (each product has its own field value). Everything that is the same across product variations can be represented by a field on the product display (which is common to several products.

See here for official doc.

Hope it helps and sorry for my english, not my first language.


Meta tag module not visible under individual node

When the metatag module is installed, you can create a metatag field in drupal just like creating a textfield, and can be reused in other content types.


Multi language with different layout drupal 6

John,

This question has already been answered here:
  Page template suggestion per language?

Cheers,


Based on @Gaydabura clues, I've created a module.
Here's the answer :

1. use hook_menu to define you own path

function toot_menu() {
  $items = array();
  $items['toot/import'] = array(
    'page callback' => 'toot_callback',
    'title' => 'Import tool',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

2. write function using docs to parse your data

function toot_callback($key = '') {
  if ($key != 'defined_key') {
    return t('Unauthorized access');
  }
  else {
    $myFeed = feeds_source('feed_unique_id');
    while (FEEDS_BATCH_COMPLETE != $myFeed->import());
    return t('Import successfull');
  }
}


Programmatically create user reference field

Check if Entity Reference Autocomplete  module helps you. The module page says

  This module defines a new form element type, called "entityreference",
  that allows developers to add autocomplete fields to forms, so that
  users can reference any entity in the same way they would do through
  an Entity Reference field.


Is the Workflow module a Symfony component?

No, the Workflow module is not a Symfony component.

As for what you found, the first list are the Drupal core dependencies, which include its dependencies from Symfony components.
Under the replace section, you just find a list of Drupal core modules. You can understand they are modules because they are listed as drupal/<module machine name>, while the Workflow component would be listed as symfony/workflow.


Feeds module will not unpublish old feeds

I am looking to solve the same problem. So far the best I have found is a patch for the Feeds module: http://drupal.org/node/1240366

EDIT: That was a poor answer, because I did not test it. Also there is a long discussion in the "Sync or Cache mode" issue: http://drupal.org/node/661314 . Posts #114 and #119 have the two leading solutions (and #114 is more sophisticated).


Webform get all submission for a node by date

It seems it's not possible directly. See webform_get_submissions date range filter issue.

From taht issue:

  We now have built-in range functionality in #1237660: Add date range
  or "last X submissions" to CSV/Excel download. That patch just uses
  the existing ability of webform_get_submissions() to filter by SIDs,
  which would probably work in your situation too as long as you can
  retrieve a list of SIDs by date.

So you have to build a query to retrieve a list of SID's bty date and then pass it to webform_get_submissions.


How do I make link act like a view or a view look like a link?

Easiest way to achieve above is using Views
Create a new view with block view

Sort Content by Post Date
Select fields as Content Display and show only one item
Enable the block by Navigating to blocks list page "admin/structure/block"

Please find the view code which you can simply import using "admin/structure/views/import"

$view = new view();
$view->name = 'latest_node';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Latest Node';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Latest Node';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');


Caches may be stale. Clear and re-test. Even disable your JS aggregation/minify, then have Drupal regenerate the aggregated JS (after testing with it off to see if that fixed the issue).
If you also use the jquery_update module, you may need to update your jQuery library.
Sometimes replacing the modules with their DEV versions help fix the issue, because sometimes there's small bugs that get fixed in DEV first before a new stable update is tagged and released.


How do I create a redirect after using pathauto_node_update_alias()

I'd have a look at redirect_path_update and hook_path_update and maybe consider using node_save() instead of writing the paths directly.

If you're going to write them directly with pathauto_node_update_alias(), you may as well just write paths aliases and redirects directly to the database instead of wasting time node_load()ing all the nodes.


How to make Forena render my SVG Graph properly?

The issue you described in your custom graph, is pretty sure similar to what is also happening when viewing the delivered graphs. So make sure that the delivered graphs work before moving on to custom graphs, such as the SVG Graph Demo, which is one of the delivered SQLite sample reports and graphs. Visit relative path /reports/sample.svg_demo in your own site. If you don't get the very same graphs in your own site, then use this checklist to get that issue resolved:

After you installed/enabled Forena, complete the required setup to Enable SVGGraph library (reports/help.setup#svggraph in your own site is where you can find the same). Pay special attention to this part documented around there:

  If you don't see a nicely formatted graph, but only some square with a gray background (about the size of the SVG graph you should see if it would have worked), or you're getting some error messages, you may want to checkout the issue queue on Drupal.org (search for html filter) ...

Obviously, if you change "gray" to "white", your first screenprint is pretty similar to "... some square with a gray background ..." (more details on that "html filter" in the next bullet).
Quite often the reason why Forena doesn't seem to render SVG Graphs correctly, is because the input format used by Forena is simply stripping out the SVG tags. To remedy this, this is what's needed:

  go to admin/config/content/forena in your site and ensure that the Text Format specified does NOT strip out SVG tags.

Additional info: have a look at "Prepare a text format to be used by forena" within the Installation and Configuration section of the Setup guide. At the very end of it there is this note:

  Especially if you're planning to use SVG graphs it is important to avoid that tags are being stripped out, as this could cause such graphs to not be shown at all or with errors.


Programmatically delete pathauto alias pattern?

Ended up throwing the following into my_module.install

/**
 * Deletes the product_nodes path alias. Check watchdog for error in case of failure.
 */
function my_module_update_8001(){
  $alias_id = 'product_nodes';
  if($alias_entity = Drupal\pathauto\Entity\PathautoPattern::load($alias_id)){
    try{
      $alias_pattern = $alias_entity->getPattern();
      $alias_entity->delete();
      return t('Successfully deleted @id PathAuto pattern. If this was done in error, you can recreate it by using the pattern: @pattern.',
        array(
          '@id'=>$alias_id,
          '@pattern'=> $alias_pattern,
        )
      );
    } catch(Exception $e){
      \Drupal::logger('my_module')->error('Encountered the following error while trying to delete the @id path alias pattern: @error',
        array(
          '@id'=>$alias_id,
          '@error'=>$e->getMessage(),
        )
      );
      return 'Failed to delete @id PathAuto pattern. Check the error log for details.';
    }
  } else {
    return t('No PathAuto pattern found with the ID @id.',
      array(
        '@id'=>$alias_id,
      )
    );
  }
}


Side-by-side contact form and GMap using panels

I found a way:

I enabled "GMap Macro Builder" which comes with the GMap module.
Added a text format by enabling filter "GMap Macro expander" at the page "admin/config/content/formats/add" and named the text format as "Gmap Macro".
Created a map macro at the page "map/macro" to paste into a node.
Created a node at "node/add/page" by pasting the macro text copied from the step 3 into the node body, chose a text format "Gmap Macro" which was created from the step 2 and gave a title 'Location'.
Created a panel page with two columns layout and url "contact-us". Added the contact form to the left column.
Added the existing node "Location" created from the step 4 into the right column.
Created a main menu link with the path "contact-us" which is the panel page url.

Finally, I got a contact form with a google map side-by-side.

Required modules:
1. Chaos Tool Suite ( Chaos tools and Page Manager enabled )
2. Panels ( Panels only enabled )
3. GMap ( GMap and GMap Macro Builder enabled )


Respect parent's node access level (Book)

I had a similar issue where I wanted the book main page's author (aka owner) to be able to edit all the lower level book page's even if they did not create the pages.

My solution was to create a custom module called 'Book author access' (http://drupal.org/sandbox/jrockowitz/1396474), which use the 'ACL' module (http://drupal.org/project/acl) to control a book's pages  access levels.

The 'Book author access' module does propagate the view, update, and delete permissions of the main book page to all to lower level pages, so it is possible that if you use the 'Content Access' module (http://drupal.org/project/content_access) and limited the view access to the book's main page it would solve your problem.

If you are not a developer then my answer might not be that useful...sorry.

As noted in my comment, I think the Book access module probably better addresses your requirements, just look at the below screenshot.


changing display depending on fields value

Another approach is to use MY_THEME_preprocess_node(&$variables) in template.php and build your logic according to $variables array elements (e.g. $variables['field_priority']). Example:

function MY_THEME_preprocess_node(&$variables) {
  if($variables['type'] == 'page') {
    $priority = $variables['field_priority'];

    if($priority > 0 && $priority < 2) {
      // do_first_logic()
    }
    elseif($priority > 2 && $priority < 4) {
      // do_second_logic()
    }
    // .... so on
  }
}


How to add custom content before hook_form()

You can use hook_form_alter() to add a 'markup' element to the form, with a negative weight so that it floats to the top. For example:

mymodule_form_alter(&$form, &$form_state, $form_id) {

  // Only act on my module's form.
  if ($form_id != 'mymodule_form') {
    return;
  }

  $form['top'] = array(
    '#type' => 'markup',
    '#markup' => 'This will be at the top of the form!',
    '#weight' => -100,
  );
}


Date with an option for end date being either a date or "ongoing"

You can create an additional field named Project status with 2 options Done and ongoing. Then using the Conditional fields module, show the date field when Done is selected and hide it when ongoing is selected.


storing value in session with ctools wizard

you cannot use form_state. every step will have it's own.
cache the date with ctools_object_cache_set


How to hide/remove "Request New password" link in Drupal 7?

this will remove it from the render array before it is printed. In your theme's template.php, add:

function MYTHEME_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'user_login_block')
    {
        $form['links']['#markup'] = '

Create new account

';
    }
}

Basically, it is just rewriting the markup for the links in the user login block. You can tweak this to theme as well. this should only apply to the user block


Values disappear in $form_state['values']

You have to move the code for changing form elements from ajax callback to form build (which includes hook_form_alter()). The form build is executed for every ajax request before the callback function is called. In the callback you are not allowed to change the form array. Put only code there to return form elements.

More information: Ajax Forms in Drupal 7

Quote:

  Changes to the form must only be made in the form builder function
  (ajax_example_autocheckboxes() in the example here), or validation
  will fail. The callback function must not alter the form or any other
  state.


How do I change the temporary directory without using any administrative pages provided by Drupal?

In Drupal 7 the temporary path is stored in the variable file_temporary_path, so you can either update the entry in the variables table with a SQL-query. Or you can use Drush:

drush vset file_temporary_path [some_new_path].


How to create more than 1 block with different .tpl (theme) file in a single module?

Block code from custom template is here

 /**
 * Implements hook_theme().
 */
function my_custom_block_theme() {

    $theme = array();

    $theme = array(
        'my_custom_block_output' => array(
            'variables' => array('items' => array()),
            'path' => drupal_get_path('module', 'my_custom_block') . '/templates',
            'template' => 'block--my-custom-block'
        ),
        'my_custom_header_block_output' => array(
            'variables' => array('items' => array()),
            'path' => drupal_get_path('module', 'my_custom_block') . '/templates',
            'template' => 'block--my-custom-header-block'
        ),
);

    return $theme;
}

/**
 * Implements hook_block_info().
 */
function my_custom_block_block_info() {

    $blocks['my_custom_block_output_block'] = array(
        'info' => t('Custom one'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );

    $blocks['my_custom_home_block_output_block'] = array(
        'info' => t('Custom two'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
  return $blocks;
}

**
 * Implements hook_block_view().
 */
function my_custom_block_block_view($delta = '') {
    $block = array();
    switch ($delta) {
        case 'my_custom_block_output_block':
            $block['subject'] = t('Block one');
            $block['content'] = _my_custom_block_block_content();
            break;
        case 'my_custom_home_block_output_block':
            $block['subject'] = t('Block 2');
            $block['content'] = _my_custom_home_block_block_content();
            break;
 }
    return $block;
}

/**
 * Callback implemented by hook_block_view().
 */
function _my_custom_block_block_content() {
    //Your custom values for output in $items
    $items = get_data();
 $output = theme('my_custom_block_output', array('items' => $items));
return $output;

}
function _my_custom_home_block_block_content() {
   //Your custom values for output in $items
   $items = get_data();
 $output = theme('my_custom_header_block_output', array('items' => $items));
return $output;

}

 //Data to be output
 function get_data(){
     //Your custom code
    }

Template file(.tpl) should be in "template" directory
Eg :

template/block--my-custom-block.tpl.php
template/block--my-custom-header-block


Commerce Stripe is a bit of a mess at the moment.  There are lots of issues that need to be fixed as you can see in the project issue queue.
You are probably experiencing the bug described on Stripe\PaymentIntent instance has invalid ID, but there is a longer discussion about how to handle this at [meta] SCA, the Stripe Review pane and recurring payments.
Basically, the issue is that Commerce Stripe does not generate a payment ID unless you go through the review pane first.  That means that if you configure a standard Commerce checkout flow and go through that flow (login -> cart -> checkout, etc.), then the module will probably work.  If not, you will spend hours searching the issue queue to try to debug the module.
Source: Have spent several frustrated hours over the past couple years with Commerce Stripe.
If it helps, I'm currently using the following patches just to get the module to work on my site:
    "drupal/commerce_stripe": {
        "do not load stripe library on every page": "https://www.drupal.org/files/issues/2020-02-03/3083393-21.patch",
        "skip review step by autosubmit": "https://www.drupal.org/files/issues/2020-09-16/commerce_stripe-3171411-2.patch",
        "fix 1112 errors https://www.drupal.org/project/commerce_stripe/issues/3177168": "https://www.drupal.org/files/issues/2020-10-16/3177168-2_commerce_stripe-fix_address_errors.patch",
        "fix TrustedCallbackInterface warning https://www.drupal.org/project/commerce_stripe/issues/3168822": "https://www.drupal.org/files/issues/2020-10-09/PaymentMethodAddForm%20needs%20to%20implement%20TrustedCallbackInterface%20for%20Drupal%209-3168822-14.patch"
    },


How to use entityQuery to find nodes with a specific multi-value field containing one specific value (and no others)?

So it appears entityQuery() can't do this, but entityQueryAggregate() can. Below is an example that achieves the goal of the original post:

$thing_id = 101;
$q = \Drupal::entityQueryAggregate('node')
  ->condition('type', 'group')
  ->condition('field_things', $thing_id)
  ->groupBy('nid')
  ->conditionAggregate('field_things', 'COUNT', 1);
$res = $q->execute();

Running dpm($res) will show:

Array
(
  [0] => Array
    (
      [nid] => 85
      [field_things_count] => 1
    )

  [1] => Array
    (
      [nid] => 33
      [field_things_count] => 1
    )

  [2] => Array
    (
      [nid] => 57
      [field_things_count] => 1
    )

  [3] => Array
    (
      [nid] => 54
      [field_things_count] => 1
    )
)


How to add a submit button in an HTML table?

Assign an id to the button and use Jquery,
set the $idUser in a data attribute example :

 <button id="buddon-id" data-user="<?php echo $idUser;?>" >button</button>
    <script>
    $("#button-id").on("click", function(e){
       userid = $(this).attr("data-user");
    };
    </script>


Entity wrapper save using db_transaction()?

I finally found an explanation of what happens in this case in the Transactions documentation.

While we cannot declare functions "transactional" in PHP, we can emulate Java's nesting logic by using objects with constructors and destructors. A function simply calls "$transaction = db_transaction();" as its first (or nearly first) operation to make itself transactional. If one transactional function calls another, our transaction abstraction layer nests them by performing no transactional operations (as far as the database sees) within the inner nesting layers.
To start a new transaction, simply call $transaction = db_transaction(); in your own code. The transaction will remain open for as long as the variable $transaction remains in scope. When $transaction is destroyed, the transaction will be committed. If your transaction is nested inside of another then Drupal will track each transaction and only commit the outer-most transaction when the last transaction object goes out out of scope, that is, all relevant queries completed successfully.


How to get the current field value in Ajax callback?

in your _regions_ajax_callback()

$element = $form_state->getTriggeringElement();
element['#value'] <-- value is in here


It would appear that OWASP think your site is vulnerable to SQL injection. You'll need to find the exact reason yourself (it requires debugging with the site in front of you), but here are some pointers:

Make sure your core version is >=7.32. There was a massive SQL hole in Drupal before that update.
Once that's confirmed, start disabling custom and contrib modules one-by-one, checking the edit form each time. If one of those is to blame, that simple process will find it. If you find a contrib module that's to blame, be sure to open a bug report on Drupal.org.
If your Drupal core version is up to date, and none of the custom/contrib modules are responsible, you'll need to contact OWASP to ask them for their criteria, and how they've arrived at the conclusion that your site is vulnerable.
On the off-chance they respond by pointing out another SQL injection vulnerability in Drupal core (very, very unlikely), be sure to report it to the security team. Same thing for contrib modules (more likely).


Database table cache_views_data is extreme large, what size is normal?

There is no normal size, it depends on your site, but I think that there's some error because this table grows exponentially.

My site was down because the size of this table. In my case, with a few views & something like 1000 users this table was 29 Gigabits. I deleted it and then everything went back to normal.

I suggest you to keep an eye on the tables of your database, specifically this table.


By concept a contrib module will hardly ever be able to use SASS, because SASS simply is not part of Drupals distribution. But that doesn't mean your local environment cannot use shared SASS resources for custom themes and custom modules.

E.g. in all our projects, the project-specific theme is a sub-theme of a shared, immutable base theme providing defaults and mixins. We are compiling with a bash script using standalone SASS with the --load-path argument:

sass ./web/themes/custom/PROJECT/scss/THEME.scss ./web/themes/custom/PROJECT/css/THEME.css --load-path ./web/themes/custom/SHARED_BASETHEME/scss

in ./web/themes/custom/PROJECT/scss/THEME.scss

@import "default_settings"; /* lives in SHARED_BASETHEME, bunch of $variables with !default */
@import "settings"; /* lives in PROJECT, partially overrides default_settings */

I'm quite certain there is something similar for the Node-Version of SASS (or in Gulp). With a black belt in in Bash-Fu (or in your case: Gulp-Fu) this can be extented to any custom module and any custom theme and vice versa.

Example with multiple themes:
We had one project using Domain access module and one sub-theme per sub-domain and we handled bulk theme compiling with a bash script:

for D in ./web/themes/custom/*/;
do
  if [ -d "${D}" ] && [ "${D}" != "./web/themes/custom/SHARED_BASETHEME/" ] && [ "${D}" != "./web/themes/custom/EXCLUDE_ME_2/" ]; then
    echo "Creating sub-theme ${D}"
    sass ${D}scss/THEME.scss ${D}css/THEME.css --style expanded --load-path ./web/themes/custom/SHARED_BASETHEME/scss
  fi
done


How can I select a set of nodes directly linked to a node using views and wikitools

So I found a very simple solution to my problem: I used a contextual filter (in Views) and a Node Reference. Each Article page is linked to corresponding Author page(s) using a node reference. Then using a Contextual Filter in Views, I was able to select all articles written by a given author and display them in the author's page.

I'll give additional details on how to set up the contextual filter, even though it might seem simple to experienced users, new users like me might find the information useful. To set up the contextual filter for the task I described, I selected: 'Provide default value' ('Content ID from URL'), then 'Override title' (and I entered "Articles mentioning %1" in the blank space), 'Specify validation criteria' ('Content', 'Author pages') and 'Node ID' as filter value format.

I don't know whether it can be helpful to someone else but I would have saved a lot of time if I had found that information earlier... :)


What does "Entity API" add to the Drupal API, and why would a module depend on it?

Not complete, but here are some advantages that I know of:

Drupal core only provides an EntityController for loading entities. For save, update and delete, you either need to write it yourself or use Entity API.
You you can expose the base properties of your entities wit hook_entity_property_info(), see privatemsg_entity_property_info() for an example. The advantage of this is that rules.module knows your entity properties and you read and write them with rules. And you also get token integration for free.
It can also automatically provide you with an administrative UI for your entities


Set location country based on coordinates

I believe Location has the ability to be added with a CCK field. The coords can then be converted into a long address. From there you should be able to pull out the country.

If you want to get even fancier you can use OpenLayers to show the location on a map. Does that answer your question?


Get taxonomy name in cycle (performance)

You can use custom query like next:

$result = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name'))
  ->condition('t.tid', $tids, 'IN')
  ->execute()->fetchAllKeyed();

Or you can do join with entity table for single query.