You can set the "Filter identifier" for each exposed filter to use the same name. This is available under the "MORE" options in the filter's settings.

These will be used as GET parameters in the request and picked up by both views. This however also means that you can't use ajax with either views as they need to detect the parameter during a page request.


Create additional menu page for node that can be accessed by the nodes' alias with /page?

You have two options.

1. Using the Sub-pathauto (Sub-path URL Aliases) module.

This is based on pathauto, and will create additional aliases for node sub-pages.

This also works for other entity types such as user/123/contact -> people/geronimo/contact, if user/123 has the alias people/geronimo.

2. Write a custom wildcard loader (far more work).

I am going to use the word "slug" here, which I remember from Wordpress.

The usual node path is node/%node, which will trigger the node_load() wildcard loader. This wildcard loader only takes node ids. It does not work with node titles. So, node_load(123) gets you the node with that id, but node_load('node title') will return NULL.

You could now create a new module "mymodule", and use hook_menu() to define a separate path article/%mymodule_article_slug, and sub-paths article/%mymodule_article_slug/page, article/%mymodule_article_slug/edit, etc.

This is going to be some work, you need to look into node.module and the hook_menu() implementation found there, and copy a lot from there. Or you could use hook_menu_alter() instead of hook_menu(), and copy some of the data already registered for node/% and friends.

The essential trick now is to define a wildcard loader for %mymodule_article_slug.

/**
 * Wildcard loader callback for '%mymodule_article_slug'.
 *
 * @param string $slug
 *   Part of the url identifying the node, e.g. "pink-elephant"
 * @return object|null
 *   The node object, usually an instance of stdClass, or
 *   NULL, if no such node exists.
 */
function mymodule_article_slug_load($slug) {
  // Load the node identified by $slug.
  $node = ...;
  return $node;
}

Now it gets insteresting. How do you load the node identified by the "slug"?
There are different ways.

You could store the slug in a field on the node, and then use EntityFieldQuery to load the node with that field value. You also need to decide what to do if more than one node has the same slug.
You could use path + pathauto and find the node where the alias is "article/" . $slug. drupal_get_normal_path() can help you with that.

With method 2, your code would look like this:

function mymodule_article_slug_load($slug) {
  // Load the node identified by $slug.
  $normalpath = drupal_get_normal_path('article/' . $slug);
  if ($normalpath && preg_match('#/node\/(\d+)$/', $normalpath, $m)) {
    $nid = (int)$m[1];
    if ($nid > 0) {
      return node_load($nid);
    }
  }
}

EDIT: This only works if the "slug" does not contain any slashes by itself!


Why does core update result in 'The requested page could not be found'?

i found nginx drupal 8 host config here https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/

my config is this

server {
server_name www.EXAMPLE.COM .EXAMPLE.COM;
root /var/www/EXAMPLE.COM/www;

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

# Very rarely should these ever be accessed outside of your lan
location ~* \.(txt|log)$ {
    allow 192.168.0.0/16;
    deny all;
}

location ~ \..*/.*\.php$ {
    return 403;
}

location ~ ^/sites/.*/private/ {
    return 403;
}

# Block access to "hidden" files and directories whose names begin with a
# period. This includes directories used by version control systems such
# as Subversion or Git to store control files.
location ~ (^|/)\. {
    return 403;
}

location / {
    # try_files $uri @rewrite; # For Drupal <= 6
    try_files $uri /index.php?$query_string; # For Drupal >= 7
}

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ '\.php$|^/update.php' {
    fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
    #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

    include             /etc/nginx/conf.d/fastcgi_params.conf;

    fastcgi_param       SCRIPT_FILENAME     /var/www/EXAMPLE.COM/www$fastcgi_script_name;
    fastcgi_param       DOCUMENT_ROOT       /var/www/EXAMPLE.COM/www;

    fastcgi_param       PHP_ADMIN_VALUE     upload_tmp_dir=/var/www/EXAMPLE.COM/tmp/upload;
    fastcgi_param       PHP_ADMIN_VALUE     session.save_path=/var/www/EXAMPLE.COM/tmp/sessions;
}

# Fighting with Styles? This little gem is amazing.
# location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
location ~ ^/sites/.*/files/styles/ { # For Drpal >= 7
    try_files $uri @rewrite;
}

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires max;
    log_not_found off;
}
}

AND the problem disappears.


How to add CSS classes to a an image which belongs to a content type?

You can use hook_node_preprocess in your themes template.php file to add to the 'attributes' array for the node before the variables are sent to your node template. when your field gets built up into html it will then have your class.

If you enable the devel module you can add the following to template.php to see what this 'build array' which is used to render the node looks like.

function twt_preprocess_node(&$vars) {

    dpm($vars);

}

To alter the classes added to your field use something like the following (though look to the above to find out if you are putting your class in the right place).

function twt_preprocess_node(&$vars) {

    $vars['field_myimagefield']['#attributes']['class'][] = 'myclass';

}

Some useful reading:

Render Arrays in Drupal 7
Setting up variables for use in a template
hook_preprocess_HOOK (Drupal 7)


Difference between function names from Drupal Devel

Maybe this can help you a bit:

dpm($var) or dsm($var) - displays the information about a variable in the form of system messages using Krumo.
dvm($var) - displays the information about a variable in the form of system messages using var_dump($var).
dpr($var, $return = false) - displays the information about a variable at the top of the page, using print_r($var, $return).
dvr($var, $return = false) - displays information about a variable at the top of the page, using var_dump($var, $return).
kpr($var, $return = false) - displays the information about a variable at the top of the page using Krumo.
dargs() - displays information about the arguments of the current function at the top of the page using Krumo.
dd($var, $label = null) - writes the information about a variable in the file drupal_debug.txt, which is located in the temporary directory (admin/settings/file-system).
ddebug_backtrace() - displays the call stack at the top of the page using Krumo.
db_queryd($query, $args = array()) - this is a debug version of db_query(), which displays it at the top of the page after the execution of $query.
dpq($query, $return = FALSE, $name = NULL) - this is an analog to the function db_queryd() only available in Drupal 7. Outputs SQL query using dpm() with substituted arguments. The first parameter takes an object DBTNG.


Create a RSS using Views of a content type

Following comment exchange under the question - just add a new view showing "content" of type <your_type>, tick "Create a page" and "Include an RSS feed" underneath. This will give you a feed with list of all nodes of a specific type. Then just play with all other settings to get what you need, and that's it.


Sending a file in e-mail message body using Views Send

take a look at the Entity Email Module:

The Entity Email module lets users create their own email templates
which can be used to send emails. Emails sent can also be recorded in
the DB if needed. Emails can be sent programmatically or by the mean
of the Rules module.
Main features:
Built on top of the amazing entity API
Allow token substitution
Templates can also contain attachments (PDF, TXT...)
Rules module support, so email actions can be triggered by any Rules
Supports the MimeMail module for HTML emails.
Build with the fields API Emails sent> can be recorded in DB

I don't know that it will integrate with Views on it's own, but you may be able to manually make it work the way you want.


How can I return a different number of results per page for a view if a user is accessing the site with a mobile device?

You could use Browscap module along with Browscap Block which would add the visibility of blocks depending on device. Next you could add two blocks one for Normal screen and one for mobile devices.

  Browscap Block

  Browscap Block adds visibility options to block configuration settings
  to allow you hide or show blocks in mobile devices.

If you do not want to create multiple views then you could use the browscap function in your template file to detect the browser and then restrict the number of items displayed. The function would be browscap_get_browser()

This could either be done in hook_views_pre_build function or with in the Style output template file where it loops through the $rows array. you could restrict it the number to 8 depending on the device by exiting the loop once you reach the required count.


Views field rewrite onClick attribute not rendering

Views rewrite uses the filter_xss_admin function to produce safe html. It's designed as a security measure and is in place even if the user has permissions to add PHP and unfiltered HTML in other contexts.

You can work around by using Views PHP for example. See this issue at drupal.org for discussion and more on workaround approaches.


how to alter "other" field label or change the label name

For customizing the 'more items' see Issue #2953803: Allow multiple value elements item(s) label to be customized.

For 'How to constrain the sum of these responses to be 100?' you are going to have to write custom client-side and server-side validation code.


How do I display a help text with field form?

Use #description attribute.

$form['field_foo'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Foo'),
  '#required'      => true,
  '#default_value' => 'foo',
  '#description' => t('Help text for Foo field'),
);


Ok. After testing and more research "drush cr" does the job. Service.yml is reloaded after clearing the cache.


Programmatically get webform submissions of a specific nodes webform

Thank you 4k4. Here is now the correct and full code for use in mytheme.theme file (we need the getData() function:

$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$webform_submission = $storage->loadByProperties([
  'entity_type' => 'node',
  'entity_id' => $variables['node']->id(),
]);
$submission_data = array();
foreach ($webform_submission as $submission) {
  $submission_data[] = $submission->getData();
}


The strikethrough effect (what you describe as 'cross text') over the language is because the specific content which you are viewing does not have content for that language in the language switch block.

The particular effect comes from the rule .locale-untranslated in modules/locale/locale.css line 2 (D7.36).

If you wish to remove it, either add content for the particular language, or add a rule as the following to your custom theme:

.locale-untranslated { text-decoration: none; }

Also for the record (I suppose you already use it) there is a module for displaying language icons.


How to set a specific vocabulary in a taxonomy reference field during migration?

The field settings are created in the process plugin, d7_field_settings, in this section of the process pipeline.

 settings:
    plugin: d7_field_settings

It seems that you will need to write a custom process plugin. You may want to preserve the settings created by d7_field_settings. I don't recall what d7_field_settings does. So you could put something like this after the settings property is set..

 'settings/handler_settings/target_bundles': my_custom_plugin

Edit:
Glad got it working. Found the core issue for this today, https://www.drupal.org/project/drupal/issues/2763637.


Insert data into entity programmatically

Yep. Just use any of the methods available to create the entity and save it.

use Drupal\contact\Entity\Message;

$message = Message::create([
    // And other fields required...
    'subject' => 'Subject',
    'message' => 'Message...',
    'recipient' => 1,
]);
$message->save();


In panels, does the right region get its argument from the left?

It gets its context from the Contexts that you load into the Page on the Page Manager part of the dialog. It looks like this:

In this case I started to override the node view page, so it comes with the initial context of the node (nid, date published etc).

I then added a relationship on that same page of User to bring in the related Author's User data. After I saved it brought that context in for me and it looks like this:

Note the User from Node part.

I can continue to bring in context connected to the node, or now also connected to the user.

To embed a view in a Panels pane you need to first install Views content panes which is part of CTools. You then add a Content Pane via the Views UI to the view. You set the Contextual argument and in ADDITION you need to click on argument input (middle part of the Views UI) to tell the view where the context is coming from. This dialog will then bring up your contextual argument that you added, and a selection for you to specify where or what to get the context from. For the most part you will select From Context and for a node select Node, Content id. Now back in your Panels UI you can add a view as content. You select View panes (though this is just a default that is specified on the view itself and you can alter it per view), select your view, and it will pick up the contextual filter and the type of context you specified for it, and automatically make a selection of contexts that match that you have enabled in Page Manager.

So in order to decide what panel needs what context (or arguments) you need to first establish how the content in the specific panel is related to the type of page your are creating a variant for. I your case of author and stories, you can start with a user page and you want to end with stories on that user page written by the user. Your initial context will be User. No need to bring in extra context as your view for the right panel will take a uid contextual filter. Your right panel will embed a Views content pane with a contextual argument of uid that you connect as the author of the nodes. You will specify in that view that you want the argument input to be of User type from Context, and in your panel, when you add the content pane it will allow you to link it to the user context that is available.


Create referral url for user and add UID to hidden field when url used

If I understand the question correctly, you want something like:

h(tt)p://www.example.com/register?uid=25

where register is a webform that the incoming person can access?

I would start by creating the form at the correct location with all of the elements you want
use some javascript (or form override) to hide the relevant form item that will hold the uid
override the form submit function to assign the uid in the url to the hidden element

take a look at the documenation for webform, and the Drupal Form API for specifics.


Answering to myself :]

Add a new filter for, say, field_file:fid, make it exposed and choose Is not empty operator.

It will not work :D It is a known Views issue. Luckily, comment #70 in that issue has a patch to fix this operator behavior, apply it and enjoy :)


$_SERVER['DOCUMENT_ROOT'] will get you the d:\xampp\htdocs and $base_path or base_path() will give you the Drupal part.


Why a successful migration is showing (0 created, 0 updated, 0 failed, 0 ignored)?

Got answer!!

I missed the following code from the abstract class MigrateDestination:

/**
 * Maintain stats on the number of destination objects created or updated.
 *
 * @var int
 */
protected $numCreated = 0;
public function getCreated() {
  return $this->numCreated;
}
protected $numUpdated = 0;
public function getUpdated() {
  return $this->numUpdated;
}

These variables need to be updated during the import process and need to be defined/updated in class that is extending the MigrateDestination.


Why anonymous users can only see 1 link in navigation menu?

That is because they do not have the necessary permission. So for example they do not have permission to create contents of type (article, blog, basic page and product) in your case. And I want to believe you don't want anonymous users to create products, pages, e.t.c.

To assign anonymous users new permissions, go to admin/people/permissions


How can I show a block in a view page, excluding its paginated pages?

You can also achieve the same in using following snippet, in the blocks visibility settings by turning PHP code on,

<?php
  $url = request_uri();
  $pos = strpos($url, "page");
  if ($pos === false && arg(0) =='news') {
    return TRUE;
   }
 ?>


This is a temporary problem.

do these steps:

1-disable overlay module.

2-click on Save configuration at the end of page.

3-click on modules again

4-enable overlay module Save configuration

its like reseting a computer


How can you expose a Quantity update / delete field in the checkout cart?

It actually isn't possible, at least using the Views Forms functionality that we use to create the shopping cart form at /cart. The issue is that using a Views Forms field in a View turns the entire View into a form - as in, you get a new form element in the DOM that wraps around the entire View HTML. Because the cart contents checkout pane is already part of a form, you end up nesting a form within a form - which just doesn't work.

You have two basic options to work around:

Alter your checkout form to embed custom quantity editing fields in that part of the checkout form. Difficult, not sure it's possible. (In the same vein, you could also figure out how to make Views Forms embeddable inside other forms - even more difficult, but probably more possible.)
Use a custom block on /checkout to show the cart contents with a Views Form that saves updates asynchronously (not the default behavior). The idea there would be you'd have a form with quantity edit fields outside the checkout form that you'd be using to update the cart contents completely separate from whatever happens on the checkout form. I say you'll want to use AJAX to save the updates because you don't want to have someone submitting a cart update form after putting data into the checkout form elements below and losing data.

These two options work with the existing Views powered cart contents pane. If I had this scenario and owned the feature, I'd probably just create a custom checkout pane and eschew the Views powered form entirely.


Profile 2 fields not displaying in registration form

Make sure you check to "Show during user account registration" on the profile type.

Admin > Structure > Profile Types > [Type] > Edit


Avoid the preprocess/hook function defined from the Zen theme is called for its sub-theme

Those are part of HTML5 support bundled with Zen 7.x-5.x. Your options are either downgrading to Zen 7.x-3.x or patching Zen. Please open an issue at Zen's issue queue asking to provide an option to turn on or off the header manipulation.


How to check if node is being rendered inside view?

You can check to see if $view is set and is an object in the template file; if it does, it means the node is being rendered in a View. From there you can even check that the View is the correct one if you need to.

if (isset($view) && is_object($view)) :
  // Do something
endif;


Content pane of users related to node by field using panels, views (D7)

The problem was that in the display fields section for my Content Type I had service_type hidden (because I only wanted to use it to filter Users without having to use a vocabulary), as such it wasn't featuring in the context and wasn't being passed into my View Content Pane.

I had to leave it displayed, then create a custom display for 'Full Content' and hide the field there instead.


How do I set the total submissions limit when I create a node?

Go to the Webform's settings
(/admin/structure/webform/manage/contact/settings)
Scroll to 'Submission Limits'
Set 'Total submissions limit per entity' or 'Per
user submission limit per entity'

I think the labeling and additional help text could help better define this features.  Feel free to create a ticket in the Webform module's issue queue


Call to a member function getFileUri() on null in ImageItem::presave()

I a similar issue on a previous migration, I found that a core issue sometimes causes that error.

The patch submitted fixed the problem on my case.


CKEditor and IMCE: how to access to public files directory

Chances are you haven't set filebrowser permissions within the IMCE config page.

Go to Configuration > Media > IMCE
Setup/confirm the IMCE Profile for filebrowsing.  NOTE:  IMCE has its own "profiles" which can be used as roles specific to the filebrowser functionality. The default User-1 role has the ability to see all files/folders.  If you need more granular access to subfolders/specific folders within the files directory, setup a new profile.
Check that your blogger/blog contributor role has a profile assigned in Public Files column (and if necessary, private files column).

In addition to checking the IMCE filebrowser permissions, you'll want to check the individual field settings.  It can only be set to save/upload to either Drupal's public files directory or private files directory.  It doesn't allow content managers to choose which directory to upload/save to at time of upload/per piece of content.


Finally I found that I have an module conflict, if you decide to use DDF (Dynamic Dependent Fields) you must think before make tests with profile2 fields.


Getting the first URL alias for a node in a SQL query

Since the value in the src column in the url_alias table is predictable for nodes you can just query it directly, without the need for any joins:

$nid = 1; // node id
$src = 'node/' . $nid;
$query = db_query("SELECT dst FROM {url_alias} WHERE src = '%s'", $src);

If you definitely want to use a join though, something like this will work:

SELECT n.nid, ua.dst
FROM {node} n
INNER JOIN {url_alias} ua ON ua.src = CONCAT('node/', n.nid)


Using Event Subscriber change the product custom field value after first checkout of that product

Do you really want to change the status of the product or the product variation?

$items is an array of OrderItems. If you loop over the items, you can get the referenced purchased entity of the single item with $purchasedEntity = $item->getPurchasedEntity();. If you only want the first item you can access it like so $purchasedEntity = $items[0]->getPurchasedEntity();.
In case the PurchasedEntity is a ProductVariation you can get the product with $product = $purchasedEntity->getProduct();

In case you want to change the status of the product:

$product->setUnpublished();

Or for the variation:

$variation->setActive(false);

If you want to set any custom field on the product variation:

$variation->set('your_custom_field_name', $value);

docs
This assumes you use the default commerce2 product architecture. It is absolutly possible that you get other purchasable entities than ProductVariations back from the OrderItem.


Why isn't media respecting my allowed file type settings

My guess based on my own experience is that the uploaded file shares the same mime type as the publication files configuration, and the system is asking the user which file type to designate. Example, if both types allow for PNGs, it won't be able to determine the file type for you. Try uploading a file who's mimetype isn't shared by others; you won't get that dialog.


How can you display the current user's name in the header region?

Using php filters is not recommended.

Instead create a User view for it.

Steps to creating a user view:

Go to Admin -> Structure -> Views
Click on "Add new View"
Now simply create a User view.

Click on Continue and edit button.
Add a contextual filter for uid.

Click on apply button. And the filter value as "User Id from logged in user".

Click on Apply button.
In the field, add the name of the user as the field to display. If you want to show more things just add more fields to it.

Save the view and place the block in the header region.


How do I do git clone with drush to download the HEAD version of a module?

drush dl views-7.x-3.x --package-handler=git_drupalorg

Update:

True, if there are commits after the dev release was packaged, you will need to run git pull to advance to HEAD after checking out via drush dl.  If there is no packaged dev release, and Drush checks out a stable release, then you need to run git checkout 7.x-3.x after drush dl.

There is no Drush command to do a verbatim git clone; part of the "value add" of drush dl is that it grabs published releases.  If git clone is what you want, perhaps a short bash script would be your best solution.  Something like this:

Usage:

$ clonedev views 3

Example script:

#!/bin/bash

MODULE=$1
VERSION=$2

DRUPAL=$(drush status "Drupal Version" --pipe | sed -e 's/\..*//')
if [ -n $DRUPAL ] ; then
  cd $(drush drupal-directory modules)
else
  DRUPAL=7
fi

git clone --recursive --branch $DRUPAL.x-$VERSION.x http://git.drupal.org/project/$MODULE.git

Modify to suit.


Can I manualy add modules in Drupal 7 just by pasting them in the modules folder?

If you have a single site setup:

Contrib modules go in /sites/all/modules/contrib/

Custom modules go in /sites/all/modules/custom/

Custom themes go in /sites/all/themes/

If you have a multi site setup:

contrib modules go in /sites/site_name/modules/contrib/

custom modules go in /sites/site_name/modules/custom/

custom themes go in /sites/site_name/themes/

I think some of the language in this post is dangerous, remember, do NOT put modules in the root modules directory, that is DRUPAL CORE.  Everything you code and download should go in the directories I've mentioned above.


Use relationship for Views taxonomy term filter

I've been able to do this with a simple "Content: Referenced product" relationship in my view. If you try using any of the "Content: xxxxx" filter fields, they won't work, as you're noting here. So, "Content: has taxonomy term ID," won't let you choose the relationship.
However, if you use the "Commerce Product: xxxx" (where xxxx is the term refrerence field) field for your contextual filter, it'll work with the relationship.


CKeditor: Add class to all ul and ol elements on output

There is no reason to do that for styling purposes. You can target the ul and ol elements by their parent container. The classes depends on your theme output, but consider this for the Garland theme:

/* Style all ul and ol elements from the body output. */
#center .node .content ul,
#center .node .content ol {
  /* Styles here */
}

If you are missing classes you can add those in the page.tpl.php and node.tpl.php templates.


can I call my entity checkCreateAccess function from custom code?

Something like this should do the trick.

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

$entity_type_mgr = \Drupal::getContainer()->get('entity_type.manager');
if (!$entity_type_mgr->getAccessControlHandler($type)->createAccess($bundle)) {
  $permission = "create $bundle $type entities";
  throw new AccessDeniedHttpException("You don't have permission to " . $permission);
}


How do I get a freshly updated value (i.e. not the cached value) using entity_metadata_wrapper?

The cache can actually be cleared using the entity_load function and passing a value of true for $reset which will clear the cache and update future references to it including wrappers retrieved from entity_metadata_wrapper:

entity_load("node", array($nid), null, true);


Cannot change CSS after CSS/JS aggregation

CSS/JS aggregation's purpose is to bundle all your non-external css/js files into a single file. This way instead of requesting multiple files and requiring multiple connections with the server, the client only has to download the unified css/js file once. However, this specific file is not re-created every time you make a change to your css or javascript. You will have to manually do it. Here is how:

In Drupal 7 go to:
Administration > Configuration > Development > Performance (admin/config/development/performance)

and click the "Clear all caches" button. Notice that this will clear all caches of your site.

The method that I use more often though is to clear all the caches through Drush (if you do not know what Drush is, you should really check it out since it's a real life saver). Instead of navigating to the URL and clicking the button, you can just write the simple command:

drush cc all

in your command line and all caches will be cleared.

Keep in mind, that if you are still theming/developing your site, you should disable CSS/JS aggregation. If you don't, you are adding more workload to the server that is rebuilding the unified css/js files every time that you press the "Clear All Caches" button. The specific option should only be turned on on production sites where css/js files have been finalized.


Create one-off page with specific fields and template

Use the Empty Page module and create an empty page.

Just like node content types, you can create a custom block type in /admin/structure/block/block-content/types

Add fields to your block type, and then in /admin/structure/block/block-content create a block of your block type.

Place block in content region and for Visibility > Pages put the URL for your empty page, so the block is only visible at this page.


You can use SSL Certification for securing Login Box which opens the box on https. Add a Login link to your pages and it opens the login box on https.


You're looking for $base_url global:

global $base_url;

If you want to have this in a preprocess function, you'd have to call it within that function; for example:

function YOUR_THEME_preprocess_whatever(&$variables) {
  global $base_url;
  // Now you can use it.
  $variables['base_url'] = $base_url;
}


Where can I configure user and admin email message in Ubercart cart module?

Go to

  sites/all/module/ubercart/uc_order/templates/

than select file user or admin


You can use the where() method for a SelectQuery:

...
$q->where('CAST(n.nid AS SIGNED) > :nid', array(':nid' => 11517));
...

So the choice is yours which type of query to use.


See handbook page Comparison of Rotator / Slider modules.


how do I disable modules in commerce kickstart

Scroll down to bottom of left column for save button.

A module worth mentioning is https://www.drupal.org/project/module_filter. It makes the module page a lot more user friendly.


pages accessible only by specific groups

Try the Nodeaccess module, here is a quote from its project page:

  ... is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.


Contextual Filter not getting the correct NID from URL

According to what i can see from the screen shots, you didn't specify your relationship entity on advanced menu. If I were you, I would pick a entity reference, then i would pick a content contextual filters with Nid. Otherwise there is no way that block is gonna understand what the relationship is. Please update us your work. This is a very sensitive topic of drupal. Kind regards


New role assigned on user account update

Just found a way to do it without coding. Works well so far.

EVENT: After updating an existing user account

CONDITIONS:

1) Data >> List contains item - LIST: "account-unchanged:roles", ITEM: "Role A" (Check NEGATE)

AND

2) Data >> List contains item - LIST: "account:roles", ITEM: "Role A"

ACTION: Send mail

Ref: http://goo.gl/Pcz2wN


Trying to display or render values from links field within paragraph field base on its current language

Below is some general purpose code I wrote to solve this problem across a lot of code.  It can take either a standard /node/## path or an alias and convert it to the desired language.  It assumes you are using prefixed language URLs and 'en' is the default language. If FL URL can not be found, the same URL is returned.

/**
 * Utility function to take a standard drupal path or alias and convert to the specified language alias path.
 *
 * @param string $path Root relative standard path, e.g. /node/### or english alias, e.g. /my/view and the like.
 * @param string $langCode  Language code for the resulting url. If not specified current language is used.
 * @param boolean $testPrefix If true, the input URL will be tested to see if the language prefix is already there.
 * @return string
 */
function my_i18n_language_url( $path, $langCode=NULL, $testPrefix=FALSE ) {
  if ( empty($langCode) ) {
    $langCode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  }
  // Optional check to see if url already has language prefix.
  if ( $testPrefix ) {
    $languages = \Drupal::languageManager()->getLanguages();
    foreach ( $languages as $code => $lang ) {
      if ( strpos($path, "/{$code}/") === 0 ) {
        return $path;
      }
    }
  }
  // If in alias format convert to node/### format.
  if ( strpos($path, "/node/") !== 0 ) {
    $url = \Drupal::service('path.alias_manager')->getPathByAlias($path,'en');
    if ( $url == $path ) {
      // Maybe it's a view
      try {
        $url = \Drupal::service('path.alias_manager')->getAliasByPath($path, $langCode);
        if ( $url == $path ) {
          return $path;
        }
      }
      catch ( Exception $e ) {
        watchdog_exception('my_i18n', $e );
        return $path;
      }
    }
    $path = $url;
  }
  $url = $path;
  try {
     $url = \Drupal::service('path.alias_manager')->getAliasByPath($path, $langCode);
  }
  catch ( Exception $e ) {
    watchdog_exception('my_i18n', $e );
    return $path;
  }
  $url = my_i18n_language_prefix($langCode) . $url;
  return $url;
}

/**
 * Utility function to get a language prefix based on the current page language.
 *
 * @param string $langCode  Optional - defaults to current language
 * @return string
 */
function my_i18n_language_prefix( $langCode=NULL) {
  $manager =  \Drupal::languageManager();
  $default_lang = $manager->getDefaultLanguage()->getId();
  if ( empty($langCode) ) {
    $langCode = $manager->getCurrentLanguage()->getId();
  }
  if ( $langCode == $default_lang ) {
    return "";
  }
  return "/{$langCode}";
}


Problem with IF command in comment.html.twig

Use the comment entity to get the raw field value instead:

{% if comment.field_points.value == 5 %}
   *****
{% elseif comment.field_points.value == 4 %}
   ****

...

{% endif %}

This doesn't work with {{ content }}, because it contains a build array to render the fields.


Feeds for the module information of drupal.org

The official Drupal.org feeds available can be found at https://www.drupal.org/api/rss.  There is a feed for projects, but to get the information about releases you'll need to parse the JSON of an API request like
https://www.drupal.org/api-d7/node.json?field_project_machine_name=media

You can read more about the APIs available and how to use them at https://www.drupal.org/api

UPDATE:  If the goal is to a list of all projects and pull their releases, this cannot be done with just an official "feed".  It requires scraping the list of projects from Drupal.org and writing code to get the release into, but the code to do that already exists.  Lin Clark's ScraperWiki code still works (http://lin-clark.com/blog/2011/07/22/writing-scripts-clone-contrib-projects-gitdrupalorg/).  Export the scrapper output as SQL, import that into a custom table, write some code to loop those the projects calling Drupal.org's API to get the release information you are looking for, and save that response.  Not as easy as just pulling the information from a feed provided by Drupal.org, but it can be done.


How can I add a sub-array structure in my results? $_POST

I managed to solve my own problem. It was a problem with the #tree.
I have to set #tree in the parents to true..

So if you want an array with the following structure:

array {
    ["parent"]=>
     array(4) {
        [1]=>
        array(9) {
          [1]=>
          int(1)
          [2]=>
          int(0)
          [3]=>
          int(0)
          [4]=>
          int(0)
          [5]=>
          int(0)
          [6]=>
          int(0)
          [7]=>
          int(0)
          [8]=>
          int(0)
          [9]=>
          int(0)
        }
    }
}

I had to configure #tree for the parents (2 here), and not only for the children

['parent']['#tree'] = true
['parent'][1]['#tree'] = true

I figured it out after trying and reading https://www.drupal.org/node/48643 (Archived, but it worked for me ;) )


How to get current product id from custom block?

Use this below code to get product ID

$product_id = \Drupal::routeMatch()->getParameter('commerce_product')->id();

and then return the value in custom block,

return [
      '#product_id' =>  $product_id,
    ];


How to change query target when using EntityFieldQuery

This is currently not possible (Drupal 7.43). EntityFieldQuery doesn't have any options for using a slave/replica database, nor does the module that actually executes the query, which is field_sql_storage.module in field_sql_storage_field_storage_query().

Ultimately that function calls db_select():

$select_query = db_select($tablename, $table_alias);

But it doesn't pass the 3rd parameter which is where the slave database would be targeted, so it will always use the master. It's also not possible to alter the query to add new options, as the Query->queryOptions property is protected.

I filed an issue against Drupal core, if it gets fixed the solution will be posted there: https://www.drupal.org/node/2714021


Check when the last time someone visited a specific node

The Statistics module that is part of Drupal already get that information. Its hook_exit() implementation contains the following code.

  if (variable_get('statistics_enable_access_log', 0)) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

    // For anonymous users unicode.inc will not have been loaded.
    include_once DRUPAL_ROOT . '/includes/unicode.inc';
    // Log this page access.
    db_insert('accesslog')
      ->fields(array(
      'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
      'path' => truncate_utf8($_GET['q'], 255),
      'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
      'hostname' => ip_address(),
      'uid' => $user->uid,
      'sid' => session_id(),
      'timer' => (int) timer_read('page'),
      'timestamp' => REQUEST_TIME,
    ))
      ->execute();
  }

The data contained in that table are reset after 72 hours. statistics_cron() contains the following code.

  // Clean up expired access logs (if applicable).
  if (variable_get('statistics_flush_accesslog_timer', 259200) > 0) {
    db_delete('accesslog')
      ->condition('timestamp', REQUEST_TIME - variable_get('statistics_flush_accesslog_timer', 259200), '<')
      ->execute();
  }

The Statistics module has a setting page (admin/config/system/statistics) that allows you to decide when the access logs are discarded; you can choose to discard then when they are older than 1 week.

The Views module has code to expose in a view the data saved from the Statistics module; you can add a field to expose the number of times a node is viewed in a view.

Alternatively, you can create a custom module basing on the Statistics module's code. In this case, you would need to implement the code for integration with the Views module, if you need it.

As side note, hook_exit() is probably going to be removed from Drupal 8; if you are using it in a Drupal 7 module, you will need to change your code when porting it to Drupal 8.


How can I allow a user to send private messages but prevent other users from sending that user a private message?

There are two ways to do this.

The pm_block_user module has settings that allow for role-based configurations for who is allowed to write whom. However, it is only possible to add positive rules. Meaning, you wold need to add all your users into a normal role that the system user is not part of and then allow users of that role to write users of that role.
Implement hook_privatemsg_block_message() and block the system user id.

You're welcome to provide option two as a patch in the main module (e.g. allow to choose a system user whom you can't write/reply and is maybe also themed differently). This is an often requested feature.


default.services.yml is just basically just documentation/ an example, it's not actually loaded, at least not by default.

To load a services.yml file, it either needs to be named services.yml, or you need to explicitly added to the settings.php file, see example.settings.local.php and how it loads development services.

The redis module also provides implementations for those services, and it does so by providing a separate example.services.yml file that you can either include directly or copy and customize. That definitely works, I wrote and tested it.


How to to check if user has changed the password?

The easiest would be to do this using Rules. Following the next steps, should do the job.

Ensure you have enabled the "PHP filter" on the modules page. This is needed to be able to use PHP code inside Rules.
Create a rule that reacts on the user event "After saving a new user account".
Add a condition of type "Execute custom PHP code" and use the following snippet: return $account_unchanged->pass != $account->pass;
Add your action(s) to send an email notification to the user or anything else that fits your purpose.


Enable placeholder translation for exposed filters

I'll post the solution I worked out just in case someone might need it. Using the hook_form_alter() function:

function YOUR_THEME_form_alter(&$form){
  if($form['#id'] == 'your_form_id'){
    foreach ($form['#info'] as $filter_info) {
        $filter = $filter_info['value'];
        if ($form[$filter]['#type'] == 'field_type' && $filter == 'field_title') {
            $form[$filter]['#attributes']['placeholder'] = t('your_placeholder');
        }
    }
}


How can I attach an existing server image to an image field rather than uploading a new image file?

I think Filefield Sources along with IMCE does what you need.


AJAX: Form API Dependent Drop Down with more options

Not totally sure, but setting $form_state['rebuild'] = TRUE in your submit or validation handler may help here.

  This is the key function for making multi-step forms advance from step
  to step. It is called by drupal_process_form() when all user input
  processing, including calling validation and submission handlers, for
  the request is finished. If a validate or submit handler set
  $form_state['rebuild'] to TRUE, and if other conditions don't preempt
  a rebuild from happening, then this function is called to generate a
  new $form, the next step in the form workflow, to be returned for
  rendering.

https://api.drupal.org/api/drupal/includes!form.inc/function/drupal_rebuild_form/7

Another option would be to replace the entire form on in your AJAX callback. So essentially you'll specify a #prefix and #suffix for the entire form and then use that prefix element id in your $form['dropdown_first/second']['#ajax']['wrapper']. Your callback will look something like this:

function ajax_example_dependent_dropdown_callback($form, $form_state) {
  ...
  return $form;
}


How to render user picture from page.html.twig file

You can either do

{{ node.author_picture.content }}

or

{{ content.author_picture }}


Views is not the right tool to use here, as views is for listing of content.

What you probably want is to use panels to take over the user page and display anything, like a view in it.


How to change programmatically exposed filters in views

For drupal 7 you can use

$view->exposed_input[$key] = $value;

This is

$view->exposed_input['title'] = 'My title is a cat';

For a full example you can try this:

$name = 'name_of_view';
$display = 'page_1';
$alter = array('exposed' =>array('title' => 'title_value'));

$view = views_get_view($name);
$view->init_display($display);
$view->preview=TRUE;
$view->is_cacheable = FALSE;

if(isset($alter['exposed'])){
  foreach($alter['exposed'] as $key => $valor){

     $view->exposed_input[$key] = $valor;

  }
}

$view->pre_execute();
$output = $view->display_handler->preview();
$view->post_execute();

print_r($view->result);

Other way is using the views set_option function

$filters = $view->display_handler->get_option('filters');

foreach($alter['exposed'] as $key => $valor){
   $filters[$key]['value'] = $valor;
   $view->display_handler->set_option('filters', $filters);
}


Luckily just a day before your question this tutorial for year select filter was posted on Drupal planet:

https://www.flocondetoile.fr/blog/filter-content-year-views-drupal-8


What are search_index & search_dataset tables for, can I clean them?

These tables are used by the site's search function, as provided by the core's Search module. They're built from your site's content, and the descriptions in code in search_schema() say:

search_dataset - "Stores items that will be searched"
search_index - "Stores the search index, associating words, items and scores"

Though you can ignore/truncate the contents of these tables to keep your database dumps smaller, they will be recreated during cron runs as your site's content is re-indexed. Beware that rebuild times can be a lengthy if your site has a lot of content.

I've always found the Backup and Migrate module to be much handier than command-line MySQL as tables and/or their contents can be ignored, plus do scheduled dumps and  have various export/import profiles.


AFAIK there is no easy way of getting a cached page as though the user was anonymous.

The easiest solution is probably to cache the elements of the front page, but that's hard to say without knowing how it's built and what's elements it consist of.


How do I initially show 3 blank fields on a form when cardinality is unlimited?

You can alter your form to add your proposed blank fields , to do that you need to implement hook_form_alter in your module and inside you would have :

if (empty($form_state['field_counter'])) {
  $form_state['field_counter'] = 3;
}
else if($form_state['field_counter'] < 3)
{
  $form_state['field_counter'] = 3;
}
for ($i = 0; $i < $form_state['field_counter']; $i++) {
  $form['YOUR FIELD NAME'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Your Lable'),
  );
}


Found it in $context['form']['#parents']. This is an array that contains the keys of the parent widget. In my case it looked like

[ 0 => 'field_pagebuilder',
  1 => ___PARENT_INDEX___,
  2 => 'subform',
]

which allowed me to generate my CSS selector for the states API:

$deltaParent = $context['form']['#parents'][1];


Try using:

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

Edit:
To further the above, if you want to see the action links/titles/tabs you can print those by:

<?php if ($title): ?>

 <?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>
      <?php if ($tabs): ?>

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

      <?php endif; ?>
      <?php print render($page['help']); ?>
      <?php if ($action_links): ?>

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

      <?php endif; ?>
      <?php print render($page['content']); ?>
      <?php /*?><?php print $feed_icons; ?><?php */?>


If you write down this piece of code outside any hook or function, it is normal that it loops because the user is always "not logged in".

However, if you've created your "page" through the admin menu system, as Parvind said, you can use Menu Access module or use that piece of code:

function hook_node_view($node, $view_mode) {
  if($node->nid == 'yournodeid" && $view_mode == 'full') {
    if (!user_is_logged_in())
      drupal_goto('user/login');
  }
}

If you've created the node programmatically (hook_menu()), you can use access argument like this:

$items['testpage'] = array(
  'title' => 'Authenticated users',
  'page callback' => 'test_func',
  'description' => 'This page is accessible to authenticated users only',
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK,
);


On my site, all I have to do to make this work is to enable the permission  "Edit own comments" for the role, and set the time limit.  If you've done this, it should work.  This is how it looks like when working:

The only thing I can suggest is that you go over your settings again.


It is not possible to translate the menu uri itself. If you want different menu links per language you need to create a unique menu per language, and use block visibility settings to limit each menu block to its respective language.

See this Drupal 8 multilingual hack for a step by step guide: build unique menus per languages


How to use access callback and access arguments to restrict access by role?

The callback is, well the callback; the function that will be run to determine access for the path.

The arguments are the arguments provided to that function for context. They can be static, or come from parts of the URL (not query params).

What you need to do is instead of TRUE, provide the name of a function which determines whether the current user is a "property owner", and return TRUE or FALSE from that function to allow/deny access respectively.

The common way to achieve that for role-based access is to use hook_permission to provide your own permission to the system, call it "access top secret area" or whatever, grant the new permission to the property owner role through the UI, and change the access arguments to an array containing that new role.

The default access callback is user_access, so it will have the effect of running

$access = user_access('access top secret data');

Obviously if you need more advanced logic, e.g. to determine that a property owner is accessing only data on a property they actually own, a custom callback will make more sense.


Accessible Checkboxes Using Drupal's Form API

Try changing your code to the following, no need for the call to form_process_checkboxes.

function my_module_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'myform':
    $block['content'] = drupal_get_form('mymodule_form');
    break;
  }
  return $block;
}

function mymodule_form() {

  $form = array();
  $form['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    '#attributes' => array(
      'name' => 'example-checkboxes[]'
    )
  );

  dsm($form);

  return $form;

}


Nothing helped in our case, but running the following command:

drush sql-query "truncate cache_update"


Can error messages be avoided for custom modules in the Update manager?

Using the tip that junedkazi gave (please up-vote his answer too if this helps you!), I add this line to the .module file for my feature module:

include_once('<my_module>.exclude_from_update_list.inc');

And in the file <my_module>.exclude_from_update_list.inc:

<?php
/**
 * @file
 * <my_module>.exclude_from_update_list.inc
 */

/**
 * Implements hook_update_projects_alter().
 */

function <my_module>_update_projects_alter(&$projects) {
  unset($projects['<my_module>']);
}

And it worked perfectly.  I took the precaution of backing up the database first, and of course I did this in a non-production environment.

This is all pretty obvious once you know about that hook, but I'm putting the code here for sake of a more complete reference, hoping it speeds things up for someone else.


With Drush, what's the correct procedure to install Commerce Kickstart, Drupal, and the sample store data as a new site?

Commerce Kickstart differs from the standard core installation profile, by having extra installation steps. These steps are illustrated in the offical Commerce installation docs - they ask questions about store features and whether or not to install the sample store data.

Installation via drush does indeed work, however it does NOT offer these extra-step choices to the user. Instead it assumes you want the sample store.

So installation via drush is straight-forward. Assuming you have downloaded and unpacked the distribution archive file, just cd to the Drupal root, and run drush site-install commerce_kickstart.

Take some time to review the options described by drush help site-install. Most likely you will need to pass in a few more options, such as database credentials. A typical installation command will look something like this:

drush site-install commerce_kickstart --account-pass=admin --account-name=admin --db-url=mysql://root:pass@localhost/db_name --notify

Note that the Commerce Kickstart takes a lot more time than the standard core install profile. It sets up over 100 modules, several content/product types, and imports the sample store data. drush site-install will tell you "This takes a few seconds...", but it took 10 minutes on my machine :-)


Paste field content directly to node.html.twig?

{{ node.field_test.value }} works in node.html.twig for "normal" fields, not for taxonomy fields.


How to get all parent nodes from a menu item?

I don't think there's anything as simple as $menuLinkContent->getTargetEntity()->getType(). Though that would be nice and I'd love for someone to correct me on that.

Below I wrote a method that loads the menu, loops through the menulink objects, grabs the url objects from them and loads the nodes based on the path of the url object. Once it has the node it gets the content type from it. I doubt it's better performance wise, but it does take advantage of more of the out of the box stuff and might be a bit easier to read.

$menu_tree = \Drupal::menuTree();
$menu = reset(\Drupal::entityTypeManager()->getStorage('menu')->loadByProperties(['uuid' => $uuid]));
$menu_parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu->id());
$menu_tree_elements = $menu_tree->load($menu->id());

foreach($menu_tree_elements as $menu_tree_element){
    $path = $menu_tree_element->link->getUrlObject()->toString();
    $node = self::nodeFromPath($path);
    $contentType = $node->getType();
    foreach($menu_tree_elements->subtree as $subtree_menu_element){
        $path = $subtree_menu_element->link->getUrlObject()->toString();
        $node = self::nodeFromPath($path);
        $contentType = $node->getType();
    }
}

function nodeFromPath($path){
        $path = \Drupal::service('path.alias_manager')
            ->getPathByAlias($path);
        preg_match('/node\/(\d+)/', $path, $matches)) {
        $nid = $matches[1];
        return Node::load($nid);
}


How to update relative image paths on domain migration? (Incorrectly generates previous)

If your CSS file and "images" folder are in "mytheme" folder, the CSS string should be:

background-image: url(../images/homepagenew4.jpg);


I figured it out by myself now. In case someone runs into the same problem:
Updating the database directly avoids the problem of rehashing:

$query = \Drupal::database()->update('users_field_data')->fields([
    'pass' =>$prefixed_password_hash,
])->condition('uid',$user->id());

$query->execute();


A good markdown that supports syntax highlighting like SE sites?

There is the Markdown filter module, which uses the files you can download from http://daringfireball.net/projects/markdown.

  Provides Markdown filter integration for Drupal input formats. The Markdown syntax is designed to co-exist with HTML, so you can set up input formats with both HTML and Markdown support. It is also meant to be as human-readable as possible when left as "source".

  This module is a continuation of the Markdown with Smartypants module, and only includes Markdown support to simplify configuration. It is now suggested that you use Typogrify module if you are interested in Smartypants support. Also note, that if you use the GeSHI filter for code syntax highlighting, arrange this filter after that one.

There are versions for both Drupal 6 and Drupal 7. In the case you are using Drupal 6 for your site, you would not need to change module when updating to Drupal 7.


No, hook_nodeapi op=presave is the wrong place for that.

You should instead use hook_nodeapi op=validate

  "validate": The user has just finished editing the node and is trying
  to preview or submit it. This hook can be used to check the node data.
  Errors should be set with form_set_error().

https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_nodeapi/6

However, it won't fail silently, instead showing an error on the node form.


Contextual view -> entity reference target ID

You need to add the proper Context to the variant.

Then you complete the setup.

And lastly you select it in the panel settings for the Contextual view:


Prevent Drupal from timing out during a large node export?

There is (obviously ;)) no setting to make Drupal faster, so you're only chance is to allow it to run longer.

You will only be able to change these settings if you are running your own server. If so, then see http://drupal.org/node/207036 and http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time.

You could also ask your hoster nicely to increase these settings for you, but that might not happen as these settings are usually setfor good reasons (On shared hosting servers are usually tons of users, so hosters want to prevent that one of those users is taking up too many ressources from others..)


"Languages" not found in Admin/Configuration

I found a permission named Administer languages, I make some test with it and I can reproduce your issue. Go to YOUR_SITE/admin/people/permissions and search under the Locale section the Administer languages permission and give the permission to your user.


Try to change your development.services.yml to following. this  works for me correctly(I hope works for you too) .

services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

# Enable Twig debugging.
parameters:
 twig.config:
   debug: true
   auto_reload: true
   cache: false

also  this article about setting up debugging on Drupal 8 is very good for future visitors of this question.


Send an alternative email to an anonymous user who placed an order

You could look to the Rules module to accomplish this, though a lot depends on how you are managing orders (Commerce module?).

If using Rules you could set conditions for user role to determine which email they get.


if you use the form API to build your form, then you can use the ajax form API.

In the field you want to trigger ajax method, use this :

$form['test'] = [
  '#type' => 'textfield',
  '#title' => 'A Textfield',
  '#required' => TRUE,
  '#ajax' => [
    'callback' => '::ajaxTest',
    'event' => 'keyup',
    'wrapper' => 'edit-output',
    'progress' => [
      'type' => 'throbber',
      'message' => t('Verifying entry...'),
    ],
  ],
];

Then create a ajaxTest function in your Form :

public function ajaxTest(array &$form, FormStateInterface $form_state) : array {
  // you can use the $form_state here to get values of all your fields
  $my_value = $form_state->getValue('my_field');
  // Make your logic code here
  $new_val = 'foo';
}

And then just add a AjaxCommand to your ajaxTest function :

$response = new AjaxResponse();
$response->addCommand(new InvokeCommand('#my_id_to_change', 'val', $new_val));
return $response;

You can find all those in the Form and AJAX API here https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.5.x, regards.


Rewrite the image markup from specific image field

I assume that you are using Drupal 7.

Short Answer

Implements template_preprocess_field() and overrides theme_image().

/**
 * Implements template_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];

  if ($element['#field_name'] === 'field_image') {
    foreach (element_children($element) as $key) {
      $item = &$element[$key]['#item'];

      $src = file_create_url($item['uri']);
      unset($item['uri']);
      $item['attributes']['data-lazy'] = $src;
      $item['attributes']['class'] = array('lazyload');

      $element['#items'][$key] = $item;
      $variables['items'][$key]['#item'] = $item;
    }
  }
}

/**
 * Overrides theme_image().
 */
function mytheme_image($variables) {
  $attributes = $variables['attributes'];

  if (!empty($variables['path']) || !isset($attributes['data-lazy')) {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

Long Answer

By implementing template_preprocess_field(), you can alter the theme variables and also the theme function for a field.

Example code:

/**
 * Implements template_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];

  if ($element['#field_name'] === 'field_image') {
    foreach (element_children($element) as $key) {
      $item = &$element[$key]['#item'];

      $src = file_create_url($item['uri']);
      unset($item['uri']);
      $item['attributes']['data-lazy'] = $src;
      $item['attributes']['class'] = array('lazyload');

      $element['#items'][$key] = $item;
      $variables['items'][$key]['#item'] = $item;
    }
  }
}

Remember to change field_image to the field name you defined.

It is the structure of $variables:

$variables['items'][0]['#item'] is a typical usage of theme function in render array. The code above has done a couple of things:

unset uri, which is used to format the attribute src in theme_image()
construct image path and assign it to the attribute data-lazy
add lazyload to class
synchronise the item array to different location of $variable

The last point is a bit weird, but there are 3 different location always store the same item array. They are

$variables['element'][0]['#item']
$variables['element']['#items'][0]
$variables['items'][0]['#item']

Theoretically, $variables['items'][0]['#item'] is the only one be used in theme function, But, in my opinion, it is better to change them at the same time for preventing any potential issue in future. (Maybe someone can provide more suggestion here?)

The last but not the least, you have to override the theme_image(). It is a global change but won't affect too much.

/**
 * Overrides theme_image().
 */
function mytheme_image($variables) {
  $attributes = $variables['attributes'];

  if (!empty($variables['path']) || !isset($attributes['data-lazy')) {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}


Comment migration working? (D5 --> D7) View displaying comments not

Things I learned today, yes it took me all day, and I learned a lot. Like to test your assumptions. Test them early and verify the problem you're trying to solve in fact is in the place you are looking.

My debacle outlined above was completely separate from all the comment tables. The maddening part, was I narrowed it down to the comment bodies not appearing (or so I thought) because I was using a view to display the author's name, followed by the comment. Where this view pulled the author name from was the comment table, where the author's name wasn't was in the users table, I hadn't run the user migration in a couple weeks & enough users had joined & commented that, well, you get the picture.

Also contributing to the madness was the lack of information in the error messages, I kept getting malformed entity exceptions, which is probably because I was using views to display the comments.

Something else I noticed, that a comment's initial changed time is a few seconds before it's created time, not sure that's a bug, but definitely a quirk.


Commerce coupon only one coupon active at a time

My solution is as follows.
1. Check if entity created is a coupon and that coupon type is the one im checking using hook_entity_insert and hook_entity_update
2. Check if coupon changed or inserted has been put active if yes then load all other coupons of right type and turn them inactive


It looks like there are possibily nightmares trying to get Panelizer or IPE and Workbench Moderation to play nice together. I've used both seperately, but not together on 1 site when using Moderation.

See this issue thread for Panelizer and Moderation for possible solutions:

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


How can I dynamically add URL or taxonomy to body class

The answer provided by mradcliffe was what I needed. One improvement that will yield a css-friendly class name is to use the Twig |clean_class filter. Here is the code:

In MY_THEME.theme

<?php
function MY_THEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $variables['current_path'] = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
}
?>

In html.html.twig:

{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    current_path ? 'context' ~ current_path|clean_class,
  ]
%}
<body{{ attributes.addClass(body_classes) }}>

Don't forget to clear your cache!


If you have only 12, or some other manageably small number of categories, I would investigate the Flag module.  Just set up flags named to your categories and you're off and running.


You can use getAliasByPath function to get the url alias for a path.

Put the below code in THEME_NAME.theme file.

function THEME_NAME_preprocess_page(&$variables) {
  $variables['url_alias'] = \Drupal::service('path.alias_manager')->getAliasByPath('/node/1');
}

Finally print the url_alias in your page.html.twig file.

{{ url_alias }}


Sounds like you'll need to use the Domain Access module to get this right. This module allows you to run as many affiliated sites as you need from one single Drupal installation, sharing the same database.

I'm using it for another site at the moment, and it works really well.


No, unfortunately, you can't use #ajax because managed_file uses it internally for its own purposes.


Couldn't create a subtheme of a core theme

In Drupal 7 if subtheme is attaching CSS with exact same file name, Drupal thinks you want to override a CSS file. That seems to be the problem for you. So you are overriding the CSS from the Seven theme by attaching style.css in the info file.

Easiest way to get over that problem is to rename your CSS file into something else e.g. seven_sub.style.css.


In Drupal 6, you implement hook_user() to add the extra fields to the registration form implemented by Drupal.

function mymodule_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'register' && $category == 'account') {
    $form['legal_agreement'] = array (
      '#type' => 'fieldset',
      '#title' => t('Legal Agreement')
    );

    $form['legal_agreement']['decision'] = array(
      '#type' => 'radios',
      '#description' => t('By registering at %site-name, I certify that I am over 18, and I have read and accepted the terms and conditions of the privacy policy.', array('%site-name' => variable_get('site_name', 'drupal'))),
      '#default_value' => 0,
      '#options' => array(t('I disagree'), t('I agree'))
    );

    return $form;
  }

  if ($type == 'validate' && $category == 'account') {
    // If the user needs to always agree with the conditions, this is the place to show an error message.
  }
}

If you want to completely replace the registration form used by Drupal with your own, then you need to implement hook_menu_alter().

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_user_register_form');
  }
}

function mymodule_user_register_form() {
  $form = array();

  // Add the form fields for the registration form.

  return $form;
}

In Drupal 7, as you are just adding form fields to an existing form, you need to implement hook_form_FORM_ID_alter() using code similar to the following one:

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  $form['legal_agreement'] = array (
    '#type' => 'fieldset',
    '#title' => t('Legal Agreement')
  );

  $form['legal_agreement']['decision'] = array(
    '#type' => 'radios',
    '#description' => t('By registering at %site-name, I certify that I am over 18, and I have read and accepted the terms and conditions of the privacy policy.', array('%site-name' => variable_get('site_name', 'drupal'))),
    '#default_value' => 0,
    '#options' => array(t('I disagree'), t('I agree'))
  );
}

The variable that contains the form definition is $form, and the hook doesn't need to return any value, as the form that needs to be modified is passed by reference.

This is very similar to the example code reported in the documentation page for hook_form_FORM_ID_alter(), which uses the following code:

  // Modification for the form with the given form ID goes here. For example, if
  // FORM_ID is "user_register_form" this code would run only on the user
  // registration form.

  // Add a checkbox to registration form about agreeing to terms of use.
  $form['terms_of_use'] = array(
    '#type' => 'checkbox',
    '#title' => t("I agree with the website's terms and conditions."),
    '#required' => TRUE,
  );

If you want to completely replace the registration form used by Drupal with your own, then you need to implement hook_menu_alter().

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_user_register_form');
  }
}

function mymodule_user_register_form($form, &$form_state) {
  // Add the form fields for the registration form; the variable containing it is $form.

  return $form;
}

To notice that in the Drupal code, the form builder receives $form as argument. The common error when porting code from Drupal 6 to Drupal 7 is to still have $form = array() at the beginning of the form builder function.
In both the cases, when you implement hook_menu_alter(), your module needs to handle all the registration process.


Issue while modifying and importing the manually content type data

Install Universally Unique IDentifier and use it as GUID.it is not required you create GUID field in most of time Nid is good choice  as GUID mapper.

Universally Unique IDentifier Description :

  This module provides an API for adding universally unique identifiers
  (UUID) to Drupal objects, most notably entities. Features in Drupal 7
  version Automatic UUID generation

  UUIDs will be generated for all core entities. An API is provided for
  other modules to enable support for custom entities. UUID API for
  entities, properties and fields

  With this unified API you can load entities with entity_uuid_load() so
  that all supported properties and fields are made with UUID
  references. You can also save entities formatted this way with
  entity_uuid_save() (depends on Entity API). Export entities to use as
  default/demo content

  The integration with Features module provides the ability to export
  UUID enabled entities with intact dependencies and references to other
  entities. This functionality depends on Deploy module 7.x-2.0-alpha1
  (soon to be released) and is probably the most robust way for
  installation profiles and distributions to provide demo content!


Best place to add to Drupal.settings from a theme

I have seen that pattern multiple times before, and it seems to be a standard practice.


How to change "Your name" label in comments form?

You can do it in a hook_form_alter() function like you suggest:

function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $label = t('New label');
  if (isset($form['author']['_author'])) {
    $form['author']['_author']['#title'] = $label;
  }
  else {
    $form['author']['name']['#title'] = $label;
  }
}


Strange behavior: Extra css classes are NOT merged with the 'Search Block' form tag classes but with those of BLOCK wrapping the form tag

It's fairly straight forward PHP mistake $form['#attributes']['class'] is an array of classes

And by doing $form['#attributes']['class'] = 'form-inline'; you're saying forget whatever $form['#attributes']['class'] was before its now a string that contains 'form-inline'. So you're changing the variable from an array to a string.

Long story short you should be adding your class to the existing array with:

 $form['#attributes']['class'][] = 'form-inline';

Note the [] after ['class']

That explains why you have no classes coming out on your form. The issue about the classes on your outer div isn't related to this code and you must have something else going on too. Perhaps a block alter hook


Custom Key Value fields in a content type

I realise I'm answering my own question here but I've done some digging and come across the TableField module.

Does anyone have any experience with this?

It appears to do something along the lines of DoubleField.


Automatic copy node from Drupal A to Drupal B

I would solve the problem with either of the following

1) Write a 5 minute custom php script that would show the node ids and data value and then update the nodes with data value in the second database with a simple update query on field_data_field_<your-field-name> table based on entity id.

2) Use services 3 module to expose your data and then import that field with put method with only the field you want.


What you are looking for are "theme wrappers" ... this allows you to create a theme function (or tpl) to use to wrap a form element (or any element in a render array).

There is a good write-up here: https://guusvandewal.nl/drupal-blog/theme-wrappers-drupal-forms

Its for drupal 7 but not much has changed with theme wrappers in Drupal 8


How to pass variable from module to other theme

For your needs, you'll need to create a custom module and implement hook_preprocess_html:

function hook_preprocess_html(&$vars) {
  // This is where you do the db query
  $myvar = _get_my_var();

  // After this $myvar will be available in html.tpl.php
  // where you need to print it out
  $vars['myvar'] = $myvar;
}


Programmatically format integer field display

You can do this using the following code:

$drupal_version = (int)$drupal_version; // make sure this is an int
$parts = array();
preg_match('/^(\d{1})(\d{2})(\d+)$/', "$drupal_version", $parts);
array_shift($parts); // get rid of the first element in $parts which is the whole matched string
$formatted_drupal_version = implode($parts, '.');
echo "Drupal version: " . $formatted_drupal_version;

As examples, these integers will turn into the following strings:
7411 => 7.41.1
74110 => 7.41.10

Which means, that this code, will work parsing the provided integer from left to right, and collecting, 1 digit for the major version, 2 digits for the medium version, and all the remaining digits for the minor version.

Hope this helps!

P.S.: You question is a bit misleading, as @No Sssweat says, you cannot format an integer like that. That is why string parsing is the only way to provide you with the desired result.


Assuming that you want to use the same avatar image, just in different sizes, you do not have to duplicate anything.

Being able to display the same image with different styles is the whole point of having different image styles. "Styled" images are created on demand, according to the request. This already works out of the box for normal image files (For example, you can chose a different image style for teaser and default view modes).

The user avatar image can be displayed with different image styles too, the only problem right now is that you can't select the image style when using theme_user_picture(). There is however already a patch for that. And if you're using Views, it should already be possible to choose the image style for the user picture.


I tried %1 in the override title and it worked.


Inline Entity Form - How to change label for the EDIT button and REMOVE button

Try form after build. it may give you solution.

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'CONTENTTYPE_node_form') {
    /*
    * Modify the Add node button when it's the first one
    */
    $form['MY_FIELD']['und']['form']['actions']['ief_add_save']['#value'] = t('CUSTOM TEXT');
    /*
    * Modify the Add node button when there is at least one node
    */
    $form['MY_FIELD']['und']['actions']['ief_add']['#value'] = t('CUSTOM TEXT');
    $form['#after_build'][] = 'yourmodulename_after_build'; //Calls function
  }
}

Use dpm($form) or print_r($form) to find the edit button id


How to write a module that changes user role when account is created

Don't re-invent the wheel!  https://drupal.org/project/registration_role

Also I think you want to look at user_presave,  rather than user_insert.  https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_presave/7


Configuring Lightbox2 to Pop-Up Images embedded in nodes

Colorbox and lightbox are the famous modules for this, once you done with all configuration, go to Content type Manage display settings tab and render the image in lightbox. it will automatically shows up in the popup.
http://i.imgur.com/KA69Iqu.png


How to render all the contents of a view in a custom module?

I've always used views_embed_view to do this. The first parameter is the machine name of your view, the second is the display id. Example:

$view_rose_output = views_embed_view('myblock_block', 'rose');
$view_lily_output = views_embed_view('myblock_block', 'lily').

If your view takes any arguments you can pass that in to the views_embed_view after the first two arguments.

Note that views_embed_view returns the rendered html of the view. If this is what you want, great! Otherwise, I've used the views_post_render hook to alter the output. The function header looks like this:

HOOK_views_post_render(&$view, &$output, &$cache)

where $output is the rendered html, and $view gives you the view object.


Read field value and pass it to section style atributes only for node page

$color = preg_replace("/#/i", "", $bg_color);
$vars['classes_array'][] = $color;
 $vars['style'] = "style='background-color:$bg_color'";


You need to (really should) use a render array.  You can use theme_image_style:

// first, make a render array for your image, as a thumbnail...
$image_ra = array(
    '#theme' => 'image_style',
    '#path' => _drupal_wall_user_profile_picture($friend_id),
    '#alt' => 'Some alt value',
    '#title' => 'Some image title value',
    '#style' => 'thumbnail'
);

// now make your link render array...
$ra = array(
    '#theme' => 'link',
    '#text' => drupal_render($image_ra),
    '#path' => $base_url . '/user/' . $friend_id,
    '#options' => array(
        'html' => TRUE,      // this says the #text value is HTML markup
    )
);

// now you can render your image link into markup...
$image_markup = drupal_render($ra);

I took the long way to show you that you need to handle the image first, and then render it as #text in the link.  I also did this to make the case that you really, really, really, really should use render arrays and stay away from writing the HTML.  Let Drupal do that work.  Just build a render array, pass it to drupal_render, and be done with it.


Hybridauth facebook and google login not works in live server

Please try out the below possibilities.

If you have any Redirect rule enabled, please disable it. OR
Set Redirect after login path in HybridAuth configuration. OR
May be javascript error was stopping the process. You should also uncheck "Aggregate Javascript files" under Performance to actually see what's going on more precisely.

I Hope it will solve your problem.


How to identify which Rule is triggered?

Below are 2 approaches that might work ...

Approach 1

Create a NEW Rules Component like so:

It uses some "identifier" as a parameter, of type something like "text" or "integer".
All this component does, is to also perform your custom action.

For each of your existing rules, rework that Rules Action like so:

Replace it by performing the new Rules Component.
For the (required) parameter of the Rules Component, use some unique value (just an integer, or maybe the machine name of the rule?), so that when the Rules Component is executing, you do know which rule it was that triggered the execution of the Rules Component.

Approach 2

Update each of your rules to contain and pass in a unique identifier. You can just do that by adding another parameter to the existing Rules Action in your rules_action_info hook. Though you'd have to update all your existing rules to make that work.


In the database that contains entity_id (field_revision_field_user_profile_phone in this case) there is a column named entity_type. That would be a name of the table which contains both uid and entity_id.


How to show an alert when user navigates to another page without filling the form?

Below are a few modules to consider (quotes included are from the project pages of these modules), sorted by "my recommended one first". It'll depend on your specific requirements which one would fit best for you.

Node Edit Protection (either for D6 or D7).

  A very simple JavaScript based protection that will alert a user if they are navigating away from a modified Node Edit form without saving. It uses a standard JavaScript confirm dialog that allows the user to either continue what they were doing, or cancel the move allowing them the opportunity to save. It marks the form as dirty by using the blur event of the node fields.

SaveGuard (either for D6 or D7).

  ... adds javascript which detects if a form had been modified, and if it has, uses the onBeforeUnload event to pop up a warning to the user if they attempt to navigate away from the page without saving their changes. This works for Firefox, IE, and Safari, but not Opera.

Dirty Forms (only an official release for D6, though for D7 there seems to be a trustworthy patch available also).

  ... provides a javascript behavior that checks forms before users leave the page, warning them if they are about to loose changes and providing an option to remain on the page.

  ... The module provides a configuration form that allows setting up a list of forms that should be excluded from the dirtyForms behavior.


How to run jquery codes before and after ajax call?

/**
 * Special Effects AJAX framework command.
 */
Drupal.ajax.prototype.commands.nameOfCommand =  function(ajax, response, status) {
  alert("Hello I'm Maged Eladawy...")  ; // this will be executed after the ajax call
}

More details


How to change term reference field according to role?

All you need to do is create separate fields for respective roles. Use Field permissions module. Or if you want to have role wise access like from editor -> moderator -> pulisher etc. Use workfolw module.


Well I did this in a slightly different way. By using hook_preprocess_content_field(), I search through all of the fields in a node and do a str_replace() on those items. This does solve my problem but I'm open to a more elegant solution.

function MODULE_preprocess_content_field(&$variables) {

  for ($i=0; $i < count($variables['items']); $i++) {
    $searchfor = variable_get('file_directory_path') . '/special_folder';
    $replacewh = 'portfolio/asset';
    $variables['items'][$i]['filepath'] = str_replace($searchfor, $replacewh, $variables['items'][$i]['filepath']);
    $variables['items'][$i]['view'] = str_replace($searchfor, $replacewh, $variables['items'][$i]['view']);
  }
}

Side note: The path portfolio/asset is part of this same module and defined in hook_menu. I would have preferred to have this done with a field formatter in the above code, but I've got to move on.


If your videos come with some kind of embed code e.g. Youtube of Vimeo then you could embed them into Notebook pages in OA. This would make them visible only to the select users in that group.


Edited my answer since my original answer referred to dev code.

The following simple module works with Drupal 7.34 and the current stable version of synonyms (7.x-1.2) and successfully matches a synonym to a taxonomy term.

synonyms_test.module:

function synonyms_test_menu() {
  $menu['test-synonyms'] = array(
    'page callback' => 'synonyms_test_page',
    'access callback' => TRUE,
  );

  return $menu;
}

function synonyms_test_page() {
  $vocabulary_name = 'tags';
  $output = '
Assuming you have a taxonomy with machine name "tags" and that '
            . 'taxonomy has a term named "first term" and that term has a '
            . 'synonym "syn one", this test will produce these results:
';
  $test_terms = array('first term', 'bogus term', 'syn one');
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  foreach($test_terms as $test_term) {
    $output .= 'Testing "' . $test_term . '"
';
    $matched_terms = taxonomy_get_term_by_name($test_term, $vocabulary->machine_name);
    if(empty($matched_terms)) {
      $output .= 'Not an existing taxonomy term.';
    } else {
      $output .= 'Is an existing taxonomy term.';
    }
    $output .= '

';
    $matched_synonym = synonyms_get_term_by_synonym($test_term, $vocabulary);
    if(empty($matched_synonym)) {
      $output .= 'Not an existing synonym.';
    }
    else {
      $output .= 'Is an existing synonym, for tid ' . $matched_synonym;
    }
    $output .= '
=========

';
  }
  return $output;
}

* Original answer below *

This is the function you're looking for (from synonyms.module):

/**
 * Returns the term objects that have the given string as a synonym.
 *
 * @param $synonym
 *  A string containing the synonym to search for.
 * @param $vocabulary
 *  (optional) The machine name of the vocabulary in which to search for.

 * @return
 *  An array of term objects containing that synonym.
 */
function synonyms_root_terms_get($synonym, $vocabulary = NULL) {
  $tids = synonyms_root_tids_get($synonym, $vocabulary);

  return taxonomy_term_load_multiple($tids);
}

So if your $matched_terms is empty, try something like:

$matched_synonyms = synonyms_root_terms_get($term_name, $vocabulary->machine_name);
if(empty($matched_synonyms)) {
  // ...now create your new term
}
else {
  $term = array_shift($matched_synonyms);
}


How to display the values after submit in drupal 7

You can use the function hook_form_FORM_ID_alter to do that.

Just replace the FORM_ID with the ID of your form.
Lets say the id of the form is my_custom_form, then the values could be printed as,

function MODULE_form_my_custom_form_alter(&$form, &$form_state, $form_id){
  //add a new function(submit handler) on submit button.
  $form['#submit'][] = 'new_submit_function';
}

function new_submit_function(&$form, &form_state) {
  // the $form_state['values'] array contains all the
  // values from the fields of the current form stored in it
  drupal_set_message("name : " . $form_state['values']['name']);
  drupal_set_message("phone : " . $form_state['values']['phone']);
  //and so on.
  //the message will be displayed on the page after form submit
}

If you are not sure how to find the id of the form, then use hook_form_alter to do that, e.g.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);
}

this would print the form id of every form you are on, so that you can use the id of the form you wish to change and perform a hook_form_FORM_ID_alter to change anything you wish :-)


In Drupal 7 Views what is the php code to validate a field against a contextual filter argument?

Below is a code sample of my contextual filter validation code for drupal 7 views 3 validation.

My view contains a page display with the following path set: blog/%/%/%

Here is a sample path argument of what I'm trying to accomplish:
Path URL: blog/7/node-title/taxonomy-name

if ( is_numeric(arg(1)) && is_string(arg(3)) ) {
//check to make sure arg 1 is text and arg 2 is a string

  $node = node_load(arg(1));
//load the node

  $terms = taxonomy_get_term_by_name(arg(3));
//get the terms array and TID from arg 3.

  if (!empty($terms)) {
    $first_term = array_shift($terms);
    foreach($node->field_repair_states_region['und'] as $x => $y) {
      if( $y['tid'] == $first_term->tid ) { return TRUE; }
//make sure the TID matches the TID to the node.

    }
  }
}

Screenshot of Validation Page: http://prntscr.com/1dcl4v

Screenshot of View: http://prntscr.com/1dclly


How to disable Create new revision option in a node programmatically

Code you have mentioned in your question solves the problem of create new revision or just update with out a new revision when a node is updated programatically in that particular instance.. It has nothing to do with form option in node edit page...

When you do $node->revision = FALSE;

It is just like telling to node your are updating should be saved as a new revision or not when a node is updated at that particular instance of node_save...

Use hook_form_alter to disable this option in node edit page form..

in your custom module implement MODULE_form_alter and check for node id's you want to disable this option..

$form['revision_information']['#access'] = FALSE;

OR

$form['revision_information']['#disabled'] = TRUE;


Never mind. I figured it out:

<?php
drupal_add_js('http://code.jquery.com/jquery-1.9.1.js','external');
drupal_add_js('http://code.jquery.com/ui/1.10.1/jquery-ui.js','external');
drupal_add_js('jQuery(document).ready(function() {

jQuery(document).mousemove(function(e) {

if (e.pageY<=5) {
        jQuery("#dialog").dialog("open");
}
});

    jQuery("#dialog").dialog({
        autoOpen: false,
        position: "center",
        title: "         ",
        draggable: true,
        width: 850,
        height: 700,
        resizable: false,
        modal: true,
    });

});', 'inline');
?>

<button id="dialog_trigger" style="display:none;">Open The Dialog</button>
<div id="dialog" style="display:none;" title="Dialog Title">
    <iframe frameborder="0" scrolling="yes" width="800" height="650" src="http://www.google.com" style="padding-left:25px;"> </iframe>
</div>


I didn't use any session data, but I have passed sections of Drupal.settings on into the Angular scope when declaring modules. It worked for my case. Here is an example:

angular.module('mypackage.name', []).constant('appConfig', Drupal.settings.custom_module.custom_module_config);

This lived within the libraries folder (attached to pages by Drupal) for 7.x.

But I am not sure that it really matters what backend you have here, this seems like an Angular question. Here is one that might help: https://stackoverflow.com/questions/14957450/maintaining-session-through-angular-js


How do I put a reset button on my view's exposed filters?

In your view configuration go to Advanced -> EXPOSED FORM -> Exposed form style: Basic | settings.

Check 'Include reset button' and save.


re-saving users with default field collection items

This finally worked for me -- may it save someone hours of headaches:

// load the user
$userwrapper = entity_metadata_wrapper('user', $entity);
// apparently you have to create the field collection entity
$fieldCollection = entity_create('field_collection_item', array('field_name' => 'field_yourCollectionName'));
// attach your field collection to the user
$fieldCollection->setHostEntity('user', $entity);
// set the value of one of your fields in your field collection - in my case it's a boolean
$userwrapper->get('field_yourCollectionName')->field_fieldNameInYourCollection->set(0);
// save the entity
$userwrapper->save();


Add execute button to Commerce POS modal?

Instead of a regular "page" callback, implement the page as a form with an action (submit) button. When the form is submitted and validates, the modal will be released courtesy of the way ctools_modal_form_wrapper() works.

POS_Command was not the right way to think about the problem in this case. POS_Button_Command is better suited to a simple, pre-defined operation as in setting the order user from a list of users. I was trying to do a more complex operation in the modal, gather some data from form inputs, then run some commerce commands on the order.

Short answer: The POS_Button_Modal_Page class works for loading a custom modal page. Implement the page as a form, and do the execution code in the form_submit handler instead of using POS_Command.


Select all checkboxes of an entity reference field on creating a node

Ended up resolving this issue with the following code:

(function ($, Drupal) {

  /**
   * Check/Uncheck all checkboxes.
   */
  Drupal.behaviors.selectAll = {
    attach: function (context, settings) {
      $(".form-checkboxes").prepend($('<input type="checkbox" class="form-checkbox shield-select-all"/><label class="option shield-select-all-label"> Select / Deselect all </label>'));
      $(".shield-select-all").on('click', function () {
        let $isChecked = (!$(this).attr('checked'));
        $(this).parent().find('.form-type-checkbox input[type=checkbox]').attr('checked', $isChecked);
        $(this).attr('checked', $isChecked)
      })
    }
  };

})(jQuery, Drupal);


It is always recommended to read the release notes of the new release before updating, to make sure that the update doesn't break some of the current features.

The release notes of Drupal 7.20 mentions:

  The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. (As an example, links that previously pointed to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png will now point to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD_VaCaD.)

You can add the following line to your settings.php to get the images in the site working:

$conf['image_allow_insecure_derivatives'] = TRUE;

but it would be as good as updating the core and not using the updates ;-)

Some useful links from the page:

#1923336: Insert module doesn't work with Drupal
7.20 - contains a working patch to solve this problem.
#1923554: New anti-DoS measure breaks for some file
URIs.
#1923936: Responsive images and styles module doesn't work with
Drupal 7.20

UPDATE:

From the release notes of Drupal 7.21, the update includes fixes for incompatibilities introduced in the Drupal 7.20 security release only. So, it is recommended to update to the latest version i.e. 7.21 to use the security fixes in version 7.20.


Drupal 7 Webform - Find input regardless of fieldset

Unfortunately, to access/modify and form fields in Webform using the form API and hooks, you have to know/include the fieldset hierarchies in the array calls as you observed.

For example:

$form['submitted']["fieldset_machine_name"]["certain_name"]

or

$form['submitted']["outer_fieldset_machine_name"]["inner_fieldset_machine_name"]["certain_name"]

Rather than set a callback function on the form element in your hook_form_alter, you may just need to find the element type with particular machine name using vanilla javascript or jQuery in either:

your theme's assorted javascript files as Drupal behavior
the custom module as a separate script


Change the url parameter 'search_api_views_fulltext' used in views exposed filter

There is a settings "Filter identifier" under More fieldset when you expose a field.


Notify site users based on user account field (e.g. apt number)


Drupal commerce auto login during checkout process

Commerce Checkout Login includes this functionality.

If you just want a rule action to automatically log a user in, then use simongeorge's wonderful sandbox. It provides a rule action that allows you to do just that.


I assume these are links to Ajax enabled route yes ?? i hope so lol any way heres is how ... see this example from a list builder:

$parent['operations']['data']['#links']['clone'] = [
  'title' => $this->t('AJAX!!!'),
  'weight' => 2,
  'url' => Url::fromRoute('someroute_name', ['id' => $entity->id]),
  'attributes'=> [
    'class' => 'use-ajax'
  ]
];

all you need to do is add
'attributes'=> ['class' => 'use-ajax']
more info see my old comment ... https://api.drupal.org/comment/62725#comment-62725


Modify Drupal error handler without killing kitten

Yes, you can use your own error handler instead. You'd put this in your own module - I'm not sure if you would need to put it earlier than hook_init(), though, i.e. in hook_boot(). Check out the Devel module, which has an option for overriding the error handler to make debugging easier.


Why does the core search module not index node titles?

There is a product called Funkywidget

If the title of the node is "Funkywidget" it's searchable by that term. If you want to incorporate search terms that aren't in the node's fields, you should look at more complex search solutions like Apache Solr.

See here: http://api.drupal.org/api/drupal/modules--node--node.module/function/_node_index_node/6
The title is added to the search string that's going in the db.

$text = '<h1>' . check_plain($node->title) . '</h1>' . $node->body;