Part 1 - Just to be sure

Add an extra Rules condition like "entity has field", related to that field-tria, before your existing Rule Condition where you do that data comparison.

If that doesn't seem to help, then (temporary) remove the data comparison, to make sure your message is shown for those scenarios as in your Rules Event / Condition (that the entity has that field). If you even don't get the message in this case, then something is really wrong with your rule (eg: you'd be using the wrong Rules Event).

Part 2 - Rules debugging needed

If the above doesn't help, I suggest you start some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?", to get more details about why your rule doesn't seem to work as you'd want it to.

Part 3 - Why your data comparison cannot work

As per your additional comment "this is a multi value field": THAT pretty much explains why your rule seems to behave bizarre ... But sorry, it's rather that you're trying to make Rules do something (compare 2 values), without providing Rules all the info it needs.

If I was to show you 10 glasses of beer (each with their own label say), and I also show you another glass and ask you "is this other one the same?", then the predictable question that would come up is "as compared to which of those 10 glasses?". So that's similar to what's happening in your current rule.

How to move forward

Your Rules Event is pretty sure OK, but you're missing a crucial Rules Action: a Rules Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should add a loop related to that list of dates (which you confirmed to be a multi value field). After you do, you should iterate over each item in that list (= each date). And for each iteration you should then perform the "equivalent of the Rules Condition" you are trying to get to work, whereas you should be using the list item being processed in the current iteration step).

To be honest, I'm afraid that the above will get you closer to the complete solution, but the remaining challenge appears to be "how to specify the date value (a single one) that is to be compared with each of those date-list-items?". Correct me if I'm wrong, but your question is still not clear on that.

PS: this answer (cearly) relates to D7.


To preface, changing the Drupal user edit forms is not the most straightforward thing to do (when compared to changing the templates for regular site's theme), but it is possible, just as anything else.  Firstly, are you currently using one of the stock admin themes (e.g. Seven)?  If so, you will need to sub-theme that, which is done in the same way as you create a normal theme, then you just configure your site to use that admin theme.  Then, you can override templates.  In the case of the user edit form, it will depend the level of customization you want to do to the form. If you turn on debugging (see https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates), then you will be able to see the templates you need to override at the form and field level.  Of course, if you can do what you need to do with CSS or Javascript (and it's not too kludgey), that is something to consider as well to avoid the pain of having to mess with the generation of the actual markup.


A simple solution would be, to give the moderators role the permission to use the users' individual contact forms ( in http://example.com/admin/people/permissions )

The messaging and notifications modules might have more functionality, however, they are still in alpha for drupal 7, so I would use them with great caution.


Modify data structure of a view REST export

In D8 you need to create custom serializer and encoder to alter the XML tags.

Create custom serializer
Ref :  https://gist.github.com/BERRAMOU/dd21e009eec0e3d98733e78360122892
Write custom encoder

-

namespace Drupal\custom_serializer;
use Drupal\serialization\Encoder\XmlEncoder as SerializationXMLEncoder;
use SimpleXMLElement;
 /**
 * Encodes xml API data.
 *
 * @internal
 */
class myXMLEncoder extends SerializationXMLEncoder {

  /**
   * The formats that this Encoder supports.
   *
   * @var string
   */
  protected static $format = ['myxml'];

  /**
   * {@inheritdoc}
   */
  public function getBaseEncoder() {
    $base_encoder = parent::getBaseEncoder();
    $base_encoder->setRootNodeName('jobs');
    return $base_encoder;
  }
}

Then in View under 'FORMAT' you will see both options.
After save, you should get XML with required tag.


How disable view page functionality and revert to pure view with master display?

While creating a view uncheck Create a page checkbox and check create a block checkbox;

If you already have created a View, you can add new display as shown in figure below:


Without knowing your exact use case (I'm assuming you want to just use Views to use the results to build an SVG); it sounds like building a custom Views display style plugin might be in order.

There's a tutorial on Drupal.org (for Drupal 8, but the premise is the same), although I must confess I've only skim read it; and haven't tried implementing it: Building a Views display style plugin for Drupal 8.


Option 1: Hook Form Alter

Rules are event-based conditional actions. For "showing" or "hiding" payments, that event it almost always going to be simply showing the form on checkout. So, technically, you could just use hook_form_alter() and locate the checkout pane that has the payment details and modify from there.

A video where I walk you through how to do hook_form_alter: https://youtu.be/xYMd6WDqxKY?t=1m3s (admittedly, this is for a different use case, but I do show you how to locate the form_id and customize the form_alter for whatever situation you're in).

Option 2: Custom Rules Condition

Another option would be to create a rule condition that you can add to your payment gateways. I think this would be more in spirit with how Drupal Commerce works.

Over here, I have shown you how to create a custom Rules action and condition:
Different vat rate per commerce shipping service

There is also a clear example here:
How do I add a new condition in Rules 2?

How to do option 2

As I said above, this is how Drupal Commerce is supposed to work. If you create a custom rule condition (perhaps there's a business server that returns a REST true/false for an A/B comparison) then that condition is exposed in the user interface and keeps the logic in code where it can be maintained separate from being implemented.

Create the custom rule condition in your custom module with your custom logic
Add that condition to your payment method: /admin/commerce/config/payment-methods
Know that every time that payment method might appear (both in checkout and on the order editing payment screen) that rule condition will be run


Programmatically uploading and validating a user_picture

You can access the values of the image field settings with:
$user->getFieldDefinition('user_picture')->getSettings();

Which will return an array, example:

You then can use file_save_upload
and you can pass to it for second param, an array containing all the validation functions

array $validators: (optional) An associative array of callback
functions used to validate the file. The keys are function names and
the values arrays of callback parameters which will be passed in after
the file entity. The functions should return an array of error
messages; an empty array indicates that the file passed validation.
The callback functions will be called in the order specified in the
array, then the hook hook_file_validate() will be invoked so other
modules can validate the new file.
 source: https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_validate/8.9.x

Here are the validation functions you can use:

Source: https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/8.9.x


The ?itok='xxxxxx' is normal.  This is to prevent possible DDoS attacks.

This problem can be broken down to a couple of things to check.

First, you need to check if the image is actually being created properly.  You can do this by looking in your public files directory under styles/[image style]/public/[path to original] (e.g. does public:/resources/foo.png exist in the directory sites/default/files/styles/medium/public/resources/.  You should see the new image there.

If not, then there is a problem generating the image. Check the status report to verify that a graphics tool exists.  Also check the logs for errors.

Common problems here are that the directory rights are not set correctly and the system can not create the file.

If the image file exists, you may be having a browser cache issue.  Most browsers will latch onto a 404 and not try to reload it.  You will need to force a full page reload (Shift F5 in most browsers) or clear cache / view from an incognito to see the image.  Only on your test browser.  Once it is created, others will not have this problem.

Another possiblity is that your site is using an upstream caching service, e.g. CloudFlare, Varnish, etc.  This service may be caching the initial 404 and not letting people see the image.

If there are still problems, please update with more information, including a URL.


How can I hide node titles only for displayed nodes, and not node edit forms?

You could add a check to see if you are editing the node, like

function mytheme_alpha_preprocess_page(&$vars) {
  if (isset($vars['node']) && $vars['node']->type == 'episode') {
    if(arg(2) != 'edit') {
        $vars['title_hidden'] = TRUE;
    }
  }
}


I do not have sound so not sure if I was following properly, but could it be that you are using a contextual filter rather than a regular filter?


Load domain-specific CSS file on a multisite

It's kinda messy, but you might be able to do something like the following in a custom module:

function mymodule_preprocess_html() {
  $site = $_SERVER['HTTP_HOST'];

  switch ($site) {
    case 'siteurl1':
      //Add your CSS for site 1 here with drupal_add_css
      break;
    case 'siteurl2':
      //Add your CSS for site 2 here with drupal_add_css
      break;
    case 'siteurl3':
      //Add your CSS for site 3 here with drupal_add_css
      break;

  }
}

Or if you specifically want it in your theme files you could do the same in template.php

function mytheme_preprocess_html(&$variables) {
  $site = $_SERVER['HTTP_HOST'];

  switch ($site) {
    case 'siteurl1':
      //Add your CSS for site 1 here with drupal_add_css
      break;
    case 'siteurl2':
      //Add your CSS for site 2 here with drupal_add_css
      break;
    case 'siteurl3':
      //Add your CSS for site 3 here with drupal_add_css
      break;

  }
}

To be honest I think you could use hook_preprocess_page in the module as well.

Many ways to skin a cat and all that jazz.


Links opening in new window have nothing to do with the URL, relative or not, but with the target attribute of the <a> tag.


Why drupal need hidden option in comment settings of content types?

This option has sense only in particular material, if it has comments.

Precisely. So you should use this option when a content type has comments that you don't want to delete, but don't want to allow people to see either permanently or temporarily.

If you don't need that option, you don't need to use it. But its existence makes perfect sense.


How to change string which comes from breadcrumbs?

Your nodes contain apostrophe in their title. Node titles will be passed through check_plain() function and it uses htmlspecialchars() function to convert the quotes to HTML entities.

You may try by decoding them back

function myowntheme_breadcrumb($variables) {
    $sep = ' &gt; ';
  if (count($variables['breadcrumb']) > -1) {
    return htmlspecialchars_decode(implode($sep, $variables['breadcrumb']),ENT_QUOTES);
  }
  else {
    return t("Home");
  }
}


How to create an extra field in the profile module to only accept the numeric values?

Install CCK module. Enable the number module that comes with CCK module. Once you enable the module you can able to add integer field to the Profile Content type if you are using content_profile module to add fields to registration.

See the screenshow below that i just got to do it using CCK, Number, Content Profile module in Drupal 6.


The YAML Form module supports inputmasks which can be configured to handle any desired input format. The submitted value will match your input mask. If you need to submitted value to be converted to a number, you will have to write an update hook to do the conversion.


How to add more Display Suite template suggestions

The problem actually wasn't in ds-1col--search-result.tpl.php. It was when I suggested a custom template for a node when I was doing quick tests, with print $ds_content; in them, the nodes which didn't have the search_result view mode configured, weren't being preprocessed by display suite hence didn't have the $ds_content variable set which was being printed on the custom template. Hence it gave me the impression that it wasn't working.

But to answer the question, there's no special stuff you need to do to suggest a template for display suite. First copy the template from display suite folder to your themes folder. And then all you have to do is use the normal hook_process_node and suggest that template for a certain view mode.


How to show images uploaded only on "read more?"

The 'Read more' button appears on the teaser display.

If you go to /admin/structure/types and select your content type, under the 'Manage display' tab you will see the display types for that content. Select 'teaser' and make the images 'Hidden' on the teaser. Then the images will only display when the full node is viewed.


How to pass cookie value into Drupal View

On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.

Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.


Need an exposed filter field as select box with values like "Last x days" etc

are you checking, value is equal to '-7 days', it must match to the value of select box.

Hope this may help full.


How to link taxonomy term with its content?

In Drupal 7 you can use l()

  $ch = db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
        INNER JOIN taxonomy_term_data td ON th.tid=td.tid
        INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
        WHERE td.vid = '6' AND th.parent = $tid AND book.entity_id = $nid")->FetchField();

  $chap = taxonomy_get_children($ch);
  foreach ($chap as $ca) {
    print l($ca->name, 'taxonomy/term/' . $ca->tid);
  }


Move fields on User edit page between pages

Neither are pretty but, you could customise SimpleNews so that it includes the correct form data on the page you want (instead of creating its own local menu entry), or use hook_form_alter() with a custom submit and validation handler on the user edit form to update the db properly - you should be able to steal the code from simplenews for the validation and submit, that way it will update the db the way it was intended. If you go for the former, new updates to simplenews will be difficult to deal with and if you go with the latter however, be aware that future updates to simplenews may break this functionality if they change table names, etc.


How to track an action when user creates a node of a specific content type?

I would use the Rules module, which allows for dozens of variations of tracking. As an example, here is a prototype of a rule, in Rules export format, to illustrate the possibilities:

{ "rules_find_links_in_body" : {
    "LABEL" : "Find links in body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "OR" : [
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "http(|s):\/\/+",
              "operation" : "regex"
            }
          },
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "ANotAllowedTextStringInBody",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Node body contains an URL ..." } }
    ]
  }
}

Some more details about the above prototype rule:

Rules Event = After saving new content of type "Article" (adapt the type to fit your needs).
Rules Conditions:

Check if the current user is an authenticated user.
Perform a text comparison, using a Regular Expression as the Comparison operation (which you can perfectly do in Rules, without using the PHP filter for it). For the actual regular expression, this rule uses http(|s)://+, which will discover strings that start with either http:// or https://. Should you have additional / similar requirements to discover variations of this (say some other string like ANotAllowedTextStringInBody), another Rules Condition (with an OR) will take care of that also.

Rules Action = Show a message on the site (adapt the message to fit your needs), and/or add other relevant Rules Actions ... Such as:

use the Message module as illustrated in the answer to "How to log and display all the users that have edited a node (without revisioning)?".
send an eMail, either to a specific user, or all users of a specific role.
use the Flag module to flag the user (for whatever reason).
grant a special role to the user.
... (the possibilities are only limited by your own imagination).

Voilà, easy as that ...


"managed_file" form field type returns null value in my form submission

After alot of digging/debugging i discovered that i could not pull any data from the "manage_file" field while using the PrivateTempStore in my Multi-Step form. After disabling the form cache, i began to get the values and the expected behavior by using:

$form_state->disableCache();

My Submit Handler

public function buildForm(array $form, FormStateInterface $form_state) {
 /**
 *  Fixes image upload bug in form. Does not work unless we
 disable the cache while using PrivateTempStore
 **/

 $form_state->disableCache();

.......

}

See https://www.drupal.org/project/drupal/issues/2647812#comment-11683961


What function or $user variable do I edit to manually increase a user's session timeout?

There are several modules that can do this for you.

https://www.drupal.org/project/session_cookie_lifetime
https://www.drupal.org/project/remember_me
https://www.drupal.org/project/persistent_login

I've had some problems with remember me and am still testing the others, but they give you more control over the session lenght.

By default drupals session expire after about 3 weeks, according to

ini_set('session.cookie_lifetime',  2000000);

You should be able to override this variable at database level as well, if you want to.


How to use hook_menu to add an item to the secondary links?

You can use menu_name to specify the menu of the items you are adding:

See the hook_menu docs for more info.

For example, to add the item to the main menu:

function hook_menu()
{
    $items = array();
    $items['bla'] = array(
        'title' => 'bla',
        'page callback' => 'mymod_blah',
        'expanded' => TRUE,
        'menu_name' => 'main-menu',
    );
    return $items;
}


Commerce Fees creates a line item of a particular type. You can loop through each of the line items on an order and remove the line item that has a particular type by looking at it's type value. I believe you can remove it by setting the quantity of the line item to 0.


I need a way to automatically make Panel layouts responsive

I think the closest you're going to get to out of the box is Panels Extra layouts, which ships with a bunch of adaptive layouts.

Other than that, your best bet is just to create a bunch of custom layouts by yourself, with their respective templates. The documentation is not bad for that; you can find it here: Panels 3: Creating a custom layout in your theme. Alternatively, just look in the Panels codebase for their implementations.


Views, Taxonomy, multiple parameters using contextual filters

To do like this too much contextual filters needed, i think it's better to manage the URL in template.php and/or with hook_menu and use views_embed_view() to pass arguments to Views

$arg =array (1,2,3);
print views_embed_view('view_name', 'page_1', implode('+',$arg)); // OR
print views_embed_view('view_name', 'page_1', implode(',',$arg)); //AND


Search keys get variable is in subsequent search pages and so search not returning any more results

You don't need to POST to /search/node as all its parameters are retrieve from query parameters. As such, you can make your basic form use the GET method with your keys input field. For example:

<form action="/search/node" method="get">
  <input title="Enter the terms you wish to search for." name="keys" value="" size="15" maxlength="128">
  <input type="submit"value="Search">
</form>

As for the "Your search returned no results" on loading /search/node, that's the default behavior.


Adding a specific field of a content type in the display of another content type

With entity reference there are a couple ways to go about this.

You can select the view mode to display (i.e 'teaser') on the display ui of the other content type and then on the 'Fruits' field display ui for the view mode teaser show only the picture. If you use the title module, you'll be able to hide the title on the teaser. If you don't want to use the title module there are other approaches to hide the title.
You can create a view using entity views attach and set up a relationship and then display only those fields. This is more complicated and not as maintainable, I recommend going with #1.

Hope that helps


How do I use hook_views_pre_render in template.php in Drupal 7?

The hook is run for every view, therefore you need to inspect the $view object (the parameter passed to the function).

Place the function in your theme's template.php.

Name it YOURTHEMENAME_views_pre_render (ie  replace 'hook' with your theme name). Then use $view object to target specific view name and display_id, as in $view->name and $view->display_id (from memory, I might be wrong, but you get the gist).

function MYTHEME_views_pre_render(&$view){
  if ($view->name == 'VIEWNAME' && $view->display_id == 'DISPLAY_ID') {
    // do what you want
  }
}

If you want to do this for many views, best do it like this to separate the views into their own functions:

function MYTHEME_views_pre_render(&$view){ {
  // will run for all views
  $function = __FUNCTION__ . '_' . $view->name;
  if (function_exists($function)) {
    $function($view);
  }
}

function MYTHEME_views_pre_render_VIEWNAME(&$view){
  // will only run for specific view, but for all of its displays.
}


How to output a screen from a submit handler? (D7)

You want output form values after form on submit?

function mymodule_myform($form, $form_state) {
  $form['mytextfield'] = array(
    '#type' => 'textfield',
    '#title' => 'My Textfield',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  if (isset($form_state['values'])) {
    $form['page_output'] = array('#markup' => 'Submitted value: ' . $form_state['values']['mytextfield']);
  }
  return $form;
}

function mymodule_myform_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}


I ended up creating a regular view, not a slideshow. Then I used a variation on the code above to reshape the images. And I used CSS on the mini pager to turn it into the buttons that one would find in a typical slideshow. It turned out exactly how I wanted it. Although it took a lot of time and aggravation, I learned a bit more about about Drupal, JavaScript, and CSS. Plus, I can reuse the code again.

If anyone is interested, my final JavaScript code is below; there were a few minor problems with the code above that caused it to act wonky in certain resizing situations.

    function myFunction() {
      var x = document.getElementsByClassName("slide");

      for (i = 0; i < x.length; i++) {
        var viewHeight = window.innerHeight;
        var viewWidth = window.innerWidth;
        var viewAspect = viewWidth / viewHeight;

        var imageHeight = x[i].height;
        var imageWidth = x[i].width;
        var imageAspect = imageWidth / imageHeight;

        if (imageAspect < viewAspect) {
          x[i].style.height = viewHeight + "px";
          x[i].style.width = "auto";
          x[i].style.marginTop = - viewHeight/ 2 + "px";
          x[i].style.marginLeft = - x[i].width / 2 + "px";
        }
        else {
          x[i].style.width = viewWidth + "px";
          x[i].style.height = "auto";
          x[i].style.marginTop = - x[i].height / 2 + "px";
          x[i].style.marginLeft = - viewWidth / 2 + "px";
        }
      }
    }

    window.onload = function() {
      myFunction();
    };

    window.onresize = function() {
        myFunction();
    };


Is it possible to protect content types with captcha?

you may create custom module
https://stackoverflow.com/questions/3434134/restrict-node-with-captcha

combine hook_node_view_alter with
http://drupalcontrib.org/api/drupal/contributions!captcha!captcha_api.txt/7


How do I programmaticaly get the name/ID of the shipping method for an order?

I found a good answer at https://drupalcommerce.org/discussions/8274/get-shipment-services-object-flat-rate-order-object

// Be sure there are line_items
if (!empty($order->commerce_line_items["und"])){
  $line_items = array();
  // Gather together the IDs of the line items
  foreach($order->commerce_line_items["und"] AS $line_item){
    $line_items[] = $line_item["line_item_id"];
  }
  // load_multiple allows us to use $conditions so we only load the entity of type "shipping"
  $shipping_line_item = commerce_line_item_load_multiple($line_items, array('type' => "shipping"), FALSE);
}


When creating a module, where do I set cookies?

Here i set the cookie as user login and logged out.

/**
 * Implements hook_user_login().
 */
function HOOK_user_login(&$edit, $account) {
  setcookie('user-logged-in', '2', 0, '/');
}

/**
 * Implements hook_user_logout().
 */
function HOOK_user_logout($account) {
  // Set cookie in the past and then remove it.
  setcookie('user-logged-in', '', REQUEST_TIME - 3600, '/');
  unset($_COOKIE['user-logged-in']);
}

You can try it will able to create new cookie anywhere i.e Create cookie into  hook_init()
https://www.drupal.org/forum/support/theme-development/2009-05-26/setting-custom-cookies#comment-2901778


The Tab Tamer module will do it for you without having to write a single line of code:

  Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.


How to change payment state programmatically?

Try this:

use Drupal\commerce_payment\Entity\Payment;

$payments = \Drupal::entityQuery('commerce_payment')
  ->condition('order_id', $order->id())
  ->execute();

foreach ($payments as $value) {
  $payment = Payment::load($value);
  $payment->setState('completed')->save();
}


Authorize.net - Multi-currency - disabling currency code when sending money

Are you sure the issue is that the currency code value is included or is it simply wrong? i.e. are you submitting a USD currency code to a CDN account? Note that in the 1.0 released earlier this month we fixed a couple of issues pertaining to multi-currency usage. Does updating to this version allow transactions to process as expected?


I vaguely recall having that same error message, and running update.php solved it. So make sure you've installed the latest version and run update.php.

To get Browscap to log non-crawler user agents, head to /admin/reports/browscap/browsers and follow the instructions. They tell you to enable 'Monitor browsers' on the Browscap configuration screen.

To participate in the issue queue of Browscap, or any Drupal project, go to the project page and look on the right side. You'll see a list of maintainers, and under that a section called Issues for Browscap. Search for your issue there. Or just go to the project's issue list.


What kind of ajax exactly? I guess it returns JSON?

Drupal's standard ajax API currently always does POST requests, those are not cached. So make sure you are doing a GET request.

Render caching is also only available for render arrays/HTML.

Your response would be cached if you return an object that returns CacheableResponseInterface but only by the (anoymous) internal page cache.

To have caching for all users, you likely need to implement your own logic  to cache the response object as you suggested. By default, the node_list cache tag can be used to have it invalidated automatically whenever any node is created or saved. You can define your own cache tag (any string works) that you invalidate yourself only when certain conditions are true (for example, a new node of a specific type, matching your entity query).


How to get images into a slideshow via json javascript with new itok

Your root problem seems to be that you are using a side effect of image_style_url().

When you don't pass in a valid image path, you used to get back the basepath of the image style.  Now, with the token patch, it will include the token, and therefore not really be the basepath.  From what I can gather, this is why a lot of modules broke.

The proper thing to do is to use the API to create the URL for you on the server side, instead of gluing together parts in JS.

This is something that I used on a recent project:

$images = array();
$styles = image_styles();

if (! empty($node->field_my_image[$node->language])) {
  foreach ($node->field_my_image[$node->language] as $image) {
    $fid = (int) $image['fid'];
    $uri = $image['uri'];
    $url = file_create_url($uri);

    $metadata = array(
      'alt' => empty($image['alt']) ? '' : $image['alt'],
      'width' => (int) $image['width'],
      'height' => (int) $image['height'],
    );

    $metadata['styles'] = array(
      'original' => $url,
    );

    foreach ($styles as $style => $unused) {
      $metadata['styles'][$style] = file_create_url(image_style_url($style, $uri));
    }
  }

  $images[$fid] = $metadata;
}

drupal_add_js(array('mymodule' => array('images' => $images)), 'setting');

This dumps all of my image fields into a JS array with all of their metadata, including all of the URLs for the image styles that I may need.  My JS code can then use what it needs from this array without worrying about building paths up.


Facebook Style 'Read More' instead of standard Pager in QuickTabs?

You can use Views Infinite Scroll.

  Views Infinite Scroll provides a pluggable pager that enables Views infinite scrolling by using jquery.autopager plugin. Using this module with Views page display will load another page whenever the user reaches the bottom of the page.


A possible alternative to achieve what you're trying to do, is to use a combination of these (commonly used) modules: Rules, Views and VBO.

With these modules in place, you could implement (for each of the fields that your question is related to) a variation of the solution described in my answer to "How to bulk update select list fields?", i.e.:

Create a Rules Component with a Rules Condition to checks if the field contains the string you're interested in (probably using a "text comparison" with a "regular expression" to find all variations).
Create a VBO enabled view of all nodes to be checked, whereas you'll use the Rules Component as your custom VBO action.

Repeat the above for each field (simply by adapting your Rules Component for each of these fields).

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

Done ...


I suggest you to check these 2 posts:

http://www.4sitestudios.com/blog/sep-13-2013/when-use-content-types-taxonomies-and-custom-entities-drupal

https://drupal.org/node/2075921


How to validate node title field Drupal 7

You can setup field/property validations with the module Field validation.

Here's the documentation on how to add validation to properties (with the Field validation module), as the title isn't a field in Drupal 7.


All your panels have a common class. Probably .panels. You need to see if your left panels also have a common class, probably .panel-left or something. You can use your browsers element-inspector to see this. It will show you something like this (simplified example) if you select your node that has panels:

    content

This gives you a clue where to set your background in CSS.

.panels .panel-left {
  background:url('path/image');
}

You need to find classes that the elements you want to style have in common, but are unique enough so that you style only those.


What about this approach (these are just my thoughts)? So, create a rout which gets request and builds $form_state and calls drupal_form_submit function, actual form looks something like this:

function myForm($form, &$form_state)
{
  ....
  $form['submit'] = array(
    '#type' => 'submit',
    '#submit' => array(),
    '#validate' => array('myFormValidation')
  );
  ....
}

function myFormValidation($form, &$form_state)
{
  $error = false;
  if (SOME_CONDITION) {
    $error = true;
  }

  ...

  if (!$error) {
   drupal_json_output(array('ok'));
   exit;
  }
  else {
   drupal_json_output(array('error'));
   exit;
  }
}

EDIT:

I don't have an expirience with Drupal's Services module or its RESTFul services, but I usually develope my REST projects (usually backend system for IOS apps) in symfony, I think I understand how all this stuff work:), So when I wrote about a rout I meant that this will be some menu item (with hook_menu):

$items['check-my-external-post-data'] = array(
  'page callback' => 'some_callback',
  ...
);
...

function some_callback()
{
  ...
  // $values - from $_POST request
  $form_state = array();
  foreach ($values as $key => $value) {
    $form_state['values'][$key] = $value;
  }
  ...
  drupal_form_submit('myForm', $form_state);
}

I've never tested this kind of things, but it should work (there are too many tutorials about REST APIs, request handling, and so on.. which can help OP if something goes wrong)


How to get the custom class added to a view

If you only need to get this information, you can use template_preprocess_views_view

/**
 * Preprocess the primary theme implementation for a view.
 */
function YOURTHEME_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {
    case 'your_view_name' :
      // print out the array with all options to see what you're dealing with
      drupal_set_message('<pre>' . print_r($view->display['display_name']->display_options, true) . '</pre>');
      break;
  }
}

But if you will need to override this custom class, you'll need to use hook_views_pre_render()

function YOURTHEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'name_of_your_view' :

      // override the view settings
      // for example: $view->field['fieldname']->options['label'] = 'Some label';

      break;
  }
}


How to set a rule that assigns a user to a specific Organic Group after the checkout process

For reference, this type of use case (selling access to an organic group) would be best handled now using the Commerce License framework, that has been designed specifically for this type of use cases.

We don't have integration with Organic Groups yet, but it seems straightforward to do in the framework.


Static image management module for Drupal 7

If you're just using static images as part of of your theme, you are indeed correct in your suggestion that using an image field is overkill. I'd even go so far as to say it's entirely incorrect to use image fields for static theme content: fields aren't very portable and add way too much overhead to something that'll likely be a part of every page on the site.

Instead, handling static images is built directly into Drupal's core API and theming layer (so, no need for a separate module). What you'll to do is reference the images in your theme using preprocess functions and the Drupal API.

Let's assume you have a logo (logo.png) in the images/ directory of your theme, and you want to display that logo on every page. In the page.tpl.php template file of your theme, you could do something like this:

But that's pretty brittle: what if the theme moves to another directory? What you want to do instead is create a variable such that you could do something like this:

<?php print $logo; ?>

To do that, you create a preprocess function to create a variable for use in your templates. In your theme's template.php file, create the following function (if it doesn't already exist):

// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
}

Then, get the path to the logo using drupal_get_path():

// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
  $theme_path = drupal_get_path('theme', 'MYTHEME');

  $logo_path = $theme_path . '/images/logo.png';
}

Finally, render the path to the logo as an image using theme_image():

// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
  $theme_path = drupal_get_path('theme', 'MYTHEME');

  $logo_path = $theme_path . '/images/logo.png';

  // Prepare the information needed to theme an image
  // @see theme_image()
  $image = array(
    'path' => $logo_path,
    'alt' => t('My Site'), // t() makes a string translatable
    'attributes' => array(
      'class' => array('logo', 'nav-home'),
    ),
  );
  $variables['logo'] = theme('image', $image);
}

Now, $logo is available for use anywhere in your theme's page.tpl.php. Do the same process (get the path to the image, then assign the themed image to a variable) for any other static images you want to use as part of your theme.


Is it possible for the Contact page to have 2 URL aliases? or clone it?

The Redirect module would allow you to create another url for for your contact page. One would simply redirect to the other.


Create custom endpoints by extending the Resource Base class

The serialization class is the input or output of normalization and denormalization, or in other words, the object that you get when you denormalize data or the object that you normalize on the way out. Drupal 8 core provides one example of this \Drupal\rest\Plugin\rest\EntityResource. If the object is an entity you can use core:

  serialization_class = "Drupal\Core\Entity\Entity",

In order to use your arbitrary non-entity, you would also probably need to implement a Normalizer, but that is possible as well.

If your goal is to create a non-REST API with a custom endpoint that does not correspond to a REST operation (such as login or getProperty), then you should look at the Services module.


Removing user points using rules module?

Just make the value of the "Points" field a negative number.

Let's say you want to remove 100 points when the flag event occurs.

Make the value for Points equal to -100.

Hope that helps.


How to update drupal by drush automatically

Updating Drupal Core to the latest version e.g. currently Drupal 8

drush up drupal -y

Updating a specific Drupal Core Version.

drush up drupal-7 -y


You're saying you want images from another site? I've got two pretty basic suggestions...

build them into your theme. You'll want to create a div (or three) in a template for the front page, adn then you can add them in with css pretty easily.
display them with a block. Create a new block, make sure you turn on HTML for your input and then add your images:

Enable the block for the region you want, and tell the block to only display on the front page. You'll want to do some simple css theming to that block, as well, to make them look how you want.

Both these options are just to display images. What do you want to do after that? Will clicking them take the user to another page?


How to replace flag text with custom icon?

This code is needed in your template.php and a font-icon lybrary added like this one: http://fontawesome.io/icons/ There is a module for that to


Working with views, better use various displays or create more views?

In the book "Mastering Drupal 8 Views" Greg Marshall suggests that there is no strong reason to prefer one or the other. He suggests using separate views most of the time, for the simple reason that it's very easy to make a mistake in the UI and apply a change to all displays when that wasn't what you wanted.

I would suggest that you think carefully about in what circumstances you are going to want to modify a view. If changes are likely to affect all displays, or be only applicable to one display of a certain type, then having a single view is fine.

If changes would likely be to multiple characteristics that could apply to all displays but you would want to be different on each display, then isolating them as separate views reduces the risk of getting in a mess.


How to re-generate Node Object from database stored Serialized Node Data .. and then Save as New Node?

Now how can i transform these data back into Drupal $node Object please?

As said you can use the following code,

$node = unserialize($data);

  Then how can i node_save($node) (as new node) upon them? (What tricks will i need?)

You can null the nid, vid and use node_save to save it as a new node like this:

$node->nid = NULL;
$node->vid = NULL;
node_save($node);


If your using multiple web servers then ETags need to be configured correctly. Add this to your .htaccess file (at the bottom) if this is the case. If you only have 1 server then you can safely ignore this recommendation.

FileETag MTime Size

Cookie-free domains offer a slight performance improvement because less data will be traveling over the wire. You need a CDN to get a cookie-free domain setup correctly.


Can I use Drupal 7's CSS/JS cache buster/token programmatically?

You certainly can, it's just a variable:

$current_token = variable_get('css_js_query_string', '0');


Hide and Reveal Sidebar Blocks in Drupal 7?

In the themes .info file you can add a line like this

"scripts[] = myscript.js". This is eplained in the drupal theming guide -> http://drupal.org/node/171205.

Drupal will then load your js file and automatically insert jquery too.

This is the code that you need to put in the js file. Be aware that every region has a div with the class name. Example "region-footer". So thats how you can target them easilly. Make sure you set a width in you css file for the element.otherwise jquery cannot toggle the width.

(function($) {
    $(document).ready(function() {
        $('.region-footer .block h2').click(function() {
            $(this).parent().children('.block-inner').animate({
                width: 'toggle'
            },5000, 'swing');
        });
    });
})(jQuery);

You could also animate/toggle the margin instead of the width. If you do that remember to declare the negative margin for the element in your css file.

Do not forget to clear the cache after altering your themes .info file.

Tip : You could add a nice animation with http://gsgd.co.uk/sandbox/jquery/easing/


Ubercart file downloads - group user's file downloads by product

I solved this issue with a combination of:

Advanced profile
Views
Node access

I used the Node Access module to create products that were nodes. Only users that had purchased a particular node could see it.

I used Views to create a view that displayed all nodes of the relevant type, including the files attached to them, in a table. The view will only display items that the user viewing it has permissions to see (i.e. those that they have purchased).

I used Advanced Profile to create a new profile page that displayed the view outlined above.


How to access to the user info on the search page?

Did you try implementing hook_preprocess_search_results (notice the plural search results)?

I haven't tested recently and I'm on a mobile right now. But I'm pretty sure that hook somehow had node objects (should be user objects in your case). Collect the UIDs, run a user_load_multiple and then add the user objects to each result for profit in hook_preprocess_search_results.

Update

I'm no longer on my mobile, so I could actually test this. It turns out that the user module does not feed the results set with the user account. I don't think Drupal 7 will receive these features anymore, so you'd have to patch the core user.module to achieve that.

Here is a patch if you are interested in going down that path: https://gist.github.com/Ayesh/b1892942b053dc746fb5


Here a solution for hide the alt and title fields:

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
    // If this is an image field type
    if ('image' === $context['field']['type'] && 'MY_FIELD' === $context['instance']['bundle']) {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
        // Add the new process function to the element
        $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
    }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
    $element['title']['#access'] = FALSE;
    $element['alt']['#access'] = FALSE;

    // Return the altered element
    return $element;
}

Et voila :)


Duplicates when creating view with entity reference

You can give a try to Views Distinct module.

Also, if there the results the logically different you can think of showing them in way that they look more of information rather than repeated results
For example if you group by conference, you can show aggregated speakers for a given conferenece


PHP code to display block based on list (text) field

With the following script you can check the value and return true. I've added my comments before each line.

// First check if the current page is a node
if ($node = menu_get_object()) {
 // Then, check if it is your content type
 if ($node->type == 'your_content_type') {
   // Get the value of your field
   $display_block = field_get_items('node', $node, 'field_display_block');
   // If the field's value is equal to 1, then return true
   if ($display_block[0]['value'] == '1') {
     return TRUE;
   }
  }
}


How to hide a field (cck) based on a date field?

The solution is very simple. In template.php file implement MY_THEME_preprocess_node(). Example:

function MY_THEME_preprocess_node(&$variables) {
  //  dpm($variables);
  if($variables['type'] == 'MY_CONTENT_TYPE') {
    $date_field_value = $variables['content']['field_DATE_FIEL_NAME'][0]['value']; // find the correct value of your field

    $converted_date = strtotime($date_field_value);

    if(time() > $converted_date) {
      hide($variables['content']['field_DATE_FIEL_NAME']);
    }
  }
}

you can also use hook_node_view:

function MY_MODULE_node_view($node, $view_mode, $langcode) {
  if($node->type == 'MY_CONTENT_TYPE') {
    $date_field_value = $node->content['field_DATE_FIEL_NAME'][0]['value'];

    $converted_date = strtotime($date_field_value);

    if(time() > $converted_date) {
      hide($node->content['field_DATE_FIEL_NAME']);
    }
  }
}


The method that you missed is $form_state->setResponse(). In combination with a TrustedRedirectResponse object, which exists for security reasons (to prevent users from accidentally being redirected to another site), you can use code similar to the following.

$response = new TrustedRedirectResponse('https://facebook.com');
$form_state->setResponse($response);


User permissions on a costum content type

You can use Field Permissions for this

Features

Enable field permissions on any entity, not just nodes.
Role-based field permissions allowing different viewing patterned based on what access the user has.
Author-level permissions allow viewing and editing of fields based on who the entity owner is.
Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
Field permissions overview


Show the view result only when users enter a value for the exposed fields

For each of your fields, in your view, you have the option Hide if empty. Select it to not display anything for the field if it is empty. Note that the field label may still be displayed. Check style or row style settings to hide labels for empty fields.


How to alter 'not null' value of field after creation

You need to ud db_change_field function to change structure of table field.

function MYOTHERMODULE_update_70xx() {
  db_change_field('tablename', 'payments', 'payments', array(
    'not null' => TRUE,
  ));
}


Disable all modules, including all core modules, that are not absolutely necessary for the failing functionality (uploading images). If the minimal configuration is working, enable each module one-by-one and test until the error occurs again, then you got the culprit.

In particular, disable Database logging.

If the basic install still causes the problem, start reading the server logs (it wouldn't hurt to check them immediately, but they might be empty), and check the server configuration.


Is it possible to hardcode views as part of the custom module to avoid `config/sync`?

Yes that's right the config export will recreate them for its config sync handling. The /module/config/install is exactly that, just for install time. The config syncing would become a big mess of overlaps if every module could define different elements to handle syncing themselves. Is it such a problem that config sync has them? As that can be your master of that the view should contain. So think of it as: The module sets up the default upon install and Drupal's config sync will make a copy so that's now the master and won't get removed unless you remove it through the UI and then do a config export.

If people are paying attention it should hopefully be unlikely someone would delete a view from the UI, do a config export and do an import on live without realising they've messed up. But just in case have you thought about adding your config sync directory into GIT? So that if someone does say delete a view through the UI and do an export you'd be able to revert


What is the proper file structure of a module that only contains sub-modules?

For what i've seen, putting sub modules in a modules folder like your first example is most common best practice.


How do you remove product from shopping cart?

If that button is missing for some reason on just a specific product type, then it's more than likely the result of custom form altering in a module file on your site. I'm not aware of any Views configuration that could remove that button just for products of a certain type. Just in case, you can check your shopping cart form View's configuration for the line item delete button to see if any advanced settings are somehow hiding it conditionally.

My hunch is on custom code, though.


Filter users in views with a mandatory role and another role that is optional

You can put condition in View's criteria.

Go to your view and step ahead to filter.
Put first filter as. For example you have role as category A and category B.

Add following filters which can be helpful as per your scenario.

   Select content:role (condition : is one of A and B)
                    OR
   Select content:role (condition : is one of A)
                    AND
   Select content:role (condition : is none of B)

Don't forget to add OR and AND condition in between filter fileds.

Hope this will be helpful.


How to display JSON returned (from external REST API) in a Block? [my code attempt inside]

$block['content'] should be an array, like in the example for hook_block_view:

$block['content'] = array(
    '#theme' => 'feed_icon',
    '#url' => 'rss.xml',
    '#title' => t('Syndicate'),
  );

For more examples, see Examples for Developers project, block_example module.

If you are putting array there, it must be a renderable array. If it's not, then either:

Implode it into string. With nested arrays, it can get a bit complicated.
Put it as an element in $block['content'] array, and set $block['content']['#theme'] element to something that can theme it. More complicated, but also more versatile and cleaner solution.


I'd recommend using hook_form_alter and user_has_role in a custom module. It allows you to alter the form programmatically and perform logic in your hook function so you can access your user's role and modify your fields that way. For example, you could do something like:

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='your_form') {
     global $user;
     if (user_has_role(your_rid)){
       // add the extra field you need here
     }
  }
}

there are many examples on how to modify/add fields in the hook docs link above, plus you can google more tutorials on that.


You need to use imagecache actions module to auto convert images from one extension to other.

Module Project page tells it provides

  File Format switcher - If you need tranparency in JPGs : make them
  PNG. If your PNG thumbnails are 30K each, save them as JPGs. (This is
  distributed as part of the color-actions submodule)


Grouped exposed filters just don't work on tags

Delete all your existing filters. I think you have misunderstood how they work.

Then add a single filter on the term reference field (field_tags?), expose to visitors, reduce duplicates, and make sure the filter is NOT required. Do not check anything else!

Submit, save your view, and you should have an exposed filter with the options '-Any-', 'Phpto' and 'Video'.

EDIT:

After much discussion, step by step:

Go to /admin/structure/taxonomy and set up a vocabulary calling it whatever you wish (lets say 'media'). Then add terms to the vocabulary like 'Photo', 'Video' etc. If you have already done this, skip to step 2.
In your content type, go to 'Manage fields' and add a term reference field to the type (lets call it 'Media') using the media vocabulary.
Go to /admin/modules and disable Better Exposed Filters.
Edit your view and delete all the current filters in the view. Save the view.
Now add a filter on the taxonomy reference field (eg field_media). Click Add and configure fiter, on the first modal select 'Dropdown' and click 'Apply and Continue'.
On the next modal, check 'Expose this filter to visitors, to allow them to change it'. The 'Filter type' should be 'Single filter'. Make sure 'Required' is not checked. Leave the operator as 'Is one of'. The only other box you should select is 'Reduce duplicates. Now click 'Apply' and save your view.

You will now see a dropdown list with all the terms in the vocabulary you created, plus the option -Any- at the top.


You should be able to use the core contact form for this.

Basic documentation about setting it up can be found in the user contributed documentation on Drupal.org.

The contact form let you have a site contact form (sent to the default user), and a contact form tied to each individual user. When you enable the latter option, a tab "Contact" will appear when someone visit's that user's page (provided they're permitted to see it).

Individual users may disable other's access to their contact form, but the administrator may override this.

The core contact form can be configured through options and permissions.  It is very flexible, but it may take some tuning to get the exact behavior you want.


Commerce Kickstart: facets are disabled when using back button

This is an issue with how FireFox serves cached pages when you use the Back button.

There appears to be two ways of solving this:

1) Per the first answer here, set autocomplete="off" for all form elements that can be disabled. As that form likely isn't one you have direct control over (without hacking a module), you'll have to do this with a hook_form_alter().

2) The second answer in the question linked above provides some JavaScript that you can use to stop this from happening:

window.addEventListener('pageshow', PageShowHandler, false);
window.addEventListener('unload', UnloadHandler, false);

function PageShowHandler() {
    window.addEventListener('unload', UnloadHandler, false);
}

function UnloadHandler() {
    //enable button here
    window.removeEventListener('unload', UnloadHandler, false);
}


Why are some place holders '@' and others '%'?

Have a look into the function definition of the format_string()
 function which is used by the t() function:

Each type of placeholder has a way in which this function intrepretes it:

@variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.
%variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.
!variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).


Commerce: Extra information per quantity bought

Not a simple answer here, you've got a lot of ways to do this, but if you're focusing in the ticket/registration case, you could take a look to Commerce Registration, that will provide the closest feature I know for that matter.

It is based in Entity Registration, so you've got there a starting point.


Issue with grouping in a view using Views PHP

Consider using a Computed Field on the Session content type to combine

the icon  (conditionally)
the session number
the session title

Then you can use that field for the secondary sort, and leave the Global PHP out of the View. Be sure to store the computed field in the database so that Views can access it.


hook_commerce_shipping_service_info() rate callback: What does the 'data' array do?

Prices in commerce have a data array to establish the original components and component modifiers that these might have. For example, discounts and taxes add components to alter a price after taxes.

I'd say you can use 'data' array as storage of context information like the line items do (they store the product display where the product has been added to the cart) and the price system stores the components there, so it's needed to add elements to it.

Check commerce_price_component_add and commerce_tax_rate_calculate for examples on where this is used.


How to delete all nodes referencing a given one?

I think a "quick and dirty" module would be the more elegant way. I did something similar recently in drupal 6 with ubercart. I have a content type that sometimes needs to be associated with a product and sometimes doesn't. When one of the custom nodes is deleted, if it has a product associated with it, that needs to be removed as well:

your_module_nodeapi(&$node, $op) {
  if($op == 'delete') {
    $product_nid = db_result(db_query('SELECT nid FROM {content_type_product} WHERE field_product_list = %d', $node->nid));
    if(!empty($product_nid)) {
      node_delete($product_nid);
    }
  }
}

In this case, field_product_list was a node reference field added to the product. I'm sure something similar would work in your case.


Allowing users to choose between two sort options in a view

You can do that with Better Exposed Filters. I've combined two sorts together that way before, one selected with Ajax refreshing sort, then having the secondary sort tied in with the same. I would checkout the handbook links on that page for more direction, they have some pretty extensive recipes there that you could use as a base to start from.

handbook page for further reference


How i could save a block that i had called it before with block_load?

After reading the code in the block.module file I can suggest the following:

Leave your code in hook_block_info_alter unchanged.
From your hook_enable hook call the following function to force calling and saving your hook_block_info_alter code:

_block_rehash();

Quoting from the function's documentation:

  Updates the 'block' DB table with the blocks currently exported by
  modules.

Hope this does it for you!


What I am seeing here is an entity with a bunch of other entity reference fields.
This followed by a bunch of access permission settings.

  some users can be assigned as the admin of a group that can add users to that group

Create a "group" entity that has 2 entity references fields (multivalue) one for users and one for admins. Each referencing the users and the admins who can have privileges.

  make sub groups and assign admins to it to add users...

Add another entity reference field to reference the same group entity type as the parent

  all the users need to have permissions to add edit and view some info that will be part of a large module I am creating...but unique to each user/subuser.

You would just need to play around the access control for that particular entity using a module like https://drupal.org/project/content_access or other ACL modules


Migrate module problem with migrating images - D7

I think my source_dir path was incorrect. I used the following and it worked:

// Image migration
// basic mapping of destination field and source field
$this->addFieldMapping('field_figurae_image', 'highresfile');
// Directory where source images are located
$this->addFieldMapping('field_figurae_image:source_dir')
     ->defaultValue(drupal_get_path('module', 'matrixmigrate') . '/matrix_library');

The major difference here is that I used my sub-module instead of the migrate module itself to grab the path. I also played with permissions in various directories. I think one of those two things did it. I also dropped the destination directory since it defaults to your Drupal file directory.


I suggest you the installation of Localization update module.

From the module's page:

  Automatically downloads and updates your translations by fetching them
  from localize.drupal.org or any other Localization server.

I use this module in all my projects, you can also have the .po files in the local server.


(Good or bad?) Calling a Function in Template File which returns a theme() Function value

If you are asking about calling theme() from inside a template file, that is possible, but it is rarely done: Out of 214 calls to theme() done from Drupal (and the Views module) only two calls are done from inside s template file.

This is the code used in the default implementation of page.tpl.php; similar code is present in the implementation of page.tpl.php for the Bartik theme.

<?php if ($main_menu || $secondary_menu): ?>

    <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Main menu'))); ?>
    <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?>

<?php endif; ?>

What you should do is initializing a variable in the preprocess function for the template file, and use that variable in the template file.

Truly, you should not put logic code in your template file; this means that, for example, code similar to the following one should not be used in a template file.

<?php if ($condition1): ?>
  <?php print theme('theme_1', $values1); ?>
<?php elseif ($condition2): ?>
  <?php print theme('theme_2', $values2); ?>
<?php elseif ($condition3): ?>
  <?php print theme('theme_3', $values3); ?>
<?php endif; ?>

If the code is similar to the following one, then it would be more acceptable, but I would still think of possible future versions of the code, and prefer using a variable in the preprocess function.

  <?php print theme('theme_1', $values1); ?>
  <?php print theme('theme_2', $values2); ?>
  <?php print theme('theme_3', $values3); ?>


Display a promo image at last in every slideshow created for a node

Create a Promo article and add the promo image as the field in this article.

Note the this article will be just a placeholder for us and will not be presented anywhere. So may you could un-publish as well.

Do a dpm to find out the fid or any related that you need to know about this particular image field. Then make changes to the view in post_execute.

   function modulename_views_post_execute(&$view) {
      // wait for the right view
      if($view->name == "name_of_the_view") {
        // create the object you want to insert in the result
        // dpm($view->result); to check how the objects are built.
        $temp = new stdClass;
        $promo_image->fid = 13;

        // replace the old result array
        $view->result[] = $promo_image;
      }
    }

Based on the answer : Insert row into a view


You don't need the Indexes on your web server. Its actually not recommend on a live environment. For testing purpose it can be useful sometimes.

If you don't have your files directory I would recommend you to created a files directory

sudo mkdir sites/default/files # Creating files directory
sudo chmod a+w sites/default/files # Permissions

After that you can you try  this on your default configuration file...

<DIRECTORY />
      Options FollowSymLinks
      AllowOverride None
 </DIRECTORY>

 <DIRECTORY /var/www/drupal_site/>
     Options +FollowSymLinks
     AllowOverride All
 </DIRECTORY>

Source: https://github.com/darol100/lazydubuntu/blob/master/bin/includes/skeleton

And then re-start your server.

If this does not solve your problem here is a similar question (with the same error)

And here is the answer.

  This is a known problem, a natural result of clean URLs

  When you are on http://example.com/?q=node/15 and the browser sees a relative "files/filename" path it resolves it as
  http://example.com/files/filename. The ?q= part does not pretend to be
  a path, so the browser does not use it.
  When you are on http://example.com/node/15 and the browser sees a relative "files/filename" path it resolves it as
  http://example.com/node/15/files/filename because it considers node/15
  as a real path.

  So, when you use clean URLs the file links must have a front slash
  (and possibly a path if Drupal's home page contains an URL path). The
  browser sees the absolute path "/files/filename" and resolves it using
  the bare domain name. You need to edit all the file paths in the
  content and add a front slash.

  Alternatively, try the http://drupal.org/project/pathologic module
  which tries to be smart about it (or one of the other modules
  mentioned there).


Why does default .gitignore suggest ignoring config directory?

You are supposed to put that in a separate repository, I suppose. Note that the best practice workflow is to export the configuration and git the staging directory. You are not supposed to edit the active directory to the best of my understanding.

Edit: since writing this answer the default storage is now in the database and there's no more active directory.


{nid} is an auto_increment field in the table {node} - As all of the nodes are sourced from that one table it's able to keep its serialization. This is part of why UUID is such an important initiative in Drupal 8. It's not straightforward to maintain portability of content across environments for this reason.

The type is int(10) also known as unsigned so you're only limited by the data type limit of your preferred database and the disk space on your database server to store all those nodes. If it's MySQL that's 0 up to 4294967295.


How to give Permissions to User based on taxonomy selected while creating a content?

I think you are looking for Taxonomy Access Control

Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Three node access permission types: View, Update, Delete.


displaying updated time in aggregator block

I implemented the above requested functionality by using a template_preprocess_block and adding the fetched variable to the $variables['block']. Code for the same as below:

    function my_theme_preprocess_block (&$variables) {
      // fetch last updated time for feed 1 only other feeds don't need this value
      if (($variables['block']->module == 'aggregator') && ($variables['block']->delta == 'feed-1')) {
        $last_updated_timestamp = db_result(db_query("SELECT `checked` FROM {aggregator_feed} WHERE `fid` = 1"));
        if (!empty($last_updated_timestamp)) {
          $variables['block']->last_updated_time = 'Last updated on ' . date('D M d g:i:s T Y', $last_updated_timestamp);
        }
      }
}

but this seems to look bad as i'm hardcoding my feed id in the query besides the fact that i'm using a query in template.php but it works.

Leaving this question hoping someone could top with a better solution.


Is it possible to access the `session` table using db_query/db_update/db_insert?

Yes, it's a bad idea :)

No, there are no extra security measures in place that would stop you having access to the sessions table (certainly nothing that Drupal is imposing, and if your site is working then Drupal must be able to read/write to that table).

If you want to switch users programatically I can't think of a better way than how the Devel module does it:

function devel_switch_user($name = NULL) {
  global $user;

  if ($user->uid) {
    module_invoke_all('user_logout', $user);
  }
  if (isset($name) && $account = user_load_by_name($name)) {
    $old_uid = $user->uid;
    $user = $account;
    $user->timestamp = time() - 9999;
    if (!$old_uid) {
      // Switch from anonymous to authorized.
      drupal_session_regenerate();
    }
    $edit = array();
    user_module_invoke('login', $edit, $user);
  }
  elseif ($user->uid) {
    session_destroy();
  }
  drupal_goto();
}

Even if you don't have devel installed (which obviously you shouldn't on a production server anyway), just make a copy of the function in a custom module and tweak it to your needs.


How to display the user edit-picture form in custom block?

The ID you pulled from the DOM isn't the form ID, unfortunately. It's just the ID of the user image picker fieldset.

Take a look at the User Picture Field module. I haven't used it, so I can't personally vouch for it. However, it does make the user picture a field, which adds a lot of flexibility. I think Panels will let you move the field to the place where you want it to appear. You should also be able to use the editablefields module to make the image editable in the display.


If you enter the full path of the file, it should work but if you're looking to create the menu with a relative path, see https://stackoverflow.com/questions/4335700/drupal-primary-link-item-to-a-relative-file-on-the-server or How can I add relative path to a pdf file link in drupal menu


Enable the PHP input filter and add a text area to the footer of your view, then use something like the following to build an array of all of your files (taken from this tutorial):

<?php
function views_get_current_view_result() {
  $view = views_get_current_view();
  return $view->result;
}
?>

And then use that array to build the zip according to download multiple files as zip in php

This would be a lovely idea for a views display handler plugin module, which many would probably find useful.


How do I get the title of an entity in hook_entity_presave?

If the entity is a node, you can do:

$entity->getTitle();

Or:

$entity->get('title')->value;

Here are a list of methods for the Entity object, and for the Node object.


Node select list + dropdown + view of entity references

maybe you should try these modules (at least for a part of your question):

Inline Entity Form can help you with #3 (embed a node form within another node form with option on existing nodes)

Entity Browser could help you with #1/#2 (build your own widget, based on a View, here with a contextual filter on logged in user and relationship to favorites) - really nice tutorial here.

and Flag for favorites.

I hope this could give you some fresh ideas.


Add a Global: Result summary field to the footer. There is no need to turn on aggregation.


How do I tell Twig not to print any form field?

Loop through the keys

{% for key in element|keys %}
    {{ children|without(key) }}
{% endfor %}


Getting the pretty url for a node if it's a term

Figured it out, using drupal_get_path_alias. So something like in the node:

$url = drupal_get_path_alias('node/' . $node->nid);


Resetting outputted HTML markup to default?

Yes, it was the configuration of the fences module. I needed to cancel the override in the first section. Navigate to Fences configuration to change the settings.


This can be done in a few ways, you can do it all in the node template with Twig or you can create a preprocess function and create a variable for use in the node template. The key to learning what is in the array is to use Devel Kint. Without that, you won't know what is in the array.

First install Kint which comes with the Devel module for Drupal 8. Next, pick your node template (but this can be done in any kind of template) and examine the content variable like so (ideally at the bottom of the template).

{{ kint (content) }}

From this, we get debugging info printed on the page and if you expand the array, you'll see a whole slew of information. Right away, I see my background value and I can construct a path to print this out as

{{ content.field_background[0]['#markup'] }}

Now you can print this as a background style or class in a div

Hello

I've tested this ands it works great, the div rendered the background color I had selected in my field list on node edit.

Now this is not ideal so we probably want to create a variable for this in a preprocess_node in our theme's .theme file.

function MYTHEME_preprocess_node(&$vars) {
  $vars['bgcolor'] = '#' . $vars['content']['field_background'][0]['#markup'];
}

Now that I have a var created, it's much cleaner to print this out:

Hello

One note for above, you should probably wrap this with an if statement to check if it's empty or not.

This would work or structure the if statement where you like it

   {% if bgcolor %}

Hello

    {% endif %}


How to limit access to a view based on the contextual filter

If you are using Drupal 7 and Views 3.x, then for each contextual argument, you can specify a validation criteria from the Views UI. Look for this checkbox under the When the filter value IS in the URL or a default is provided section for a given contextual argument.

Suppose your committees are taxonomy terms in a vocabulary, say, Committee, then you can use the Taxonomy term validator. Otherwise, you can simply use the PHP Code validator and key in the custom logic that defines access to your view.

Think of this custom logic as a boolean method from which you can access the view object and the raw value of the argument and then based on this context, allow or deny the current user's access to your view accordingly.


Is this a "legal/normal" setup?

It's perfectly legal, and yes it's normal for modules that need or want to break their functionality down that way.

  Does nesting one module within another confer any special features between the two modules?

No, they’re just standard modules.

  Where in the drupal source code are modules searched for/loaded?

I think this is pretty much exhaustive for Drupal 7:

/modules/**
/profiles/*/modules/**
/sites/*/modules/**

  Is there any canonical piece of documentation that covers how module loading works?

I wouldn't have thought so - following the code is probably the best way to understand how it works. Core is pretty well commented.


How to send an email using Rules when a node's boolean field is changed?

Here are some details about how to make this work (using Rules):

Rules Event: Before saving content.
Rules Condition (1st): "Entity has field", whereas you should specify these values:

"node" (saved content) for the "data selector" of entity.
the machine name of your boolean field (for field).

Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different.

So part of the "clue" to make this rule work is the condition Entity has field. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Update (to further clarify the new questions in the "update" part of your question, with the quoted text copied from the update in the question):

  I am not sure what to pick at Data selector, while at bottom (Field: Value) i found the field I need.

You should select node (saved content), because you want to check if a "node" has the field you're looking for.

  ... but also did not find an option: "Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different."

For this you add an additional Rules Condition which is a Data comparison. And the actual data to be compared are:

original value of the field, which you should be able to find/select by first using as data selector the node-unchanged:...(unchanged content), followed by selecting the field name of your field from the additional list that is shown after you selected that node-unchanged:...(unchanged content).
updated value of the field, which you should be able to find/select by first using as data selector the node:...(saved content), followed by selecting the field name of your field from the additional list that is shown after you selected that node:...(saved content).


Blocks are cached by default.

You don't need to manually clear those caches when you change your configuration, but you need to flag/tag your blocks output to tell Drupal that your block output depends on your configuration.

Read the Cacheability documentation. What you need is something like this:

$output['#cache']['tags'] = $config->getCacheTags();


How do I remove the site name from the page title on a particular page?

Try the Page Title module. Here is a quote about it (from the module's project page):

The word "title" is a bit overloaded. Every piece of content in Drupal has a title, and so does every page. The page title is the one found in the HTML head inside the  tag. It is also used on SERPs (Search Engine Result Pages) and can greatly enhance your websites SEO (Search Engine Optimization).
This module gives you granular control over the page title. You can specify patterns for how the title should be structured and, on content creation pages, specify the page title separately to the content's title.


How do I disable a single option from select

The options can be hidden by a one liner code,

unset($form['field_name']['und']['#options'][1]);

where

['field_name'] is the name of the your field

[1] is the index of the option in the list

In my case [1] is Submitted, [2] is Reviewed, [3] is Accepted and [4] is Rejected


No page style appearing on Permissions page.

I recommend you to do the following:

delete css files under /sites/default/files/css and then checkout the administrator pages
go to /admin/appearance and select an administrator them at the bottom of the page. If its already been selected try to use another administrator theme
make sure "Use the administration theme when editing or creating content" is checked
clear your cache using drupal clear cache button under /admin/config/development/performance
Checkout Administer themes permission in the permission page /admin/people/permissions
try to open your site with another browser


redirect or rewrite /user/xx links to a module page

d'oh! thanks to @geoff above .. this seems to work (in a module called 'faces')

function faces_user_view($account, $view_mode, $langcode) {
    if ($view_mode=='full') {
        drupal_goto('faces/'.$account->uid);
    }
}


WYSIWYG error when using managed_file and AJAX

go around ckeditor.utils.js, the thing is that at various events ckeditorOff() function is called which causes ckeditor to go off, i just commented out a destroy call in the ckeditorOff() method and the RTE disappearance issue got solved


Why am I unable to send an email order using the Ubercart and Smtp Authentification module?

Okay I found the solution using the instructions at "Drupal – Ubercart and SMTP Authentication Support".

I installed Mail System module.
In the Mail System configuration, I updated the Cart module class, Order module class and Store module class so that they all use the SmtpMailSystem rather than UbercartMailSystem, as shown in the screenprint below:


How to detect which module creates session?

Unless you have a strong suspicion on a particular module or a small number of modules that could be creating a session, finding the 'culprit' module could be too tiresome.

I would suggest searching for the 'cookie name' instead of a string like '_SESSION' as a more accurate and a faster way.

Say if the cookie name is 'PLAY_ACTIVE_ACCOUNT' (real example from site play.google.com), you could navigate to the parent directory of your contrib module and do a grep -iRn PLAY_ACTIVE_ACCOUNT * to find the filename and line number of where this session cookie is being set. And then disable the module or take other action.

You can discover the name of your cookie by using your browser. In chrome you could do this by typing chrome://settings/content in a new tab and then clicking on the button 'All cookies and site data'. And then typing in the name of your site domain (like I have used play.google.com for example)


Accessing content variables through the page variable

Per the docs on the core page.html.twig:

 \* Page content (in order of occurrence in the default page.html.twig):
 \* - messages: Status and error messages. Should be displayed prominently.
 \* - node: Fully loaded node, if there is an automatically-loaded node
 \*   associated with the page and the node ID is the second argument in the
 \*   page's path (e.g. node/12345 and node/12345/revisions, but not
 \*   comment/reply/12345).

The node variable is available in page.html.twig. If you need to access one its fields you can use {{ node.field_myfield.value }} to print it out.


Drupal 8 Bootstrap Theme Background "transparent" (e.g. offcanvas-lining visible)

Looks like this was being caused by the "Settings Tray" module which was added in Drupal 8 and which I had activated. Deactivating the module has fixed the issue for me.

It seems other people also have this issue with other themes: https://www.drupal.org/node/2819091


How do I put username into email when send mail to role in Rules?

add rules conditional module, now in actions you can add more conditions, in actions fetch entity by id, node-author, drill until you find UID, add a conditional, add an if, entity has field, entity-fecthed-author-by-id, select your field, now you have what you need, repeat as needed, for every field, a conditional, an if and your field. done.
Your rule will look something like this:


How to always show poll results view instead of vote view on poll single node?

It's template_preprocess_node() to hook in :D

function MYTEMPLATE_preprocess_node(&$vars) {
  // check if we are in the right place
  if ($vars['type'] == 'poll') {
    if ( /* add other conditions here if you need to */ ) {
      // then unset the voting view first
      unset($vars['content']['poll_view_voting']);
      // and add the results view instead
      $node = node_load($vars['nid']);
      $vars['content']['poll_view_results'] = array('#markup' => poll_view_results($node, TRUE, FALSE));
    }
  }
}


Take a look at the core Views example Archive (admin/structure/views/view/archive/edit) which is disabled by default.


How to set paths where to load administration theme?

You need a route subscriber, where you search for routes, which have a path you want to load with the admin theme, and add the option:

$route->setOption('_admin_route', TRUE);

More info Altering existing routes and adding new routes based on dynamic ones.

Example

There is an example in core. You can configure the admin theme for the node edit form in UI and this route subscriber is applying this configuration:

namespace Drupal\node\EventSubscriber;

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

/**
 * Sets the _admin_route for specific node-related routes.
 */
class NodeAdminRouteSubscriber extends RouteSubscriberBase {

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Constructs a new NodeAdminRouteSubscriber.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
  }

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($this->configFactory->get('node.settings')->get('use_admin_theme')) {
      foreach ($collection->all() as $route) {
        if ($route->hasOption('_node_operation_route')) {
          $route->setOption('_admin_route', TRUE);
        }
      }
    }
  }

}


So the context is mandatory and it is actually important because it sets the data you want to fetch when the rule is triggered.

I just needed to set the context to the good entity as follow.

"entity" = @ContextDefinition("entity:uc_order",

The working annotation is the following.

/**
 * Definition of the action performed.
 *
 * @RulesAction(
 *   id = "my_action_id",
 *   label = @Translation("My action label"),
 *   category = @Translation("My module"),
 *   context = {
 *     "entity" = @ContextDefinition("entity:uc_order",
 *       label = @Translation("Entity"),
 *       description = @Translation("Specifies the entity, which should be saved permanently.")
 *     )
 *   }
 * )
 */

Then you are able to fetch the current uc_order in the administrative page.


No, there is no such thing.

One of the typical update block configuration tasks was changing the cache flag (before 6.22, that is). You can find updates that mess with the {block} table directly in many projects, including mine: privatemsg_update_6002().


How can I override the string programmatically in forum topic list?

You could do it using the String Overrides module.

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


Redirect a form just if the form is loaded in specific page(url)

It can be accomplished adding 3 functions to your custom module:

The first one is to implement hook_form_alter():

function my_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='user_login') { // It will be executed only on this form.
    // Check if the form is loaded in your custom path.
    if (current_path() == 'my_custom_path') {
      array_push($form['#submit'], 'my_module_login_custom_path_submit');
    }
    else {
      array_push($form['#submit'], 'my_module_login_user_submit');
    }
  }
}

The second one is to implement the redirect to your custom path:

function my_module_login_custom_path_submit(&$form, &$form_state){
  $form_state['redirect'] = 'my_custom_path';
}

The third one is to implement the redirect to user page:

function my_module_login_user_submit(&$form, &$form_state){
  $form_state['redirect'] = 'user';
}


Webform Custom element option values validate

due to explaining in comment i am thinking you are making a custom
Plugin\WebformElement;
aka
namespace Drupal\YOURMODULE\Plugin\WebformElement;
use Drupal\webform\Plugin\WebformElementBase;
...
if this is the case look at this example
( '#element_validate' => [[get_class($this), 'validateOptions']] )
 public function form(array $form, FormStateInterface $form_state) {
  $form = parent::form($form, $form_state);
  $form['general']['mycustom'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('mycustom Settings'),
  ];

  $form['general']['mycustom']['some_question_text'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Some Question title '),
    '#required' => TRUE,
    '#default_value' => $this->getDefaultProperty('hello'),
    '#element_validate' => [[get_class($this), 'validateOptions']], //HERE <----
  ];

........
later on in the same class ...
.......
 /**
  * Example validate
  */
 public static function validateOptions(array &$element, FormStateInterface $form_state) {
   $name = $element['#name'];
   // EG ... $options = $element['#options']
   $form_state->setErrorByName($name, t('@m', ['@m' => 'HELLO']));
 }


I want to build multidimensional array at Twig

In Drupal 8 use an Attribute object instead of a multidimensional array:

D7 PHP:

$attributes['attributes']['class'] = array();
$attributes['attributes']['class'][] = 'innerTab';

D8 Twig:

{% set attributes = create_attribute() %}
{% set attributes = attributes.addClass('innerTab') %}

You can use the Attribute object in Twig link():

{{ link(title, support_url, attributes) }}


Drupal Commerce Need Function To Retrieve Customer Profile Fields From Commerce Order

There are probably a few different ways to bridge that gap but here are the first 2 that spring to mind:

Use commerce_customer_profile_load_multiple instead, and make use of the $conditions parameter, e.g.

$profiles = commerce_customer_profile_load_multiple(array(), array('uid' => $order->uid));

foreach ($profiles as $profile) {
  // Make sure this is the correct profile (users can have multiple profiles)
  // and extract the field values as you would with any entity (field_get_items())
}

But the $conditions array is deprecated for core entities so probably will be for commerce entities too at some point.
Use an EntityFieldQuery to get the profiles, e.g.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_customer_profile')
  ->propertyCondition('uid', $order->uid);

$results = $query->execute();

if (!empty($results['commerce_customer_profile'])) {
  $profiles = commerce_customer_profile_load_multiple(array_keys($results['commerce_customer_profile']));

  foreach ($profiles as $profile) {
    // ...
  }
}


how to get the values of a view in _preprocess_views_view_fields drupal7

hope this will help,

     function yourtheme_preprocess_views_view_fields(&$vars) {
    if ($vars[view] -> name == 'yourviewname') {
         foreach ($vars[view]->result as $key => $value) {
            kpr($value -> field_field_name['0']);//here you will get the name field RAW value and  RENDERED value in array.
        }
    }
}


db_query() function in a foreach cycle - only the first query is getting executed (D6)

I'm not sure if checking the return of $query_result against empty() is meaningful, since the only indication query failed is if it returns FALSE. Same for $affected_rows, since the query may be successful but not necessary change any rows.

I'd suggest installing Devel module because it has a feature which records and prints all DB queries on a page load. This would enable you to see the actual query(ies).


How do I apply a global filter on view tabs?

You can use Global filter which creates filter widgets as blocks based on field or view of your choice and you can use the filter choices in ANY view as contextual filter.

Here is a simple example usage

For basic page create List (text) - field_choices with widget Select list and values choice1 choice2 choice3

Create some basic pages to include 1 of the 3 choices
Create or modify the view and make it display the choice for each result

Add contextual filter with choices as field and provide default value Global filter field

Go to Structure > blocks and add Global filter block 1 to a region of you choice and configure it to display choice field as a filter with default widget

Visit the view page that has the contextual filter (on choices) and you should be able to filter the view based on the Global filter (choices dropdown widget)

You can add the same contextual filter to as many views (or view displays) as you like


How to print the path alias without "/" in views

If you have a custom module of your own, you can use the function below.
To find the exact structure of the data you want to modify, you can use dpm or just simply print_r.

function hook_views_pre_render(&$view) {
    if($view->name == "MY_VIEW"){
        foreach($view->result as $key => $r){
           $view->result[$key]->path[0]["rendered"]["#markup"] = substr($view->result[$key]->path[0]["rendered"]["#markup"], 0, -1);
    } //if
 } // function

As for a direct way, I was trying and I think I even post a question, but to no success. Surely it is much simpler but don't know how to.


How to check if managed_file has uploaded a video and use it in states

If you examine the comments in the documentation, there are several things to look out for:

You may need to target the element's widget, as mentioned in this comment. Most likely you would do this in a #process callback or in a form alter hook.

This is a good nuance to understand - thanks! Targeting the widget
worked for me on a number field. It gets ignored otherwise.

// My number field is hidden unless repeat is selected
$form['field_myfield_num']['#states'] = [
  'visible' => [
    ':input[name="field_myfield_select"]' => ['value' => (string) 'repeat'],
    ],
];

// My number field is set as required when repeat is selected.
$form['field_myfield_num']['widget']['0']['value']['#states'] = [
  'required' => [
    ':input[name="field_myfield_select"]' => ['value' =>  (string) 'repeat'],
  ],
];

In the same comment above, we also see that sometimes it helps to cast your candidate value to a string: ['value' =>  (string) 'repeat']. I've also seen this explicitly mentioned elsewhere, but can't find the reference.

It is possible to test for a negation using '!value', as seen in this comment:

I had a form with a field of #type select_or_other, which renders like
radios. I wanted to enable the submit button when the form element was
not "none". The following worked for me:

$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Donate'),
  '#button_type' => 'primary',
  '#states' => [
    'enabled' => [
      ':input[name="amount[select]"]' => ['!value' => 'none'],
    ],
  ],


Using Rules and Rules Once per day how can I check when a node's date has expired?

From the "...adding a condition to check for a particular field on the node type in question..." in your question, I bet you are aware about the importance of adding a Rules condition Entity has field (related to your field you're looking for). If not have a look at what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

However, even though nowhere in your question you indicate which Rules Event you're using, I bet you're using the wrong one. And the "Rules once per day" in your title is probably a good indication of what you really try to use as a kind of Rules Event (which is not really an event).

Nevertheless, I think you're just using the wrong approach (sorry). What I would do in your scenario, is a variation of my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder". Some more details about how to adapt that answer to fit your case here:

Create a variation of the Rules Component (in Step 2) to change that boolean field for "a" node (which at least requires the node id as a parameter). Use the "execute" link in front of the Rules Component to QA-test your component (with a single node id, etc).
Create a variation of the Rule (in Step 3) like so:

Use a Rules Event like "when such node gets created or updated" (something that fits your case).
In the Rules Condition of that rule, for sure you'll be able to use the "Entity has field" condition (for your date field).
In the Rules Action, you "schedule" the execution of the Rules Component mentioned above. For this you need to enable the Rules Scheduler, and that should do the trick.

Last but not least, be patient ... and wait until the specified date arrives, then wait for your next cron job to run (if you don't run that, nothing will actually get executed, be aware!). And then: voilà.


Add following code in "themename.theme"

function themename_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('block_id');
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
 $variables['your_block_name'] = $block_content;
}

in twig template file use following variable

{{ your_block_name }}


How to check whether multi value field is of type field_collection_item or not?

That's how an EntityMetadataWrapper stores multiple fields. There are only those two types, so just use

if($req_field['type'] == 'field_collection_item' || $req_field['type'] == 'list<field_collection_item>') {
  // So something here
}

Or some variation on that.