How to handle non-fatal errors during a batch operation?

Preamble:
The answer given by burnsjermey did help me find the solution. He deserves kudos for pointing me to the correct documentation and this project on github. Both helped a lot, so I've accepted his answer.

However, his answer contains a lot of stuff that has nothing to do with the question. Also, his code examples have bugs that stops them from working. Therefore, I also want to add a self-answer containing only code snippets that are relevant to the question asked.

Self-answer:
First, as pointed out in the API documentation, non-fatal error management should be handled using 'results'. Hence, when we encounter a non-fatal error, we add an error message to the results array:

function mymodule_process_one($file, &$context) {
  if (!is_readable ($file)) {
    $context['results']['error'][] = t('@file is not readable.', array('@file' => $file));
  }
  else {
    $context['results'][] = t('@file processed.', array('@file' => $file));
  }
}

Then, in the finished-callback, we put code that looks for these errors, and prints them out if there are any.

function mymodule_finished($success, $results, $operations) {
  if ($success) {
    if (isset($results['error'])) {
      drupal_set_message(t('There were !count non-fatal error(s):', array(
       '!count' => count($results['error']),
      )), 'error');
      foreach ($results['error'] as $error) {
         drupal_set_message($error, 'error');
      }
    }
    else {
      drupal_set_message(t('No errors.'));
    }
  } else {
    $error_operation = reset($operations);
    drupal_set_message(t('A fatal error occurred'));
  }
}

That's all folks!

PS:
If you want to learn how to handle fatal errors during batch processing, the best answer is the accepted answer to: Can a batch process be stopped.


How to add login form to the Access Denied page?

Option 1: Use the CustomError module

The CustomError module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them. Some more details about its features (from its project page):

  Configurable page title and descriptions.
  There are no author and date/time headers as with normal nodes.
  Any HTML formatted text can be be put in the page body.
  The error pages are themable.
  Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
  Allows custom redirects for 404s.

You should be interested in the part about "Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.".

Option 2: Redirect to user/login using the Rules module

"Adding settings for the 'access denied page' and displaying the 'User login' block on that page" is indeed a solution that should work. However, you could take this a little step further, and enhance the user experience AbitMORE. By using a variation of the approach described in the answer to the question about "How to redirect anonymous users to login page using Rules module?".

To do so, assume the path of the "Default 403" page is set to "no_access" (via /admin/config/system/site-information, near the bottom of that admin page). Then create a rule using the Rules module, with as Event something like "After visiting node 'no_access'". So that the entire rule would look something like so:

Events: After visiting node 'no_access'
Conditions:

User has role(s) - Parameter: User: [site:current-user], Roles: anonymous user
NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user/login

Actions: Page redirect - Parameter: URL: user/login

Should you want to do so, you could even add another Action to also display some (informational) message in the Drupal message area, with something like "You tried to visit a page for which login is required ...".

True, it might require you to enable an extra contributed module (Rules). But, as indicated by its growing popularity also, that module is probably already enabled in mostly any site (similar to the Views module), because there are dozens of use-cases for this module. Just 1 variation of this question: how about enhancing the user experience for "Page not found" in a similar way?

Option 3: Show User login block on dedicated page

Another variation, as an alternative to the Rules "Action" (to redirect to user/login), is to create some designated node, say with a path like "my_login_page_with_login_block". And then combine this with configuring the "User login" block (via admin/structure/block) like so:

Display that block in whatever theme region of your choice.
Use the "configure" link to the right of that User login bloc, to set the "Visibility settings" for "Pages". I.e. change the option for "Show block on specific pages" to "Only the listed pages", and specify the path (my_login_page_with_login_block) within the text box below it. If for some reason you don't want to use a path, then just specify node/nid (nid = id of the node) as the path instead.


How to upload videos and play in Drupal 7?

Here is complete Community Documentation about the Media module.

There is another Drupal Video Setup Using Media and Media Youtube
 tutorial about using the [Media] and Media Youtube modules in a Drupal site.

If still you can't get it to work, then you can also check the tutorial Post YouTube Videos with Media + Media: YouTube (from Drupal's Post Installation forum).

Now choice is up to you in which you feel easy.


You can also add code page.html.twig as well.

For print only date use {{ "now"|date("m/d/Y") }}

More Details

http://twig.sensiolabs.org/doc/2.x/filters/date.html

https://stackoverflow.com/questions/17364206/symfony2-how-can-i-set-twig-dated-f-y-filter-to-output-months-in-swedish


Create an 'active' class for partial url?

There is a module for that - Menu Trail By Path

Menu Trail By Path sets the active-trail on menu items according to the current url.

For example if you are at yoursite.com/blog/category1/article1

Menu Items with these paths will get the active-trail class on them and expand accordingly.

blog
blog/category1
blog/category1/article1

This is particularly useful if you want a lot of nodes to appear as children of certain nodes / taxonomy term / views / referenced nodes / etc, but do not want to add them all to the menu. eg. hundreds of blog articles.

Menu Trail By Path is best used in conjunction with Pathauto.


Show comment module but have it disabled for anonymous users

I didn't know this until I just tried it but you can use a hook_form_alter() function in a custom module and simply set the whole $form to disabled...this disables all child elements as well. Combine it with the user_is_anonymous() function and you should be set:

function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if (user_is_anonymous()) {
    $form['#disabled'] = TRUE;
    // Add a link:
    $form['register_link'] = array(
      '#markup' => l('Click here to register...', 'user/register')
    );
  }
}


How do I set my custom input type as default?

In Drupal 7, the default input format is the one the users have the permission to use, and that appears first in the list of the input formats reported in admin/config/content/formats.

In my case, Textile is the default input format that is selected for the administrator role, but if the currently logged-in user doesn't have the permission to use that input format, then the default input format will be "Filtered HTML." "Plain text" is the input format that all the roles can access; in the case none of the other input formats is accessible to the user, "Plain text" is the input format that will be used.

In Drupal 6, the default input format is the one selected as default in admin/settings/filters.


Deploy to production with git using Acquia like localserver

You're missing the database. git only handles files.

So export your local database, and import it in production.
For that you could use drush sql-sync, but you need to set it up properly.

You could also export the database to an .sql file via phpMyAdmin or your preferred db-tool. and then in aquia devcloud, you import that .sql file.


in ckeditor plugin, why isn't my getConfig returned array affecting editor?

It turns out I was just formatting the array improperly. In order to return the configuration to my wordcount plugin I did this:

 return ['wordcount' => ['maxWordCount' => '10']];


You can use a template_preprocess_page function to add your custom tpl for Panels page. Here's how:

/**
 * Implements template_preprocess_page().
 */
 function MODULEORTHEMENAME_preprocess_page(&$variables) {
    if (module_exists('page_manager') && count(page_manager_get_current_page())) {
        $variables['theme_hook_suggestions'][] = 'page__panels';
    }
 }

Then create a page--panels.tpl.php for your custom Panels page.


How to get an editable cart at checkout with Drupal Commerce?

The module Commerce cart form checkout pane does this very well.


Downloads restrictions through direct URL

Not sure if this will help you, as I have never used it, but worth checking out:
Unique-download

Onetime download link is useful to create one-time download link,
similar to one time login. This will be helpful to send users one time
download links for e-commerce or download entities such as books, mp3
etc etc. considering them as file attachment for initial development.


Hide label for input on focus and when has value

Check out this

   if ($(value).val() != ""){
  var fieldId = $(value).attr("id");
  $("label[for='"+fieldId+"']").hide();
}


Pathauto pattern for a content type depending on a reference field?

A taxonomy field is referencing entities, it has no value property. See how to print value of a taxonomy field to headline with node.html.twig?
Converting this to a token pattern:
[node:field_content_class:entity:name]/[node:title]


How to allow Infinite Scrolling through "Views Load More" module with waypoints?

It's actually really easy to do with standard Views and jQuery.autopager in your theme.

The most important part is using the correct classes, I can't find my working example at the moment, but it should look something like:

$.autopager({
  // where contents would be appended.
  // use "appendTo" or "insertBefore"
  appendTo: '.views-content',

  // a selector that matches a element of next page link
  link: '.pagination .next a:first',

  // a selector that matches page contents
  content: '.views-row',
});


Generate unique form ID based on context

As with Drupal 7, forms need to have a unique form ID. What's different is that in Drupal 8, the connection between the form (code) and the form ID is reversed.

In Drupal 7, as pointed out by @Ivan Jaros in the comment, you start with the form_id, so we had hook_forms() that allowed to map form ID's to a function that then built the form.

In Drupal 8, you first need to create a form object so that its getFormId() method can return a unique ID. The challenge there is that getFormId() is called very early, specifically before buildForm(), so the usual way of passing arguments to forms does not work.

What you need to do is create the form object yourself instead of just passing the class name to the form builder, then you can set any data on it that you want before passing it the form builder.

To get the form class, you can either instantiate it yourself, but then you can't use the ::create() method to inject dependencies, for that, you need to use the class resolver, from FormBuilder::getFormId(), this is what it does by default if you pass in a class name:

if (is_string($form_arg) && class_exists($form_arg)) {
  $form_arg = $this->classResolver->getInstanceFromDefinition($form_arg);
}

You could even use the current object or any other existing object as a form, as long as it implements \Drupal\Core\Form\FormInterface. One example in core that does that is the DraggableListBuilder and BlockListBuilder, see its render() method:

public function render() {
  if (!empty($this->weightKey)) {
    return $this->formBuilder()->getForm($this);
  }
  return parent::render();
}

That has the advantage that you do not need another class, you could make a block plugin that displays a form do it in the same class, for example. On the other side, that prevents you from re-using that form elsewhere and could also result in conflicts if the same method names are used for something else.


scheduling backup_migrate with elysia cron

It all depends on your preferences and situation.

Elysia is designed to work in environment when you can trigger Elysia every minute (or every five, or ten minutes, but regularly 24/7). In that environment it would be more convenient to simply schedule Backup and Migrate with Elysia. Just remember to keep what you set in Home > Administration > Configuration > System > Backup and Migrate > Schedules in sync with what you set in Home > Administration > Configuration > System > Cron > Settings.

Benefit of that solution is easily accessible status of a cron task, the fact that you can see with GUI how long it took and when it was last fired, without login to any other tools but your Drupal.

Problem is that if cron system gets delayed, you may lost next sheduled backup - it may be mere 23h 58m since last time Elysia fired BaM task, so BaM may decide it's too soon to take another "everyday" backup. It's common problem with one scheduler calling another. And if you will make Elysia to trigger BaM every 5 minutes, to make sure everyday backup will be triggered consistently, you will waste a lot of CPU power for nothing.

drush bam approach is more direct. Long story short, it's main pros is lack of problems described above, and main cons is lack of benefits described above. And it's slightly faster in execution overall, as one "layer" less is in use.


Is there a module for showing only posts in some defined date?

This is done with the Views module. Create a new view of content with a display type of 'block', and set it up as an unformatted list of teasers with links, then click 'Continue and edit'.

Add a filter on Content:Posted Day, and choose your conditions like 'is greater than' 'offset' '-10 days'.

You can then set any other views parameters to get what you want.

Save your view and go to admin/structure/block to find your block and place it where you want it.


Images loading fine on day 1, broken on day 2

There is a related issue for this here. http://drupal.org/node/1352182.

What's happening is that drupal is storing the URL that is created when the page is first viewed after the cache is cleared. Normally that would be your site url, but sometimes it's not.

In the issue linked you see that some people fixed this using the Pathologic module.


You need to define the $user variable first. You can run the drush command as a particular user by specifying --user on the command line:

drush --user='admin' ev 'global $user; print_r($user);'

If you don't specify a user, drush runs as anonymous by default.

Or, you can do it like this:

drush ev '$user = user_load_by_name("admin"); print_r($user);'

It will display this:

stdClass Object
(
    [uid] => 1
    [name] => admin
    [pass] => *****
    [mail] => info@example.com
    [theme] =>
    [signature] =>
    [signature_format] => filtered_html
    [created] => 1443708895
    [access] => 1515415027
    [login] => 1515411954
    [status] => 1
    [timezone] => Europe/London
    [language] =>
    [picture] => 0
    [init] => info@example.com
    [data] =>
    [uuid] => f6800524-c092-4abc-abcd-f71d091623cd
    [roles] => Array
        (
            [2] => authenticated user
        )

    [force_password_change] => 0
)


Drupal 8 - url rewrite don't work on beta12 after installation

Last Drupal 8 Beta release don't have .htaccess.


How can I stop the Devel module from generating blog/forum entries for Anonymous user?

The Devel module doesn't have options to decide to which users the generated content is assigned, but you can create a custom module to limit the users to which the created content is assigned. You need to:

Implement hook_form_alter() to add the extra form fields necessary to select which users accounts should be used in the form generated by devel_generate_content_form()
Replace the form submission handler with one that generates the content using the user accounts selected in the form

You can use the existing form submission handler (devel_generate_content_form_submit()) as guideline to build your submission handler.

function devel_generate_content_form_submit($form_id, &$form_state) {
  module_load_include('inc', 'devel_generate', 'devel_generate');
  $form_state['values']['node_types'] = array_filter($form_state['values']['node_types']);
  if ($form_state['values']['num_nodes'] <= 50 && $form_state['values']['max_comments'] <= 10) {
    module_load_include('inc', 'devel_generate');
    devel_generate_content($form_state);
  }
  else {
    module_load_include('inc', 'devel_generate', 'devel_generate_batch');
    devel_generate_batch_content($form_state);
  }
}

Unfortunately, devel_generate_content() doesn't allow to select the user accounts to use as authors of the nodes. This means you need to write all the code yourself. The bright side is that the function that in your module replaces devel_generate_content() is very similar to that function with a single difference: the function to call instead of devel_generate_content_pre_node().

function mymodule_generate_content($form_state) {
  if (!empty($form_state['values']['kill_content'])) {
    devel_generate_content_kill($form_state['values']);
  }

  if (count($form_state['values']['node_types'])) {
    // Generate nodes.
    mymodule_generate_content_pre_node($form_state['values']);
    $start = time();
    for ($i = 1; $i <= $form_state['values']['num_nodes']; $i++) {
      devel_generate_content_add_node($form_state['values']);
      if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
        $now = time();
        drush_log(dt('Completed !feedback nodes (!rate nodes/min)', array('!feedback' => drush_get_option('feedback', 1000), '!rate' => (drush_get_option('feedback', 1000) * 60) / ($now -$start))), 'ok');
        $start = $now;
      }
    }
  }
}

function mymodule_generate_content_pre_node(&$results) {
  // Get user id.
  $users = mymodule_get_users($results['exclude']);
  $results['users'] = $users;
}

function mymodule_get_users($exclude) {
  $users = array();
  $result = db_query_range("SELECT uid FROM {users} WHERE uid NOT IN :exclude", 0, 50, array(':exclude' => $exclude);
  foreach ($result as $record) {
    $users[] = $record->uid;
  }

  return $users;
}

The code I shown assume you add a form field (exclude) that contains the user ID for the user accounts that should not be assigned as authors of the generated nodes.

Probably, you also need to write the equivalent of devel_generate_batch_content(), which is the other function used to generate content, for your module.

Notice that the Devel generate module is used to generate content for developing/testing purposes. It should not be used to generate content for a production server/web site. That is the reason why there aren't too much options for the content to generate.


What about the timezone settings ? This could be a lead.
http://php.net/manual/en/function.strtotime.php


The Formatter Field module was made for just that:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

There are some steps on the module page I'd recommend reading before diving right in, it's not immediately obvious how to make this module work.


As reported in Installing sandbox projects, sandbox projects don't have download links, since versions are not enabled for them. You need to use git to download the code.

Assuming you mean the PredictionIO module, that doesn't still have code, at the moment; it is reported in its Version control tab.

  No code is available for PredictionIO. File an issue or contact a maintainer if you have questions.

If there were code, you could download it with the following command.

git clone --branch master http://git.drupal.org/sandbox/mrded/2116851.git predictionio

In the predictionio directory, you would find the module code.

Update

On June 17, 2015, the maintainer answered to Code? saying:

  Hi guys,

  We actually stopped developing of this module.
  If you're interested, I can publish your codebase as full project and give you a maintainer permissions to fully control the module.

If nobody is going to offer to be maintainer of that sandbox project, the project will not have any code.


Which actions in Drupal needs clearing the cache?

Strategy is quite easy - clear it when you changed something in code or database.

Below some popular cases (based on my experience):

you added new content and need to update cached pages, views or blocks (for example you enables cache for anonymous users)
you changed JS or CSS files and you have enabled aggregation
you installed new modules (in this case need to run update.php)
you did modifications in existing module which require update cache. For instance added menu item or implemented some hooks.
you did changes in theme files


Can't get CKEditor to work on Drupal 7.8

Well I finally got it working...

I installed CKEditor module, CKEditor library, and then had to hack the CKEditor library folder by creating new subdirectories with the appropriate files (it was looking for the skin and language files in the wrong directory within the CKEditor library folder)...

I'm using the latest version of everything - why is this happening? I would have thought since this happened to me its happening to everyone else as well!

If anyone else has this problem, ensure you have these files in your /modules/ckeditor/ckeditor/ folder:
"lang/en-gb.js"
"skins/kama/images/sprites.png"
"skins/kama/editor.css"
"skins/kama/icons.png"

All these files are just in the root folder by default for some reason.


Which is better approach "taxonomy_get_term" or using SQL to display term name on template file

Literally the only difference between you calling taxonomy_get_term() and running the query yourself is that taxonomy_get_term() statically caches and serves term objects that have been loaded previously in the same page load.

You'll only get performance increases, not decreases, if you use the API function so I'd thoroughly recommend using that instead of going directly into the database.

Since you're running an identical query anyway, it's just repetition of code otherwise.

This is the code from taxonomy_get_term(), it should help illustrate the above:

function taxonomy_get_term($tid, $reset = FALSE) {
  static $terms = array();

  if ($reset) {
    $terms = array();
  }

  if (!isset($terms[$tid])) {
    $terms[$tid] = db_fetch_object(db_query('SELECT * FROM {term_data} WHERE tid = %d', $tid));
  }

  return $terms[$tid];
}


First off, don't edit the module's code directly. Make a custom module that will hold your changes.

Secondly, you can use HOOK_form_alter to make changes to the form.


How to pass node queue id in views contextual filters

You can give a try to nodequeue_extras module

  Provides 2 pieces of helper functionality specific to Nodequeue and Views:

  Contextual nodequeue edit links for views that include a nodequeue relationship.
  A special Views nodequeue relationship and subqueue argument that let you build views based on a subqueue without requiring that all result nodes in the view exist in the subqueue.


Check not NULL in entityfieldquery propertyCondition

Unfortunately, it is impossible at the moment. See the workaround described on http://drupal.org/node/1226622.


How to setup event registration and paypal payment?

You should use Registration Commerce module. This module acts as a integration point between entity registration and drupal commerce enabling you to implement paid registration using entity register. Also use Commerce paypal for paypal integration with drupal commerce.


how to add taxonomy terms to admin/config/people/accounts/fields programmatically?

You need to create an instance of the field, and then attach it to your content type. This is done using the field_create_instance() function.

There's a nice example in the standard profile of attaching the 'Tags' vocabulary to the article content type upon install:

$instance = array(
  'field_name' => 'field_' . $vocabulary->machine_name,
  'entity_type' => 'node',
  'label' => 'Tags',
  'bundle' => 'article',
  'description' => $vocabulary->help,
  'widget' => array(
    'type' => 'taxonomy_autocomplete',
    'weight' => -4,
  ),
  'display' => array(
    'default' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
    'teaser' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
  ),
);
field_create_instance($instance);

The documentation page has a full list of all the available properties for your field instance, but the above code is an excellent place to start.

I also have this piece of code in my arsenal which dumps the field/instance definitions of an existing field so I can inspect it and just chop and change what I need to:

$entity_type = 'node';
$field_name = 'field_FIELDNAME';
$bundle_name = 'BUNDLE_NAME';

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


What about leaving the rendering of fields by Drupal and putting your list directly in the template?

Depending the condition about your node rendering, can be based on 1 particular node, or by content type, ... you can use a separate tpl file. For example, if its for a content type gallery, you can create a node--gallery.tpl.php in the templates folder of your activated theme.

Inside the tpl, you can create an HTML structure like this:

<div class="content"<?php print $content_attributes; ?>>

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

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

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

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

    </

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

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

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

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

    </

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


It is possible to create this functionality using the Geolocation Views module. Here is a quote about it (from the module's project page):

... is sub-module for Geolocation Field to display markers on Google Map using Views 3.
Module support:

show content in Info Windows
custom marker images
markers as links
multiple maps on a single page
support MarkerClusterer


Making context aware Views is not something you can easily do with Context module. That is I'm sure it would be possible, but it would require a lot of work.

Panels is designed to accomplish such tasks, with it's tight integration to views, it can pass arguments to views that you can use to determine what to display.


What you're actually saying is that you don't want contextual filters, contextual means that you want an argument based on the context of the site which is usually separated out by the url.

The quickest way to do what you want is this.

move your contextual filters into the filters section of views,
making sure that you expose them to visitors.
Under the more setting of each filter is where you set the filter
identifier and change the advanced options to label the filter as you
require such as "nid" then your url would be
mywebsite.com/page?nid=xxx
Then under the exposed form settings, change the setting to "expose
form as block" to yes to make the exposed filters disappear.


How can I programatically get the cart's dollar sum of drupal commerce?

You should have it already.  That call to "commerce_line_items_total" returns the array:

return array('amount' => $total, 'currency_code' => $currency_code);

Thus you should have the total price at $total['amount'] since you already have $total['currency_code']


How renderable array for an image with style should look like?

There's nothing specific for images, but there is for any theme function. Your old code using theme() would be equivalent to:

$build = array(
  '#theme' => 'image_style',
  '#path' => $image['uri'],
  '#style_name' => 'product_page_thumbnail',
  '#alt' => $image['ImageAlt'],
  '#title' => $image['ImageTitle'],
);

Basically you pass the named variables for the theme function as #-prefixed properties, and the render system will do the rest.


Field visibility & access can be controlled with the Field Permissions module.


Worth noting that tracking individual users is against the Google Analytics terms of service:

  7.PRIVACY . You will not (and will not allow any third party to) use the Service to track or collect personally identifiable information of
  Internet users, nor will You (or will You allow any third party to)
  associate any data gathered from Your website(s) (or such third
  parties' website(s)) with any personally identifying information from
  any source as part of Your use (or such third parties' use) of the
  Service. You will have and abide by an appropriate privacy policy and
  will comply with all applicable laws relating to the collection of
  information from visitors to Your websites. You must post a privacy
  policy and that policy must provide notice of your use of a cookie
  that collects anonymous traffic data.

However, Drupal can track authenticated users using the core statistics module.

More info:

statistics_node_tracker
statistics_user_tracker
statistics documentation


How to change autocomplete_route_parameters value on change of select option?

I have used below example to do that.

https://api.drupal.org/api/examples/ajax_example%21ajax_example.module/function/ajax_example_dependent_dropdown/7.x-1.x

Customized it as listed below.

$form_state_values = $form_state->getValues();
if (!empty($form_state_values['language'])) {
  // write your logic here to prepare $skip_node_id_string & $langcode
}
$form['first'] = [
 '#type' => 'textfield',
 '#title' => $this->t('first'),
 '#autocomplete_route_name' => 'autocomplete_node_search.autocomplete',
 '#autocomplete_route_parameters' =>
 array('skip_node_id_string' =>$skip_node_id_string,
 'langcode' => $langcode),
 '#prefix' => '
',
 '#suffix' => '
',
];
$form['language'] = [
 '#type' => 'select',
 '#title' => $this->t('language'),
 '#options' => ['someval'],
 '#ajax' => [
  'callback' => [$this, 'changeLanguage'],
  'event' => 'change',
  'wrapper' => 'change-lang-wrap',
 ],
];
// Ajax callback.
public function changeLanguage(array &$form, FormStateInterface $form_state) {
 return $form['first'];
}

Hope this will fix your issue.

Tried below links, but no luck.

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


Views don't display any result until the exposed form is submitted

I think you have marked the exposed filter as required.

Uncheck the "Required" checkbox right below the "Expose this filter to visitors, to allow them to change it" checkbox.


Webform - User to edit submission (admin can close)

You have to view your submission and click on edit to update. Remember you can only edit your own submission.


So @NoSssweat's suggestion of using Paragraphs seems to be the best solution to me right now. There seems to be few documentation about this, unfortunately. It took me several hours to figure everything out, that's why I wrote this looong step-by-step guide:

Download and install the Colorbox plugin.
Download and install the Entity Reference Revisions plugin. This is a requirement for Paragraphs.
Download and install the Paragraphs plugin.
Go to Management > Structure > Paragraphs types

First, we need to add a paragraph type. Click the "Add a Paragraphs type" button.
Give it a name and press "Save". I named mine "Text with image (left)".
You're back at the "Paragraphs types" node. You can now see your new paragraph in the table. There's a column "MACHINE NAME", this is going to be important later on when we're theming the paragraph!
We now need to configure the paragraph, so click the "Edit" button next to your new entry.
Click on "Manage fields".
We're going to add two fields. These are the values that you set for your paragraph when you're adding it your content later on. Press "Add field".

In the "Add a new field" drop-down box, select "Image" (in the "Reference" group) and give it a name (for example… "Image"). Press Save and continue.
Now the editor for the "Image" field is shown, with the "Field settings" tab being selected. The default values were fine for me, especially the "Allowed number of values" being 1. So I pressed "Save field settings".
You should still be in the editor for the "Image" field, but now the "Edit" tab is selected. Here you can configure a few things about the image itself, like it's minimum and maximum sizes, which file types to allow and so on. The "Required field" checkbox is notable, it tells whether you must set an image when you're using the paragraph. I'd say yes, so enable this checkbox. Press "Save settings" one you're done.

You're back in the "Manage fields" node. Press "Add field" again.

Now select a text field type, like "Text (formatted, long)" and give it a name (for example, "Body"). Press "Save and continue".
In the "Field settings" tab, there's not much to do. We only want "Allowed number of values" to be 1. Press "Save field settings".
In the "Edit" tab, also enable the "Required field" checkbox. Press "Save settings".

We're back on the "Manage fields" page of the paragraph. In the "Manage form display" tab you can configure how the UI to add content to your paragraph will look like. I just changed the size of thumbnail here, the rest was OK for me.
Go to the "Manage display" tab.

I set the labels for both fields to "-Hidden-" as I don't want them to be shown when the paragraph is rendered.
For the "Image" field, set the format to "Colorbox" and press the gear symbol on the right to configure how the image is going to be rendered. Specifically, set the "Content image style" to a suitable thumbnail size, for example "Medium (220x220)". I don't know yet where you define your own, but the Medium selection suited my need anyway. Press the "Update" button when you're done.

We're now done with the paragraph. Next, we need to add a suitable content type or modify an existing one. Let's set up a new one:

Go to "Manage" > "Structure" > "Content types".
Press "Add content type".

We need to give it a name, for example "Paragraphs page". All the other values were fine for me, so I just pressed "Save and manage fields".
You're now on the "Manage fields" tab. By default, there's one entry in the table named "Body" of type "Text (formatted, long, with summary)". We don't want it, so click on the down facing triangle next to "Edit" and select "Delete". You're asked whether you want to do so, confirm by pressing "Delete".
Back on the "Manage fields" tab, press "Add field".
In the "Add a new field" drop-down box, select "Paragraph" (in the "Reference revisions" group) and give it a name (I named it "Paragraph"…).
Press "Save and continue".
You should now be on the "Field settings" tab of your paragraph field. For "Type of item to reference", make sure "Paragraph" is selected and you probably want the "Allowed number of values" to be unlimited. Press "Save field settings".
You're now on the "Edit" tab of your paragraph field. Do not enable the "Required field" checkbox here as this triggers a bug that prevents you from saving when you add new content (you can't save and get the message "This value should not be null." due to this bug). Just press "Save settings".
In the "Manage form display" tab you can again refine how the UI for adding content will look like. The defaults are fine.
Go to the "Manage display" tab, it allows you to tweak how the content is rendered. I don't want labels so I set the label for the paragraph field to "-Hidden-". Press "Save".

Now we're able to actually create content, although it won't look the way we want it yet. Let's try it anyway:

Go to "Manage" > "Content" and press "Add content".
Select your new content type, in my example it was "Paragraphs page".
Enter a title.
You'll see a message "No Paragraphs have been added yet. Select a Paragraph type and press the button below to add one." Below that message is a button that starts with "Add" followed by a paragraph name. In my example, it's named "Add Text with image (left)". Press it.
You can now select an image (you may need to set the "Alt" field as well) and enter some text for the body. Do so and press "Save and publish".

You can add multiple paragraph per page. Just press the "Add …" button above the "Save and publish" button to add another paragraph.

If everything is alright, you will now see your image and your text. Depending on how you arranged the fields in the "Manage display" tab of your paragraph type, either the image or the text is on top. But we wanted the image to be next to the text. To do that, we need to theme the paragraph.

So the final step is to theme the paragraph. This is under-documented part, IMHO. Here's how to do it:

This needs to be done on the server's filesystem, either by shell or some file transfer software. It depends on your setup.
I'll call the top-level Drupal directory DRUPAL_ROOT. That's the directory with core, modules, sites, … subdirectories.
The Paragraphs module comes with basic template for theming. It's located at DRUPAL_ROOT/modules/paragraphs/templates/paragraph.html.twig.
You'll need to copy that file to the current theme's directory with a special filename.

There might be a better way to do this, please let me know if there is. It feels hack-ish…
Find the theme's template directory: there's some directory that contains *.html.twig files. You need to locate that. I was using the Bootstrap theme, the correct directory for that theme is DRUPAL_ROOT/themes/bootstrap/templates/bootstrap/. For Bartik, it's DRUPAL_ROOT/core/themes/bartik/templates/.

You also need the machine name of your paragraph. I mentioned it above, you can find it by going to "Manage" > "Structure" > "Paragraphs type". Look at the "MACHINE NAME" column.

For my paragraph, that name is text_with_image_left_.

Now, copy the paragraph.html.twig file into your theme's template directory and rename it to paragraph--<machine_name>.html.twig.

My file thus is named paragraph--text_with_image_left_.html.twig. Since I was using the Bootstrap theme, the path thus was DRUPAL_ROOT/themes/bootstrap/templates/bootstrap/paragraph--text_with_image_left_.html.twig.

Edit the file. I don't know what the stuff between {% and %} is for, I didn't need to tweak it. Just edit the HTML to look like this:

{{ content.field_image }}

    {{ content.field_body }}

The content.field_image and content.field_body correspond to your paragraph's field names. You can see those in the "MACHINE NAME" column of your paragraph's field list ("Manage" > "Structure" > "Paragraphs type", press the arrow next to the "Edit" button and select "Manage fields").

Save. Now you need to clear Drupal's cache: "Manage" > "Configuration" > "Performance" > "Clear all caches".
We're done! Reload the test page you've created before and the text should now flow around the image. Clicking the image should open the large version.


Is a content type needed by a custom module?

You can create you own data structure but I think your life will be a lot easier if you create a new content type or an entity. You can alter the form in the way you need it or get it and render it wherever you want. You also have validation and submit handlers.


No need to add prefix/suffix markup, just add a container or fieldset and use CSS to float them inside.


Show Active terms from vocabulary using taxonomy menu

You can do this by using hook on taxonomy insert and update inside a custom module.

Here is a sample of code (needs refactoring/cleaning/checking but that's a start and it works for me) :

function custom_module_taxonomy_menu_insert(&$item) {
  //load taxonomy to access fields
  $tax = taxonomy_term_load($item['tid']);
  //get your field display (here i called it field_status)
  $display = isset($tax->field_status['und'][0]['value'])?$tax->field_status['und'][0]['value']:'';
  //check your value
  if($display == 0) {
    //I don't want to display this element
    $item['remove'] = TRUE;
    return $item;
  }
}

function custom_module_taxonomy_menu_update(&$item) {
  //IDEM without comments
  $tax = taxonomy_term_load($item['tid']);
  $display = isset($tax->field_status['und'][0]['value'])?$tax->field_status['und'][0]['value']:'';
  if($display == 0) {
    $item['remove'] = TRUE;
    return $item;
  }
}

[Edit to add some details]

The menu will not update automatically, you'll have to save/update your terms to update the menu (hook_taxonomy_menu_update). For new terms, it's going to work automatically  (hook_taxonomy_menu_insert).


Eliminate access to specific user based on url, uid and role

I don't understand what you want to do specific to the panels page. In general you are looking for some kind of hook triggered every time a user visits a page. In D8 every page is connected to a route. You have to implement an access check on this route, see the documentation Access checking on routes. You can define the access check when you create a route or if you have an existing route from another module you can alter the route definition, see for this the next chapter in the documentation Altering existing routes


get taxonomy term aliased path when its a referenced field in a $node entity

Sure enough I could use the tid or target_id in entity reference lingo and use it to find the URL fromRoute using as route_name entity.taxonomy_term.canonical

    $tid = $node->field_category[0]->target_id;
    $categoryurl = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $tid], $options);

find other taxonomy route_names

might also need to see the Url::fromRoute definition


How to periodically deduct user points for flagged nodes?

Part 1 - Deducting user points

Repeat the daily deduction of user points

Use the rules scheduler as explained in the video about "Repeating scheduled events". The "clue" here is:

as the last action of your rule, you reschedule the same rule to be executed again after +1 day(s).
the very first time you need to trigger the execution of this rule manually (from the Rules UI). Or you can use the Rules Event "when node is flagged".

Video tutorials

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

Part 2 - Stop deducting if insufficient user points

The 2nd part of your question is about "... when user doesn't have enough points anymore, then node must be unflagged ...". The challenge with that is that there is no Rules Condition like "If user has less then X user points".

However, to also make that work, you can use a Rules Action "Load user points of a user", as an alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user". Have a look at my answer to "How to create rule to change user role based on points (using User Points module)?", which includes an sample rule that uses this Rules Action.

So all you have to do is to further enhance your rule as in Part 1, by using the Conditional Rules module so that your Rules Action will look something like so:

  Load user points balance

  If user points balance > 40

  then reschedule the same rule to execute in 1 day.


How to always require email verification before accessing a page?

Because the page I was creating was actually a form, I found this module got me out of trouble password_require

Although strictly speaking my question didn't specify it was a form. Other than mentioning buttons.

Hope it helps someone


Pre-process to change the name of a file field in node

if you only want to change the label maybe the module string overrides is your best option https://www.drupal.org/project/stringoverrides

you can also edit your settings.php file to change the label https://www.drupal.org/node/522036


Removing a row from a view depending on the user currently logged in

This isn't a views' problem. I'm assuming that the non-core users should not have access to the content that has the core-team tag anywhere (not just in the specific view). That's because if you use a "hack" to remove the result from the view, someone entering the specific blog post's url directly in his browser would take him to the node.

What you actually need to do is use the Taxonomy Access Control module to restrict access to the "core-team" tag. When you do that, the non-core user will not have permission to view the content tagged as "core-team", so the view will not display these results either (assuming that in the access restrictions of the view you left the default value of: "Permission").


How to make a link type of a news automatically?

Create a View named "xyz" & select content of type "news"
Select page or block
Add fields what you want to show or if you need filtration then you can filter your content.
& save.


You can specify the round mode you want in the tax type configuration page.

/admin/commerce/config/taxes/types/vat/edit

(It should be configure to no round by default)


jQuery(document).ready(function() {
 if (window.location.pathname == '/recruiterForm/2') {
      jQuery('input#edit-submit').hide();
      }
});

i have solved this problem using jquery.I have used window.location.pathname.This property returns the pathname of current page.if pathname is equal to the required url then i am hiding the save button by using the save button id.This solution works for me.


Node view mode in page template suggestions

The hook hook_theme_suggestions_HOOK is the one you should implement.

When you have a node of type page (labeled as Basic Page from the default profile), then the HOOK is node and the specific hook you would implement is hook_theme_suggestions_node(array $variables)

As @pinueve points out, there is already a specific suggestion that includes the custom display mode: node--page--CUSTOM_VIEW_MODE.html.twig.

Also, as @pinueve suggests, the easy way to find the template suggestions is by enabling the debugging mode. I tested this using a custom view mode called customvm that I created, so I can see these suggestions in the browser by inspecting the source code:

* node--17--customvm.html.twig
* node--17.html.twig
* node--page--customvm.html.twig
* node--page.html.twig
* node--customvm.html.twig
x node.html.twig

Alter hook

Note that there is also an alter version of the hook [HOOK_theme_suggestions_node(array &$suggestions, array $variables)][3], you should use this if you are trying to alter the existing suggestions, maybe changing the priorities.

Suggestions for a page from a custom controller

The page HOOK is meant to be used when the output comes from a custom controller and route, like the one in this example:
https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

In this case the HOOK is page and you would implement these hooks:

HOOK_theme_suggestions_page(array $variables)
HOOK_theme_suggestions_page_alter(array &$suggestions, array
$variables)


Form with managed_file value as link in email

Thanks to Jaypan from drupal.org, I've got the answer:

<?php
file_create_url($file->uri);
?>

Simply with adding this code and make another variable that will use the code, I've got the right result.


Instead of #markup, which is filtered, use inline template:

$file_path = 'movie.mp4'

$video = '<video width="480" height="320" controls="controls">
  <source src="{{ file_path }}"  type="video/mp4">
</video>';

$element[$delta] = array(
  '#type' => 'inline_template',
  '#template' => $video,
  '#context' => array(
    'file_path' => $file_path,
  ),
);


How to display $variables in drupal 6 preprocess function?

Install the Devel module.

Once installed use the function dpm() like this: dpm($variables);

This will give you a nice print out of your variables.


How to programmatically create a add to cart form with quantity input?

Interesting. I would have never thought to do this. A quick search in the commerce module produced this example:

<?php
// line 2649 of commerce_cart.module

// Extract the drupal_get_form() arguments array from the element.
$arguments = $element[$key]['#arguments'];

// Add the display path and referencing entity data to the line item.
if (!empty($entity_uri['path'])) {
  $arguments['line_item']->data['context']['display_path'] = $entity_uri['path'];
}

$arguments['line_item']->data['context']['entity'] = array(
  'entity_type' => $context['entity_type'],
  'entity_id' => $entity_id,
  'product_reference_field_name' => $field_name,
);

// Update the product_ids variable to point to the entity data if we're
// referencing multiple products.
if (count($arguments['line_item']->data['context']['product_ids']) > 1) {
  $arguments['line_item']->data['context']['product_ids'] = 'entity';
}

// Replace the array containing the arguments with the return value of
// drupal_get_form(). It will be rendered when the rest of the object is
// rendered for display.
$output[$field_name][$key] = drupal_get_form($arguments['form_id'], $arguments['line_item'], $arguments['show_quantity'], $cart_context);
?>

Which means you could do this:

<?php
$product_id = 1;
$form_id= commerce_cart_add_to_cart_form_id(array($product_id));
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1);
$line_item->data['context']['product_ids'] = array($product_id);
$form = drupal_get_form($form_id, $line_item, true);
dpm($form);
?>

And you will see how it affects the quantity (makes it become a proper field). You're also missing the $cart_context that the core module uses to determine what to do with displaying/hiding fields.


If that package is doing it correctly, then it registered its classes with composer and it should just work.

If it doesn't use namespaces (which you could see by opening the file), then just write new ClassName and it should work.

That is assuming you installed the dependency correctly, it needs to be in your main vendor folder, not the one of a module or so.


How can I run a query with php before entering a view

I used hook_views_pre_execute
and was able to run what I wanted before the view is created


I've packaged this up into a module to extend the og_username_helper.

 58 /**
 59  * Extends og_username_helper to Groups Invite Members tab
 60  */
 61 function soc_searchtweak_form_alter(&$form, $form_state, $form_id) {
 62
 63   $form_changes = array();
 64   $form_changes['og-invite-link-invite-page-form']='invitees';
 65   $form_changes['commons-profile-friend-search-form']='search_text';
 66
 67
 68   foreach ($form_changes as $form_id=>$field_id) {
 69
 70
 71     if ($form['#id'] == $form_id) {
 72       $form[$field_id] = array(
 73           '#type' => 'textfield',
 74           '#description' => t('Lookup a username and add it to the list below.'),
 75           '#autocomplete_path' => 'og/username_helper/autocomplete',
 76           '#size' => 40,
 77           '#maxlength' => 60,
 78           '#weight' => -2,
 79           '#access' => $helper_access,
 80           );
 81
 82       return $form;
 83     }
 84
 85   }
 86
 87
 88 }

The module.info file puts og_username_helper as a dependency.

1 name = Search Tweak
2 description = Extends og_uesrname_helper in various places
3 core = 6.x
4
5
6 dependencies[] = og_username_helper


The invocation of the hook_html_head_alter was removed from Drupal core.
Issue - Remove invocation of hook_html_head_alter().

D8 has a new hook to achieve it : hook_page_attachments_alter().

Code from the change record :

function MYTHEME_page_attachments_alter(array &$page) {
    $viewport = [
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'viewport',
        'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
      ],
    ];
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];
  }


How to troubleshoot subdomain issue on Aegir

Your platform is most likely missing the .htaccess file in its top-level directory, or (less likely, or else the Aegir interface itself would likely show the same problem) mod_rewrite is not enabled on your site.

See if you can get to http://testname.mydomain.com/?q=user

If that works, but http://testname.mydomain.com/user doesn't, then your .htaccess file is missing or being ignored by Apache.


Yes as simple as changing the post time at the point time that you would like to released that post


How to add css class to these form fields?

You should write a statement that first check the form element type then add class attrubutes to it,
something like
//in form_alter

foreach($form as $form_elem){
if($form-elem['#type']=='textfield'){
    $form[$form_elem]['#attributes']['class'][] = 'myclass';
   }
}

(this is not the exact solution,I just want give you idea)

another way is using hook_preprocess_field

and the final and easy way is using js to add class, because drupal set default class for his textfields,you just need one line jquery code to add you

   $('.form-text').addClass('myclass');

if you don't want this js not load in all page, I suggest you add your js with drupal_add_js conditionally in hook_form_alter, it means that

    //in hook_form_alter
     $des_forms=array('node_add_page','node_add_prodcut');
    if(in_array($from_id,$des_forms)){
    drupal_add_js('your js'); //you also add it inline,but I suggest you put it in js and add it as file
}

again I tell you because I have no time in this moment I just suggest you some solution idea, I hope could help you


How can I create a Link to an URL containing a fragment identifier?

Please see public static function Link::createFromRoute

array $options: The options parameter takes exactly the same structure. See \Drupal\Core\Url::fromUri() for details.

You can pass a 4th argument as an array with a fragment key value:
Link::createFromRoute($this->t('Title'), 'entity.node.canonical', ['node' => 77], ['fragment' => 'example']);


How to hide node by Role similar to the Hide Block by Role module?

Rules (the module) is your friend ... Here is a prototype of a rule (in Rules export format) that you could use (assuming that the Role ID (rid) for Role B is "4", adapt the value of this rid to fit your case):

{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "op" : "IN",
          "value" : { "value" : [
              "node\/123",
              "node\/456"
            ]
          }
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "access_denied" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

After you enable the above rule, you can grant Access (view) permission to the nodes "node/123" and "node/456" for users with role A (using the Content Access module). That will already prevent access to these nodes for any user who does not have that role A.

The above rule will ensure that users who do not have role B, will NOT be able to actually "view" these nodes. Instead they'll get a message starting with "Access to the content located at ..." (change this message to whatever fits).


Function to check for value prior to using getValue?

I think you are looking for the main property of the field:

if ($item = $user->get($fieldName)->first()) {
  $string = $item->{$item->mainPropertyName()};
}
else {
  $string = '';
}


How to expand the fieldsets in node-add form?

I believe you have one of two options...

In Code: Have a look at hook_form_alter() and modify the applicable field groups to be $form['the_form_fieldset']['#collapsed'] = FALSE;
In UI: Modify the CCK types form. Go to your content types, click manage fields on the one you want and then select the 'Manage Form' tab.

Hope that helps!


Web service with application-level and user-level authentiation

Under D6, using Services 3.x

It may be more easy to consider that:

User authentication should be handled directly by Services (OAuth/API/Session)
Using an specific mobile app is a Permission:

in your module, in the resources definition, add a access_callback & access arguments:

Code:

/**
* Implementation of hook_services_resources().
*/
function mymodule_api_services_resources() {
  return array(
   'myresource' => array(
     'retrieve' => array(
       'callback' => '_mymodule_resource_retrieve',
       'access callback' => '_mymodule_api_access',
       'access arguments' => array('Use registered mobile app'),
       'access arguments append' => TRUE,
       ...

add corresponding permissions in a my_module_permission() hook:
Code:

/**
* Access callback for the resource.
*
* @param string $op
*  The operation that's going to be performed.
* @param array $args
*  The arguments that will be passed to the callback.
* @return bool
*  Whether access is given or not.
*/
function _mymodule_api_access($op, $args) { ... }

And then return false if the mobile app is not registered...


How to show image in teaser of any content

Your sentence is not very clear but :

To display user's picture, add "author of the node" relationship to the view and "user picture" field, with the relationship.
To display post's picture, presuming it's in a distinct image field and not in the body, go to your display settings of your content type, in the teaser section, set the image as you want it to be displayed, it will then appear in your view.


How to make loadByProperties or entityQuery case sensitive for field value

It was this long issue thread, they add sensitive case support to entityQuery.
So instead of = operation you can use = BINARY or instead of LIKE you can use LIKE BINARY.
Try this:
$entity_ids = \Drupal::entityQuery('node')
  ->condition('field_myfield',$value, '= BINARY')
  ->execute();


Access denied for admin page, after moving site from sub-folder to root folder

Got it! I was using url as ?q=admin instead of ?q=user url.


$form_state['values'] empty in form _submit hook

Change property '#value' to '#default_value'.


Should I create a reference field or a third content type to represent a many-to-many relationship?

I know you won't like this answer but in general it depends:

What are your use cases when adding a new relationship? Is it more likely to add classes via students or the other way around? Or is it a migration process?

If UI is heavily used by both of the entites, I would give reference fields to both content types, and always update the other type reference field upon saving one type.

If this is more like for listing stuff (without editing on the UI these properties) and the information is coming from a big relationship list, then I would store it in a key-value table or a custom table.


Apply different css files according to user selection

I found the link bit helpful... It might help you too.
http://wearepropeople.com/blog/7-ways-to-add-custom-js-and-css-to-a-page-in-drupal


How do I set the language code for rendering in entity_view()?

I'd recommend looking inside of user_view() https://api.drupal.org/api/drupal/modules!user!user.module/function/user_view/7

That function should be called by entity_view() and it contains a drupal_alter() call. Print out the $build variable that goes into drupal_alter(). Is it using Japanese? Also print it out after the drupal_alter(). Is $build now back to English? If so, some other module is altering the display.


There are certain cases where db_query may not be able to do certain things, and this very well could be one of those cases.

That said, nothing is stopping you from leveraging PDO just like that blog post you linked to.

Here is an example from a project of mine in 2015 in Drupal 7 that performs a function using PDO:

/**
 * This takes the provided uploaded file and imports it directly into a temporary table in the database.
 * Drupal has some issues executing the statement, so the PDO class is leveraged with some different options to allow it without error.
 *
 * @param $table_name
 * @param $uri
 */
function populate_mysql_table_with_infile($table_name, $uri) {
  $database = Database::getConnectionInfo()['default'];

  $data_source = 'mysql:host=' . $database['host'] . ';dbname=' . $database['database'];
  $db_user = $database['username'];
  $db_password = $database['password'];

  $connection = new PDO($data_source, $db_user, $db_password,
    array(
      PDO::ATTR_EMULATE_PREPARES => TRUE,
      PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_PERSISTENT
    )
  );

  $statement = $connection->prepare("LOAD DATA LOCAL INFILE '" . drupal_realpath($uri) . "' INTO TABLE " . $table_name . "
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\r\n'
    IGNORE 1 LINES");
  $statement->execute();
  $statement->closeCursor();
}


How do you check to see what your drupal site looks like as different types of users?

For the anonymous user you will require a second browser (not logged in) or you will have to log out to view the changes. For other roles, check out the Masquerade module. It permits you to rapidly switch user roles by masquerading as a user with that role.


How can I add sort criteria for search api views?

I just discovered that if I re-index the fields (in this case, first name and last name) as strings, rather than the default fulltext, they are made available to sort on in views. This is great news.


A different template based on a taxonomy term in views

You can define each template by using template
page--taxonomy--term--xxx.html.twig
where xxx is your term id.

In your code, $term->getVocabularyId();
will return machine name of vocabulary, not the term id. It mean all term of this vocabulary will use this template.


How to display the data of a View in table format?

yes there us absolutely a way

go to any view->FORMAT->Format (unformated list) click on that see below for image
click on table format ->apply display

and enable label in all fields. will display it in table format


Database error when creating entities using hook_update_N

Similar to what Clive said, you will want to use the Database API (db_update, db_insert) or use an Entity Metadata wrapper.


The function signature is not right, which may be the reason for the code not executing.
See the docs for hook_user_login function.

The parameter $edit is passed by reference and not directly by value. So, the correct definition your function should be,

function custom_user_login(&$edit, $account) {

  // rest of the code goes here (not duplicating).

}

Also make sure, your modules name is custom and it has files custom.info and custom.module in the module directory. And offcourse, enable the module ;-)

Also, to suggest you to look into the session and cookie info (based on your comment), you can put an echo '<pre>';print_r($_COOKIE); echo </pre> inside your theme's template.php file.
Or simply install the Devel module, and enter dpm($_COOKIE); inside your template.php, to see a nicely formatted result. You'll need to clear the cache to again load the fresh template files.
Similarly, you can print the $_SESSION superglobal to see the session information.


problems with CKEditor install in drupal 7

It's an issue that happens from time to time.

The instructions that you see are fine:

  Extract the archive and copy its contents into a new folder in the following location:
  sites/all/libraries/ckeditor

  So the actual library can be found at: sites/all/libraries/ckeditor/ckeditor.js

If the issue is caused by the message "The version of CKEditor could not be detected." at admin/config/content/wysiwyg.

This solution helped me yesterday:

Open "\sites\all\libraries\ckeditor\ckeditor.js" file in a text
editor.
Add in the first line of the ckeditor.js file:

// version:'4.4.4',revision:'4391'

and save it.

You can get more help about this module on the documentation page.


Duplicate webform data to second database?

I wouldn't try to tackle this at the Drupal level to be honest, it'll be a lot more trouble than it's worth.

If it was me I'd just add a trigger on the webform table that runs a stored procedure to copy the data into the second database.

There might be something you can do with Replication, but I'm not sure if it's granular enough to go down to the table level.


How to resolve 'Unknown data property commerce_product' when adding a product in Drupal Commerce?

Looks like an answer to "this" question might be similar to what I suggested in How to add Drupal Commerce to an existing Drupal site?, which originally was rather a request for manuals/docu about this topic. It has a comment (from the OPer) like this (bold markup added here now):

  ... After your post I've uninstalled all modules and installed again and still had the errors, however this time when I run Commerce Repair the fields were fixed and everything worked.

With that it appears to me that "this" question "has an answer" now also.

Ps: The "Commerce Repair" module is "looking for a new maintainer", and used in over 1.000 sites. To me it appears as the best possible alternative to consider, which is not the same as "the module is no longer maintained" I believe (as I read in a comment to the question here).


In Views, use group type's image in a field when a group content type is fitered

You will need to setup a relationship between the "Group Type" and "Group Content" content types. If the parent > child relationship is determined using Taxonomy you can use the "Taxonomy: Parent Term".

Then you can add the field for the image which comes from the parent (make sure you change the relationship to the parent tax) and have it on the same row the as children.


Can we make 2nd field required only if 1st field is filled in a custom composite field?

You can do it with two ways

With Webform Custom Handlers.
With custom js.

I prefer you to go with the 1st approach I mentioned above. How to create and work with webform custom handlers is documented well on drupal.org's webform document. Attaching here for quick reference.

namespace Drupal\mys_module\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\Component\Utility\Html;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Webform validate handler.
 *
 * @WebformHandler(
 *   id = "my_module_custom_validator",
 *   label = @Translation("Alter form to validate it"),
 *   category = @Translation("Settings"),
 *   description = @Translation("Form alter to validate it."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class CustomValidatorWebformHandler extends WebformHandlerBase {

  use StringTranslationTrait;

  //We will overwrite the method validateForm, inherit from WebformHandlerBase.
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $this->validatePhone($form_state);
  }

  //We will define a new method to validate for example the phone.
  /**
   * Validate phone.
   */
  private function validatePhone(FormStateInterface $formState) {
    $value = !empty($formState->getValue('phone')) ? Html::escape($formState->getValue('phone')) : NULL;

    // Skip empty unique fields or arrays (aka #multiple).
    if (empty($value) || is_array($value)) {
      return;
    }
    if ($value > 9) {
      $formState->setErrorByName('phone', $this->t('Phone not valid.'));
    }
    else {
      $formState->setValue('phone', $value);
    }
  }
}

Enable it for your webform: The route to administer the handlers of a Webform is  /admin/structure/webform/manage/[your_webform_name]/handlers

The second way is to add javascript in assets section of the webform:
Route is: /admin/structure/webform/manage/[webform]/settings/assets

In the case of jQuery, I suggest instead of removing the required try adding it. As the property is configured in the webform element setting.


Print the image field in the node template like any other field:

{{ content.field_gallery }}

And then use a field twig to loop through multiple field items:

field--field-gallery.html.twig

 <div class="row expanded">
  {% for item in items %}
     {{ item.content }}
     {{ item.alt }}
    {% endfor %}
  </div>


Commerce add product attribute without adding new product variations

It appears I have been looking for Commerce Pricing Attributes. There is one SKU with a base price and I can manage the attributes and add a price modifier for each of them.

This screenshot from the module page explains it all:


To answer my own question, pixture_reloaded is the sub-theme I want to edit, as that is the last child/sub theme in the hierarchy.


3 vocabulary and taxonomies in this vocabularies

Your question is not well-asked but this is the answer:

Yes, you can have multiple vocabularies, multiple taxonomy terms in these vocabularies and also multiple child-terms in these taxonomy terms. It's one of the core functionality of Drupal.
Yes, the breadcrumbs can show the taxonomy hierarchy as you wanted but it depends on  the theme you use.
Yes, it's possible to show taxonomy terms in url with Pathauto module.


Best practice: Twig logic versus Preprocess functions

Best practice is documented in the node template. These are the two most important variables:
* Available variables:
 * - node: The node entity with limited access to object properties and methods.
 *   Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available. For example:
 *   - node.getCreatedTime() will return the node creation timestamp.
 *   - node.hasField('field_example') returns TRUE if the node bundle includes
 *     field_example. (This does not indicate the presence of a value in this
 *     field.)
 *   - node.isPublished() will return whether the node is published or not.
 *   Calling other methods, such as node.delete(), will result in an exception.
 *   See \Drupal\node\Entity\Node for a full list of public properties and
 *   methods for the node object.
 * - label: (optional) The title of the node.
 * - content: All node items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.

It clearly states that you should print the render array {{ content }} and use the object {{ node }} with its properties and methods to get the node data you need.


Soft and hard copies of a single product in Drupal Commerce?

After some more experimenting I have worked it out. For any sort of product variations you need to edit the Product reference field. Change the field to a select list and also make sure the you set the number of values to unlimited (or at least more than 1). This will then create a drop down list which when changed will switch between the different products within the same node. I hope that this helps!


Users field manually delete from database cache problem

I'm really not sure why you'd want to remove a column from a field table but just looking at your problem as is, a way by which you can disable caching of field values in the cache_field bin is by letting Drupal know that you don't want values for the field instances attached to a given entity type to be cached at all.

You can do this by implementing hook_entity_info_alter() from a custom module and setting the field cache key for the user entity as shown below:

function mymod_entity_info_alter(&$info) {
  $info['user']['field cache'] = FALSE;
}

You might find the documentation of hook_entity_info here useful. You might also want to lookup the definition of field_attach_load() from here.


Access / Alter user registration form submit button in $form variable

While UserLoginForm is a regular form based on form api, RegisterForm is an entity form, where the actions are defined in a separate method EntityForm::actions(), which is overridden in RegisterForm:

  protected function actions(array $form, FormStateInterface $form_state) {
    $element = parent::actions($form, $form_state);
    $element['submit']['#value'] = $this->t('Create new account');
    return $element;
  }

which you can override again in your extended class.


He Hui,

Currently the webform module does not provide integration of its submissions data with the views module.  You can see the status of this issue here: http://drupal.org/node/680386.  There is plenty of interest and work on the issue, but it is not functionality that currently exists.  By default, the only fields views will let you get to for the submissions are the sid, date created and a few others, but you can't get to the actual fields.

You can actually use additional modules to get to your webform submissions data in a round-about way, and there is lots of information online from folks who have made it work.  For Drupal 7, here is a sample post with instructions: http://drupal.org/node/1658784.  As you can see, you'll need three additional modules to get that functionality!

Hope this helps.


Merging duplicated nodes, and their fields

I have never heard of such functionality.

The first idea that comes to mind: Ctools has contexts for both Node view and Node edit. One could use such contexts to display two nodes side by side on a page, in either view or edit mode. With some custom form logic for picking, "left", "right" etc, on top; one could get very far in this.

Ctools also provides other niceties such as an object cache and a modal framework that could potentially be useful for developing this.


Is there any problem with downloading and overwriting modules?

You don't need to disable a module. That is often not even possible e.g. when there are many other modules relying on it and disabling them would break your site.

You might want to take your site to maintenance mode while running updates though, as your site might completely break between replacing the files and running update.php.

What however is recommended is to remove the old files first and then add the new directory. The reason for this is that you otherwise end up with stale files if files have been moved or deleted.

If you have shell access, I can strongly recommend using drush dl/up for this task as this will handle this for you automatically.


How can I create a views with right-join relationship?

I am not sure what you are getting at, but you might need to switch the chain around and start from the rightmost table and left join by not ticking the "this relationship is required".


Custom field doesn't show up in 'field type' dropdown

This does appear to have been a caching issue. The field has appeared now. weird.


Grant/refuse access permission on the fly

Yes. Look into this topic: Node access rights.

That's what you should do if you want the permissions to be respected in all contexts, including DB queries (except your own if you don't use db_rewrite_sql).

Another potential solution, assuming that you can get your existing setup to work with it, is Content Access. It can do per-user access control. The way I would do this is implementing hook_nodeapi's update operation and then programmatically configuring Content Access to match the list of users. Basically, the list of users would become a simplified admin interface in this approach. You would of course have to look at how Content Access manages this specifically (I know it uses the ACL module).

This approach should have all the benefits of the previous one, i.e. low-level security.

The poor man's way to do this would be to use hook_menu_alter and change access callback/access arguments to your own, where you'd load the nodes and do your fancy checks. This would only help on viewing, though, not on data retrieval. But it is probably easier than the other two ways if you don't need a perfect solution.


To see all of the hooks available to you, run your command with --show-invoke, like this:

$ drush status --show-invoke 2>&1 | grep mymodule
drush_mymodule_core_status_pre_validate
drush_mymodule_core_status_validate
drush_mymodule_pre_core_status
drush_mymodule_core_status
drush_mymodule_post_core_status

However, when we do this on node_export commands, we see no results.  Why is that?  Well, unfortunately, some commands do not go through the drush invoke hook process.  If you look at the definition of the node-export-import command, you will see this:

$items['node-export-import'] = array(
  'callback' => 'drush_node_export_callback_import',

In Drush's command.inc, there is this comment in the function drush_get_commands():

    // If command callback function name begins with "drush_$commandfile_",
    // then fix up the command entry so that drush_invoke will be
    // called by way of drush_command.  This will cause all
    // of the applicable hook functions to be called for the
    // command when it is invoked.  If the callback function does
    // -not- begin with its commandfile name, then it will be
    // called directly by drush_dispatch, and no hook functions
    // will be called (e.g. you cannot hook drush_print_file).

If a command provides a callback, then Drush calls that function instead of drush_command, so _drush_invoke_hooks is never called.  This means that, even though you named your hook function correctly, Drush will not call it, and you are stuck.

From here, you have two options:

Post an issue to the node_export issue queue, and request that they stop using the 'command' callback parameter, and let Drush choose the function name to call.  This will make hooks work again.  Using 'callback' is deprecated unless it is necessary (e.g. many commands calling the same function, such as drush_print_file), so hopefully the maintainers will be willing to do this.
Post a feature request to the drush issue queue, and request that Drush call the invoke hooks even if the Drush command uses the callback feature.  This is theoretically possible if the parameters to _drush_inovke_hooks were enhanced to include a replacement function name to call in place of the primary hook function.  This would have to be set up in drush_get_commands(), and then detected and uses in drush_command() where it calls _drush_invoke_hooks.  This didn't seem like a good idea at the time, but if it is common for contrib module maintainers to ignore subtle Drush conventions, it might be worthwhile to go to the extra effort to let folks hook their functions anyway.

Update:  I made a patch for you.  See: https://drupal.org/node/2041109.  You might still want to do #1, as I don't think that we will necessarily backport this enhancement to Drush 5.

Update 2: Above-referenced patch has been committed to Drush-8.x-6.x-dev.  This happened after the rc1 release, but it will be in the next release.

Update 3: This is now available in Drush-8.x-6.0-rc2.


You're missing #options property in your tableselect element, e.g.

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
);

See: Adding checkboxes to a table.


Show multiple drupal 7 'name field' in one view row?

The views aggregator plus module solved my problem https://www.drupal.org/project/views_aggregator


How to check whether \Drupal\Core\Archiver\Zip::extract() succeeded?

The Drupal Zip class is just a wrapper around the PHP ZipArchive class.

As @tenken already mentioned the wrapper just returns itself:

  /**
   * {@inheritdoc}
   */
  public function extract($path, array $files = []) {
    if ($files) {
      $this->zip->extractTo($path, $files);
    }
    else {
      $this->zip->extractTo($path);
    }

    return $this;
  }

I guess that your best option is to retrieve the ZipArchive object itself via the getArchive() method of the Zip class. On the ZipArchive class call the extractTo() method and check its output (TRUE or FALSE).

I am currently working on a rewrite of the archiver classes to use PharData: https://www.drupal.org/node/2891871. The PharData class throws exceptions on failure. If this issue is done and the patch lands you are able to catch exceptions to check if the archive operations were successful.


How do I show webform component labels in a chart using Views chart format?

Module involved

About your PS:

  ... not sure which module page I should log an issue, so any pointers on how to patch the relevant project would be appreciated.

No doubt possible: Charts.

Using tooltips

It sounds to me that you should have a look at Pass library-specific options via existing #raw_options, which already provides a solution (using #raw_options) to what you're trying to get to work (ie: "tooltips"). For charting engine Highcharts it's already supported (and committed to the most recent dev version, which is the version I recommend), while for charting engine Google Charts (which you are using) you'd need to apply the RTBC-patch attached to comment nr 9. Obviously, after that patch is committed, using the #raw_options will continue to work (for either charting engine). And rest assured, this patch will (not might ...) make it.

With this #raw_options solution, Charts has a solution for using options that are specific for either of the supported charting engines (Google Charts or Highcharts). While still not deviating from a key design concept of the Charts module, which is that all supported charting options should work for either charting engines (you should be able to easily swap from one to the other charting engine, without your charts being affected).

Notes:

Apart from Webform Chart (without s), there is also Webform Charts (with s). The results you'd get are probably going to be similar, because both modules use Charts.
Drupal 7.50, which you are using, is the most recent Drupal version, but still your screenprint includes that (red) error msg with "There is a security update available for your version of Drupal"... bizarre ...

Disclosure: I'm a co-maintainer of the Charts module.


As a developer who has worked extensively with both Drupal and Wordpress I have to say that the convenience of Drupal's relative URLs outweighs the (apparent) accuracy of Wordpress's absolute URLs.

When moving a site from dev > staging > production a Wordpress site's URLs and image references have to be replaced in the DB, this can create an absolute mess.
Rather than creating links between pages as hyperlinks a good Drupal setup uses entity reference and entity embed, so if the path or URL of a file changes the page's source is still correct.
Wordpress feeds are natively better as the URLs are natively absolute, Drupal views feeds can be made to use content filters to make links absolute.
In Drupal I like to use a module called pathologic to set absolute URLs in the rendered source, the stored source however remains free of site domain.
Performance hit of content filtering is negligible on Drupal and there are multiple layers of caching.

Hope that answers some people's questions if they arrive here.


Commit doesn't show up in profile on Drupal site

Commits submitted in the issue queue are only counted when the maintainer accepts them and credits you with the patch.  Otherwise, people could just spam useless patches through drupal.org to increase their commit counts.


Group entitiy queries for a specific content type using Taxonomy Term

Ok well here we go if i understand you correct you want nodes linked by a entity reff field value:
in your example "field_group_sched" the see the below condition
but later you can just group stuff by anything you want

   // this is the known term id.
    $group_term_id = 1;
    // for Entity ref use field_name.target_id
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1, '=')
      ->condition('type', 'schedule')
      ->condition('field_group_sched.target_id', $group_term_id, '=')
      ->sort('created');

    $entity_ids = $query->execute();
    if (count($entity_ids) != 0) {
      $entities = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadMultiple($entity_ids);
      // dump($entities); // requires var dummper
      if (count($entities) != 0) {
        $group1 = [];
        $group2 = [];
        // then you can play with order or whatever you want here.
        foreach ($entities as $node) {
          // These are the loaded nodes;
          $title = $node->getTitle();
          $field_name  = $node->field_schedule_name->value;
          // if the schedule_name is "beer" put in to group 1
          if ($field_name == 'beer') {
            $group1[] = $node;
          }
          else {
            $group2[]= $node;
          }
        }
        // SEND your Nodes to the template here.
      }
    }


How to disable Toolbar on certain pages / theme?

page_top and page_bottom are still available, but on html.html.twig. template_preprocess_html() initializes those variables with the following code.

  $variables['page_top'] = NULL;
  if (isset($variables['html']['page_top'])) {
    $variables['page_top'] = $variables['html']['page_top'];
    unset($variables['html']['page_top']);
  }
  $variables['page_bottom'] = NULL;
  if (isset($variables['html']['page_bottom'])) {
    $variables['page_bottom'] = $variables['html']['page_bottom'];
    unset($variables['html']['page_bottom']);
  }

Since toolbar_page_top() uses the following code, I take you can use hook_preprocess_html() to avoid the toolbar appears.

  $page_top['toolbar'] = array(
    '#type' => 'toolbar',
    '#access' => \Drupal::currentUser()->hasPermission('access toolbar'),
    '#cache' => [
      'keys' => ['toolbar'],
      'contexts' => ['user.permissions'],
    ],
  );

Bear in mind that a note on Added hook_page_attachments(_alter)() and removed hook_page_build/alter() says:

  You no longer can change $page['content'] (or, generally speaking, $page[$region_name]) into something completely different.


How do I alter the Price Component Title in Commerce Userpoints Discount without altering the module?

The implementations of hook_commerce_price_component_type_info() are invoked from commerce_price_component_types(), which uses the following code.

  // If it did not exist, fetch the types now.
  if (!isset($component_types)) {
    // Find components defined by hook_commerce_price_component_type_info().
    $component_types = module_invoke_all('commerce_price_component_type_info');

    // Add default values to the component type definitions.
    foreach ($component_types as $name => &$component_type) {
      $component_type += array(
        'name' => $name,
        'display_title' => $component_type['title'],
        'weight' => 0,
      );
    }

    // Allow the info to be altered by other modules.
    drupal_alter('commerce_price_component_type_info', $component_types);
  }

As with other hooks, if you want to alter what an hook implemented from another module returns, you need to implement an alter hook.

In your case, the code should be similar to the following one.

function my_module_commerce_price_component_type_info_alter(&$component_types) {
  if (isset($component_types['userpoints'])) {
    $component_types['userpoints']['title'] = t('My Userpoints Currency');
    $component_types['userpoints']['display_title'] = t('My Userpoints Currency');
    $component_types['userpoints']['weight'] = 2000;
  }
}

Generally speaking, this is only possible when the module using the hook is also calling drupal_alter(), such as in this case.


Redirect User: Delay + Intermediate page

Before the goto call you can add
   drupal_set_message( $message, $status);

Its the more straightforward solution, although the message will be displayed inside the login page and there wont be any delay.

Or just change the goto path to a custom... 'user/sorry' page with your message, and something like:

and a JavaScript function

function myRedirect(){ window.location = "user/login"; }

Add the standard "if you are not redirected, click here" link in case JavaScript is disabled.


User must click Back button twice after adding item in cart

While, not an specific answer. Just to point out another possibly cause, this could be caused by JS.

https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries

Basically, there are ways of modifying the history via JS. There might be some code somewhere that's introducing this. Not sure which module though.

Assuming JS, what you probably should look into is calls to,

 history.pushState()
 history.replaceState()


Rules: How to check one field against same field on all other nodes of that contenttype?

You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed below.

In what follows, I'm assuming that the machine name of your field is field_address (change to whatever fits).

Step 1 - Create a VBO view

Use the Views Bulk Operations (VBO) module to create a view of all relevant nodes, in which you should:

Add a VBO field to it.
Add a contextual filter for the field_address field for which you want to check that its value is unique. Make sure to correctly configure this contextual filter, similar to what is mentioned in this answer to "How to have a field that counts the nodes submitted by the current user?" (credits to Niall Murphy, merci!).

Include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Here is an export of such VBO view:

$view = new view();
$view->name = 'relevant_nodes';
$view->description = 'Produce a list of node ids that satisfy a specific filter';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Relevant nodes';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Relevant nodes';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Address */
$handler->display->display_options['fields']['field_address']['id'] = 'field_address';
$handler->display->display_options['fields']['field_address']['table'] = 'field_data_field_address';
$handler->display->display_options['fields']['field_address']['field'] = 'field_address';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
/* Contextual filter: Content: Address (field_address) */
$handler->display->display_options['arguments']['field_address_value']['id'] = 'field_address_value';
$handler->display->display_options['arguments']['field_address_value']['table'] = 'field_data_field_address';
$handler->display->display_options['arguments']['field_address_value']['field'] = 'field_address_value';
$handler->display->display_options['arguments']['field_address_value']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_address_value']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['field_address_value']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['field_address_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_address_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_address_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_address_value']['limit'] = '0';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'relevant-nodes';

Step 2 - Create a Rule

Create a rule like so:

Rules Event: something like "Before saving content of type Article" seems most appropriate, though you can use any variation that fits.
Rules Condition: "Check number of results returned by a VBO view". And select the VBO view created in the previous step. In doing so, you will be asked to "specify arguments to pass to the view, one per line. You may use token replacement patterns.". The token to be entered there is node:field-address. If the number of results is 1 or more, then you know the value already exists. So within Minimum number of results you should enter the value 1.
Rules Action: this is pretty much up to your own imagination (your question doesn't specify what should happen ...). For example if the Rules Condition is TRUE, you could use "Set a data value", to set the value of that field to whatever fits. Maybe also display an appropriate message, such as (when trying to set the value to HomeIsWhereMyStellaIs):

  The value "HomeIsWhereMyStellaIs" has already been used in at least 1 other node ...

Here is an export of a Rule that does (without such "Set a value" though) what is described above (if you have the Rules UI enabled, and a field with the machine name field_address, you should be able to just import this rule):

{ "rules_prevent_multiple_nodes_with_same_field_value" : {
    "LABEL" : "Prevent multiple nodes with same field value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "views_bulk_operations", "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "views_bulk_operations_condition_result_count" : {
          "view" : "relevant_nodes|page",
          "args" : [ "node:field-address" ],
          "minimum" : "1"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "The value \u0022[node:field-address]\u0022 has already been used in at least 1 other node ...",
          "type" : "error"
        }
      }
    ]
  }
}

Note that my Rules Event is limited to "Article" (change to whatever fits), and replace (prior to trying to import this rule) the machine name of field_address to whatever other machine name your field.

Done!

PS: I'm assuming this is about D7.