group same fields in views using custom template

Go to your view: admin/build/views
Edit your view: admin/build/views/edit/view_name
Look at your fields node title (field_title) and node author (field_author) and click on Node:Title for instance
Once editing the view output of the Node:Title field, check "Rewrite the output of this field"
You should see replacement patterns: [title] == Node: Title

In the Rewrite this field section called "Text:" enter

[title]

Repeat 3,4 and 5 for the Node:Author field.

[author]

You can put anything else in the rewrite field here.

(note: D7 has more options that using the rewrite method)


Why a unnamed  is added to a specific region?

It could be coming from region.html.twig:

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21region.html.twig/8.2.x


Why my theme suddenly gone blue after an update?

Check the css with your browser's inspector and see what elements are surrounding this behavior.  Is this occurring for all users (admin to anonymous)?

Does this happen in all regions or just the "highlight" region?


Autopopulate a different field if node reference autocomplete doesn't have a matching candidate?

After some poking around and asking on the Drupal forum, I've found that there's a module that does pretty much what I want


How can I make URL Alias required when creating new content

The easiest solution is to use the pathauto module. If the user does not touch the URL path alias field, pathauto will automatically generate a URL for the node based on the node title.  Other configuration options are available.  The user may still uncheck the pathauto checkbox and type in a specific URL for their new node.

Update:

If the URL format is built from fields or metadata in the node that is created, pathauto can do that for you automatically through its pattern configuration page. For example, I have one content type with a pattern [node:field-gender:name]/[node:field-era:name]/[node:field-genre:name]/[node:field-item-type:name]/[node:title] to create four levels of nesting in the URL based on field values entered. If the user does not have the permission to create and edit url aliases, they will be stuck with the pattern pathauto provides.

If you want to allow users to also edit the URL, you could validate the field from hook_node_validate. I don't know if there is a way to do node validation with rules.

Update 2:

If you have a field called "tag" that is a taxonomy term, then [node:tag] will return all of the terms in this field, concatenated together, and [node:tag:1] will return just the first taxonomy term.  In both cases, spaces are converted to dashes.


Custom user_register_form for Auto Assign Role registration pages

I think if you already have a template file for the form user-register-form.tpl.php, you should be able to use a preprocess like this:

function MYTHEME_preprocess_user_register_form($vars) {
  // if role2
  // use other theme
}

There should be no need to define your own themes with hook_theme


Getting menu links: correct chain of API functions

Since you're using menu_link_get_preferred() I'm guessing Drupal 7 here...

Theme functions have changed, and parameters now need to be named in an associative array passed to the theme function. So per the theme_menu_link() docs:

$html .= theme('menu_link', $menu_link);

becomes

$html .= theme('menu_link', array('element' => $menu_link));


User relationship one way relation block and unblock option

This feature does not currently exist, you can not implement it without hacking the module.

There are feature requests open for this, I suggest have a look at these:

http://drupal.org/node/203364


theme_table() isn't respecting sortable fieldname

You're doing too much work.

For sorting:

$query = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('uid', $user->uid);

$sort_query = $query->extend("TableSort")->orderByHeader($headerColumns);
$records = $sort_query->execute();

Using the TableSort extension will simplify things immensely.


How to alter node load system to make it possible for only one field is attached to a node?

After a long research, found a solution :-)

You can do it using views module and views_field module. Follow below steps to achieve the solution without doing a full node load or full field items load so that you can achieve the performance you are looking for !

Install views module
Install views_field module
Go to the body field settings page and enable the base table by checking " Expose as base table" checkbox.
Create a new view with base table as "Field Body" while creating a new view in show dropdown.
Remove fields in the field list
Set the path as node/%/body/%
Add field "Field Tables: Body > value"
Add contextual filter "Field tables: field_body => Entity id" and set default value as "Raw Value from URL" and Path component as "2"
Add one more contextual filter as "Content: Body:delta" and set default value as "Raw Value from URL" and Path component as "4"

That's it !! It worked for me !!

By implementing above solution, views module directly queries body table with delta and entity id as filters and get's the body value which you will be looking for without loading full node or field body items !!


How to changing Bartik's "Show - Main navigaton" mobile menu message?

You can translate following strings through the core translation system (admin/config/regional/translate):

Show &mdash; @configuration.label
Hide &mdash; @configuration.label

The strings above are defined in block--system-menu-block.html.twig at line 17 and 18.

Furthermore you should translate/rename your Main menu name.


Coming from Drupal 7, which files should I be versioning with git in Drupal 8 projects?

Drupal comes with an example .gitignore file, just rename "example.gitignore" to .gitignore and you have a pretty good starting point. It also comes with a lot of explanations.

Many of your questions go way beyond just answering that should be added to get, there are also some different opinions.

Yes, put your modules in /modules and so on, it's a lot easier to work with.
Whether or not to commit /vendor depends on your deployment process. if you deploy your git repository directly and have no intermediate deployment process, you probably still want to commit the vendor directory. There are various alternatives, starting from just building an archive yourself and deployment that, to automating that with scripts/build tools to using solutions like platform.sh that run composer install automatically for you. If you use any of those, you likely want to ignore vendor as the example .gitignore file does by default.
It's also common practice to have a settings.local.php and add settings.php to git, see instructions in settings.php at the end.
I don't understand your repo.git and repo folder examples. It's not more complex than in Drupal 7, just different folders.
Yes, you probably want to move your config folder out of files (you need to update the path in settings.php) and commit it. You shouldn't only have one environment, and config allows you to make changes on one site, export it and import it on production. There are many questions here and documentations about this available.


Memcache module is working but with a strange error

"Not supported" doesn't necessarily mean that it shouldn't work at all. I guess in this case it only means you shouldn't complain in case something breaks.

You may want to check if you can install a newer version of Memcache on your platform, just to be sure and future-proof.


Ok, found it.

If one includes this code, it will prevent all items with a class "tabledrag-parent-locked" from being dragged into another group, while still being orderable with their siblings.

This code uses a CSS class of 'parent' to target the parent relation field. The actual CSS class would obviously depend on what CSS class you pass to drupal_add_tabledrag().

/**
 * @file
 * Override some Tabledrag functionality.
 */

/**
 * If the dragged row has a class of 'tabledrag-parent-locked', check the rows with which it might get swapped.
 * If the row it gets swapped with has a different  parent, block the swap by returning false.
 * This will prevent the locked child from being dragged to another parent.
 *
 * @override Drupal.tableDrag.row.isValidSwap
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype.row.prototype._isValidSwap = Drupal.tableDrag.prototype.row.prototype.isValidSwap;
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(row) {
  if (this.indentEnabled && $(this.element).hasClass('tabledrag-parent-locked')) {
    var nextRow;
    if (this.direction == 'down') {
      nextRow = $(row).next('tr').get(0);
    }
    else {
      nextRow = row;
    }

    if (nextRow && $('.parent', this.element).val() !== $('.parent', nextRow).val()) {
      return false;
    }
  }

  // Return the original result.
  return this._isValidSwap(row);
}

/**
 * If the dragged row has a class of 'tabledrag-parent-locked', disable the indentation for the duration of
 * the drag. Store the old indentation setting in _indentEnabled.
 *
 * @override Drupal.tableDrag.dragRow
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype._dragRow = Drupal.tableDrag.prototype.dragRow;
Drupal.tableDrag.prototype.dragRow = function(event, self) {
  if (self.rowObject && $(self.rowObject.element).hasClass('tabledrag-parent-locked')) {
    if (self.indentEnabled) {
      self._indentEnabled = true;
      self.indentEnabled = false;
    }
  }

  return self._dragRow(event, self);
}

/**
 * Restore the original indentation setting, if needed.
 *
 * @override Drupal.tableDrag.dragRow
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype._dropRow = Drupal.tableDrag.prototype.dropRow;
Drupal.tableDrag.prototype.dropRow = function(event, self) {
  if (self._indentEnabled !== null) {
    self.indentEnabled = true;
    self._indentEnabled = null;
  }

  return self._dropRow(event, self);
}


Validate and submit functions not calling on template.php

The hook hook_form_FORM_ID_alter does not return a variable. The $form variable is passed by reference so it can be modified inside the alter hook.

Remove the return $form; line from your mymodule_form_user_register_form_alter function.

Make sure you clear your cache after code changes to any of those functions.


You should be able to use the taxonomy_get_tree function to get all the children of the term, and then just run a foreach() on that.

Example:

function mymodule_blah($vocabulary) {
  $terms = taxonomy_get_tree($vocabulary);

  foreach ($terms as $data) {
    $output[$data->tid] = $data->name;
  }

  return $output;
}

This should return an array keyed by Term ID, although you could put whatever you want where it says $data['tid'] to put a different key in.

Example output:

[1] => ['My First Term']
[2] => ['My Second Term']
...
[15] => ['My Fifteenth Term']

Then pass this to your '#options' on your select box.

EDIT:

Forgot to mention that the helper function will need the vocabulary ID passed to it - should have added in the clarification just for completeness' sake.

EDIT 2 (full implementation):

function mymodule_myform($form) {
//The rest of your form stuff is in here
$form['status']['currentStatusList'] = array (
    '#title' => 'current status',
    '#type' => 'select',
    '#options' => mymodule_selectbox_contents(PUT THE NUMERIC VOCABULARY ID HERE)    ,
);
//The rest of your form stuff is in here
}

function mymodule_selectbox_contents($vid) {
  $terms = taxonomy_get_tree($vid);

  foreach ($terms as $data) {
    $output[$data->tid] = $data->name;
  }

  return $output;
}


How to disable cache for a specific content type?

You need to set max-age 0 in e.g. hook_node_view().

function yourmodule_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  if ($node->getType() == 'yourtype' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }
}

That said, I recommend you find a way to make caching work. There are concepts like lazy_builder that allow you cache most of a node and only dynamically build a small part in it.

Also note that this does not disable the page cache for anonymous users. If you need that too, which I would recommend even more to try and avoid, then you also need:

\Drupal::service('page_cache_kill_switch')->trigger();

Update, answer is getting too long to post in a comment:

Ah, flag. How do you hide the flag for the author? Are you using the latest D8 and flag version?

If you look at flag_entity_view(), you can see that flag is already doing exactly that. It registers a so called lazy builder and enables a thing called placeholdering. It does that to show a flag/unflag link depending on the user. You probably just set #access on that element right now.

Flag is supposed to have access hooks but I think they don't work right now. See https://www.drupal.org/node/2584299. Follow that issue, once that is resolved, you can just implement that.

But for now, you can just switch out the lazy builder callback there with your own for now that does your additional check and then does what the existing one does. And it will just work.


Programmically displaying imagecache presets no longer works

I discovered that the problem in this particular case is that the imagecache 6x-2.0rc1 module has a regression bug in it. Reverting to the previous version restored the functionality and everything works as it should. Hopefully this will be fixed with the next release of imagecache.


What is the template file for node add/edit page?

The template for the node add form is node-edit-form.html.twig. But adding attributes to form fields is not an easy task in twig. You probably are able to do this more efficient in a form alter hook.


Is there a way to prevent a user from seeing a field on their user profile page?

Is this possible?

Yes, but not out of the box with Drupal.

  I'd prefer not to use a module.

Not an option unfortunately, you need either a contrib or custom module to make this happen. You could theoretically do it in the theme, but that logic doesn't belong there.

Field Permissions is the go-to module for this.

Ah, just noticed your edit.

If you want the field to simply not be rendered, but you're happy for it to exist in the edit form, you can override the user-profile.tpl.php template in your theme, and just hide the field there:

<?php hide($user_profile['foo']); ?>

Or just hide it through the UI at admin/config/people/accounts/display if that works for your scenario.


Can I remove the "Item successfully added to your cart" popup?

Goto: /admin/config/workflow/rules
and disable 'Display an Add to Cart message' Rule.

Thank You.


I found the answer. It is done using the hook_field_access. In my case, what I did was:

function my_module_field_access($op, $field, $type, $entity) {
    if ($op=="edit" && $field["field_name"]=="my_field") {
        if (!user_access("administer users"))
            return FALSE;
    }
}


How to change the author and date of a new comment before posting it?

Author
For changing the author (not the date), you might be able to use the Masquerade module for this. Some details from its project page:

The Masquerade module allows site administrators (or anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time.
This is helpful for site developers when trying to determine what a client, logged in as themselves, might see when logged into the site.
The masquerade module is designed as a tool for site designers and site administrators. While masquerading, a field is set on the $user object, and a menu item appears allowing the user to switch back. Database log (watchdog) entries are made any time a user masquerades or stops masquerading as another user.

So just switch to the appropriate user before filling in your forms, that should do what you're trying to achieve.
PS: works for any currently supported release of Drupal.
Date
Not sure (yet) about how to do this, but I'd try to use the Rules module for this. Here is a prototype of a rule that you may want to look at and experiment with:
{ "rules_update_comment_post_date" : {
    "LABEL" : "Update comment post date",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_presave" : [] },
    "DO" : [
      { "data_set" : { "data" : [ "comment:created" ], "value" : "-1 day" } }
    ]
  }
}

This rule should set the actual comment date to "current date - 1 day". Just as a sample. Adapt the value to fit your needs (before posting each comment, sorry ...), or try to think of an enhanced version of it to somehow retrieve the comment date as part of this rule.


Call internal pages with drupal_http_request

Here is what I'm using in a similar situation, with $base_url as Baysaa mentioned above.

$path_to_file = '/path/to/feed.xml';
$base_url = $GLOBALS['base_url']; // Not sure if this line is necessary.
$file_over_http = $base_url . $path_to_file;
$http_result = drupal_http_request($file_over_http);


Making title unique using hook_entity_bundle_field_info_alter()

This hook only runs with a cold cache.
In Drupal 8 validation is done with plugins.

When this hook runs for the node entity type, you will have an array of fields, one of which is title. You need to define a new validation constraint plugin. Model it on the unique feed title or unique username one and that way you'll only have to write one method and a property or two.
Take note of your plugin's ID. When you're in that hook, call addConstraint on the title field, passing your plugin ID.

I have a feeling there's another hook too, maybe hook_entity_base_field_info_alter, but I could be wrong there. If you don't see title in the field list, check the api docs for a hook with base field in the name


Creating one view for taxonomy page teasers so I don't have a ton of views

When you have the taxonomy and views module enabled you should see a couple of disabled views and one of them is a view that format the taxonomies pages and their XML feed. Enable them and you will be able to play with them as need it.

See image below:


Simply find the module name, and write the following command in your command-line/terminal/console to disable the module at first (by considering that the current path in your command-line is the Drupal project root directory):

drush dis moduleName -y

then after the completion of the executing the above command, write the following command to uninstall the module:

drush pm-uninstall moduleName -y

If you have several modules, you can list their names. For example for three modules, you can write:

drush dis moduleName1 moduleName2 moduleName3 -y
drush pm-uninstall moduleName1 moduleName2 moduleName3 -y


The Form API gives checkboxes names that include their options key. So your :input needs to be slightly adjusted to

':input[name="check[1]"]' => array('checked' => TRUE),


Incidentally, I got this error yesterday ;-) And after a bit of searching and looking into the documentation, I found that the cause was the functions which loads entities in Drupal and with the name like something_load(e.g. node_load()). I was using node_load() function to load the node and then delete it using node_delete_multiple().

This error was caused because, I was passing array as an argument to node_load(), by something like user_load(array("...; which is not the right way to do it.
The argument to anything_load() function must be a single id. So, you can search for the _load functions which uses array as an argument in your code.


Have you tried https://localhost/oauth2/authorize ? That is the authorization start point for me.


It turns out this has something to do with the "WYSIWYG filter" under text formats (admin/config/content/formats). Disabling this gave my non-breaking space back. You would probably want to adjust the configuration rather than just turning it off.


How to display an image field next to the title on the profile pages?

The use of the template is solid guess. However, you're using the wrong template. The template you suggesting isn't based on the page.tpl.php page. The output of the user-profile.tpl.php page, will end up in the $content section of your page template.
You should try to use a different approach.

How about a preprocess function? It will intercept the rendering of the variables and by so, you can alter them. If you want to change the title of your user-profile page, I'ld go with something like this:

/**
 * Implements hook_process_page().
 */
function mymodule_process_page(&$vars, $hook) {
  // Load the global user object
  global $user;

  // Check if it's the userpage and the current user, depending on URL
  if ((arg(0) === 'user') && (arg(1) === $user->uid)) {
      $vars['title'] .= ' ' . $user->avatar[LANGUAGE_NONE][0]['value'];
  }
}

Above preprocess function should be placed in your preprocess folder of your theme or the template.php.
It will extend the existing title with your extra fieldvalue.

There is only one drawback on this implementation. If you have a page with a path like /user/overview, the title will change too. Every URL with user as first argument and a UID as second, will be altered...

Goodluck!

EDIT:
Try this please and let me know how it went:

/**
  * Implements hook_process_page().
  */
function mymodule_process_page(&$vars, $hook) {
    // Load the global user object
    global $user;

    $image = array(
      '#theme'  => 'image',
      '#path'   => file_create_url($user->field_avatar[LANGUAGE_NONE][0]['uri']),
      '#width'  => 20,
      '#height' => 20,
    );

    if ((arg(0) === 'user') && (arg(1) === $user->uid)) {
      $vars['title'] = render($image) . $vars['title'];
    }
}


drush sql-sync fails with PHP Fatal Error

First you run this command on console. if command is run successfully after then you check your drush library, I think this is drush library problem.

Second is you can try other command like :-

drush ard


Drupal Rooms module is a perfect solution to this. It is a booking and room management solution for hotels, vacation rentals and B&Bs. It integrates directly with Drupal 7 Commerce.


How to modify the Drupal Solr Search fields / apply custom fields / modify results

I think that you may find that the Apache Solr Views module will do what you are wanting fairly well.


You can do it with the built-in text filter named "PHP Code".  To get access to this, you need to first enable the core PHP Filter module (in core, but disabled by default).  Then navigate to Home » Administration » Configuration » Content authoring  » Text formats and allow the Administrator to use the filter named "PHP code".

Now the Administrator can create nodes that use the PHP include statement to embed static HTML pages in Drupal nodes. For example, to import a static HTML page located in the Drupal root named static.html, create a Basic page node with this contents:

<?php include $_SERVER['DOCUMENT_ROOT'] . '/static.html'; ?>

and set its text format to "PHP Filter".

Note that the "PHP code" text filter allows arbitary PHP to be embedded into nodes, so make sure that only highly trusted users have access to this filter.


Dynamic results label for Views with Taxonomy Filters

Your question doesn't seem to be related to Better Exposed Filters, BEF only format the actual form elements of the exposed form, not the display of the view results.

You can use the Result summary option you can add to the Header or Footer area in Views. It's under the Global Category, here are the listed tokens:

You may use HTML code in this field. The following tokens are supported:

@start -- the initial record number in the set
@end -- the last record number in the set
@total -- the total records in the set
@label -- the human-readable name of the view
@per_page -- the number of items per page
@current_page -- the current page number
@current_record_count -- the current page record count
@page_count -- the total page count

You can also use the Text area option that comes with some more options, including the arguments from Contextual and Exposed filters (if you turn on the Use replacement tokens from the first row):

view

[view:base-field] - Base field: The base field used for this view.
[view:base-table] - Base table: The base table used for this view.
[view:current-page] - Current page: The current page of results the view is on.
[view:description] - Description: The description of the view.
[view:id] - ID: The machine-readable ID of the view.
[view:items-per-page] - Items per page: The number of items per page.
[view:label] - Label: The label of the view.
[view:page-count] - Page count: The total page count.
[view:title] - Title: The title of current display of the view.
[view:total-rows] - Total rows: The total amount of results returned from the view. The current display will be used.
[view:url] - URL: The URL of the view.

In your case you're filtering by Taxonomy Entity Reference field (that information is directly in the node). But the ER fields only store the ID number of the referenced entity (TID in your case) and not anything else, which mean the Taxonomy term name isn't saved inside the node.

There is some magic done in Views for Taxonomy that makes it seem like the term data is available but those are targeted specific parts. Generally speaking you have to add a Relationship for that ER field in order to pull in data about the referenced entities.

So in you case you need to add the Relatinship for the Color and Size (how ever you have them called), and then add the Taxonomy: Name field for both cases.

Now when you open the Use replacement tokens from the first row option you will see the tokens for those fields that show term Names more directly, something like {{ name_1 }} == Taxonomy term: Name.

You will probably want to use some twig logic when to show it, check for Exposed filter being used.


Is custom coding faster than Rules when reacting on user creation?

I wouldn't focus too much on speed in situations like this because it's extensibility you will care about as the site grows in function. While your custom code is probably "faster" it's not the measure you should be deciding by since it'll be nanoseconds you're talking about and any good caching strategy will nullify most of that concern.

But to answer your question, your code would likely be faster especially if you're not defining as many hooks as the Rules module.

However, I'd advise using rules for the following reasons.

Rules are exportable
Rules are integrated with all the "big" modules out there.
Never program something you can borrow. :)

Hope this helps.


One of the best ways to keep this information in code is to use features. Feaures can put into code:

Content types
CCK fields
Permissions
Roles

The list goes on.

One nice feature about features is the drush integration

drush features will give you a list of all features on the site, and their status
drush features revert all will revert all features back to what is in code (really handy for running after deployments)

Help this helps


Is there is any module which creates new users by reading a spreadsheet/excel file?

Try out the user import module

  Import users into Drupal, or update existing users, with data from a
  CSV file (comma separated file). Provides a wide range of features out
  of the box, and a comprehensive API to customise imports.


How to send mail with third party domains?

It is possible to send email via SMTP using Outlook's SMTP server. Make sure you have set Swiftmailer to send mail via SMTP.

SMTP server: smtp-mail.outlook.com or smtp.office365.com
Port: 587
Encryption: TLS

Use your Hotmail address and password to log in. You'll probably need to enter your Hotmail address under "Configuration" -> "Basic site settings".

Your web hosting provider may block outgoing SMTP ports. Check with their support to make sure.

More information:

https://support.office.com/en-us/article/POP-IMAP-and-SMTP-settings-for-Outlook-com-d088b986-291d-42b8-9564-9c414e2aa040
https://docs.microsoft.com/en-us/exchange/troubleshoot/send-emails/smtp-submission-improvements#new-behavior-when-submitting-messages


By the documentation, you should return content you want in block, not echo it.

$block['subject'] = t('Subject'); // String here
$block['content'] = t('Content'); // Array or string here
return $block;


How to set cache meta data on drupalSettings?

When you add attachments you can add cache data as well:

$attachments['#cache']['tags'][] = 'config:my_module.settings';

BTW #attached and #cache are the only data you are allowed to add in hook_page_attachments() or hook_page_attachments_alter().


I believe that good start is to implement EventSubscriber listening on ProductEvents::FILTER_VARIATIONS event. It was introduced to filter out some product variations based on different aspects, such as stock, date, etc.


How to control field_group quantity - control field group quantity

Field group is used for purely cosmetic purposes. If you want to enable the functionality you describe, use Field Collection.


Dynamic Field Adition / Subtraction using FAPI

if (!isset($form_state['values']['number_subscribers'])) {
   $form_state['values']['number_subscribers'] = 0;
}

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}

You should add '#tree' => TRUE on your form, it will be easier to extract the form values afterwards


From showcase website to e-commerce website

In order to do that, here is what I did :
 - install Drupal Commerce
 - create the product (name, ref and price)
 - and add the product reference field to the existing product

If that can help...


The easiest way is through CSS.

body.front .your-menu .list-item-identifier {
  display: none;
}


What are functions that start with 'hook' used for?

hook_action_info and other functions that begin with hook_ exist only to document the contract between the caller of the hook and the module that implements it.


Is it possible to serve a theme from outside the web root?

If you have

Options +FollowSymLinks

set for the DocumentRoot for your Drupal site, you can put the proprietary theme anywhere you want as long as you create a symlink to it somewhere Drupal searches for themes (eg, sites/all/themes).

Just keep in mind that Apache needs to be able to read it.  Whether the client can read it directly is a permission issue, but if Apache can read it a savy client can get it via custom PHP.


Entity print get variable in twig template

Looks like you need to review Entity Print in Drupal 8 again. I am using the Entity Print module and it works just fine. Here are some pointers I would recommend below. Your original post is regarding printing node variables in twig templates

On your content type, navigate to Manage Display-->Expand Custom Display Settings-->Enable PDF. This will create a PDF view mode (which is used for printing)
Create a twig template node--article--pdf.html.twig (replace article with machine name of your content type)
Update your_theme.info.yml and your_theme.libraries.yml as suggested in Entity Print in Drupal 8 so you can control the theme and assign a css file only for print
Copy and add entity-print.html.twig to your subtheme
Using node--article--pdf.html.twig, you can control whatever variable you need. However, I recommend you use the PDF view mode first to see what it can do for you.

I have yet to use a preprocess function and you should only need that if you need additional processing. Using the PDF view mode, entity-print.html.twig and the node--article--pdf.html.twig templates you will be able to print as you need.

Ultimately, you should use the PDF view mode so you can manage the PDF view mode (add classes, divs, order, add/hide/remove fields, etc.) through the UI. I have found that managing what fields are displayed through code can be cumbersome if you have a lot. The view mode can handle a lot of what you need, but you need to enable the PDf view mode first.

Sample entity-print.html.twig

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>{{ title }}</title>
  {{ entity_print_css }}

      {{ content }}

Sample node--article--pdf.html.twig:

  {{ content.field_name }}
  {{ content.body }}
  {{ label }}
  {{ content.field_name.0.value }}


You'll have to either create your own apps server using the Apps Server module or submit your app to an existing app server. In your case, you'll probably want to post on the Panopoly issue queue and ask about the process to do that; @populist will probably be the guy to answer your questions there.

Check out this post for more info on the Drupal apps scene:

http://chocolatelilyweb.ca/blog/drupal-apps-answer-plug-and-play-drupal-site-building


From the ajax callback, you only need to return the render array containing the data to be inserted into the div you have specified as the callback to your #ajax.

So in the ajax callback you can return this, rather than an AjaxResponse:

return $form['output'];


Restricting view access to a line Item field based on role

The hook method is a good one but you'll need a different hook.

The order page uses a view of line items, not a node display, so you should use a views hook.

I would try either hook_views_pre_render or hook_views_pre_view.

Use dpm($view) (needs devel module) to inspect the view and then modify it however you wish.

To figure out that it was using a view I went to the page, inspected the element in my browser and followed the chain up until I found either a form or a view:

Additional information:

You will definitely need to put an if statement around your code.  Dig through the dpm results for a view id or some other identifier and do something like:

If ([address of view id] != [view id you want]){
  return;
}

To make the column disappear you'll need to unset the field itself, not just the value.  Look in $view somewhere other than ->result.  Sorry, without the dpm output in front of me I can't be more specific than that.


How to create Stacked area charts instead of Basic area charts using the Charts module?

Stacking the charts

The most recent Charts version does not yet support "stacked" charts (of type Area, or Column, etc.).

However, have a look at the support issue (not bug!) about Stacking column/bar charts. Even though that issue is not about "Area", the approach should also work for Area charts. The clue is in comment nr 1 or nr 3 of that issue, i.e. this specific line: $chart['#stacking'] = true;. So if you succeed in passing that, you solved your question. This is what you can see in the example included there:

<?php
function MYMODULE_chart_alter(&$chart, $chart_id) {
  dsm($chart_id); // Need Developer module enabled for dsm to work
  if ($chart_id == 'MYCHARTVIEW__DISPLAY') { // Watch out for those double underscores
    $chart['#stacking'] = TRUE;
  }
}
?>

Obviously, the above requires a custom module, since it's not possible "yet" to so via the Views UI.

You may also want to have a look at these somehow related feature requests, which possibly provide an alternative to what you're trying to get to work:

Pass library-specific options via existing #raw_options.
Add an "Additional raw settings" text area to the config form.

Once we'll have these feature requests committed, we'll have 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).

Popup information

Refer to "Combination chart without aggregation" for an online demo of a chart (with multiple stacked charts) that shows such popup information (perform a mouse-over for any of the data points to see them at work).

This demo sample using Google Charts as its charting engine (not the Highcharts as in your question). Since nowhere within the Charts module there is some option to specify like "add popup information", my best guess would be that, by default (without specifying any charting engine options about it), the default for Google Charts is that such charts are created with such popups, while for Highcharts they are created without them. As a quick debugging hint: temporary change to the Google Charts engine and revisit your same chart, to check if that makes them show up in that case. So that you know it's really a Highcharts related setting that's missing (and which differs from the default).

If it doesn't seem to work for the Highcharts library, then you'll have to find out what the specific charting engine option for this is to make it work (there are tons of options in each charting engine, nobody knows them all, at least not me). After you know the specific option(s), you could try to use an approach of passing these options as raw_options, similar to stacking the charts.

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


user can not view nodes of custom content type

I assume that you just forgot to publish the content. Since the first user has access to every content, he can see unpublished content from the userX, but userX cant see unpublished content created by user1. To change this behavior you could give userX the permission "bypass node access".

For further explanation take a look at the official documentation:

http://api.drupal.org/api/drupal/modules!node!node.module/group/node_access/7

  In determining access rights for a node, node_access() first checks whether the user has the "bypass node access" permission. Such users have unrestricted access to all nodes. user 1 will always pass this check.

Edit: As mentioned in the comment, although this solution solves the initial answer, in most cases it isn´t good to give the "bypass node access" to a large number of users. In the case which is described in the comment, you should use a more sophisticated module for content pushblishing like the Workflow Module.


Is there a drupal.org API for retrieving the list of available modules?

Very recently there's an API published: https://www.drupal.org/api


How to add comment to a node with ajax (ctools modal)?

You need to add ajax library to that

drupal_add_library('system', 'drupal.ajax');

Or you can use the below function to render the ajax link

$block['content'] = l(t('Add a review'), "add/nojs/review/{$comment_site_id }", array('html' => TRUE, 'attributes' => array('class' => "ctools-use-modal ctools-modal-first-popup-style")));

Replace the above line to below.

$block['content'] = ctools_modal_text_button(t('Newsletter datacapture modal'), "add/nojs/review/{$comment_site_id }", t('Add a review'), "ctools-modal-first-popup-style");

Modify the argument

function current_posts_menu() {
 $items['add/%ctools_js/review/%'] = array(
   'page callback'    => 'current_posts_ctools_modal_review',
   'page arguments'   => array(1,3),
   'access arguments' => array('create review content'),
 );
 return $items;
}

and not to mention "Clear Cache"


I assume what you want to know is how to generate a UUID in Drupal 8, because there's really not much else that you can do ;)

Entities all have an UUID automatically, so if you store your data as a config or content entity, you just have to define the uuid entity key.

To generate a UUID yourself, you need the uuid service:

$uuid = \Drupal::service('uuid');
$uuid->generate();
$uuid->isValid($uuid_to_validate);


Block displaying in 'content' region of admin theme?

According to this comment, you can also specify the theme. I haven't tried it -- let us know if it works!

  There's also a theme key-value pair:

'exposed_order' => array(
'info' => t('Exposed commerce order filter'),
'theme' => $admin_theme,
'region' => 'content',
'pages' => ORDER_MENU_LINK,
'status' => 1,
'visibility' => 1,
),


Too few arguments to function drush_migrate_tools_migrate_messages()

The Examples section makes it pretty clear. drush migrate-messages expects one parameter, the machine name of your migration for it to display the migration messages. There's no "show all" option. Run drush migrate-status to see all migration machine names (left column) available.


Is this the proper way to add a 'class' attribute to a form date element

Yep.

Here's the references:

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attributes

And a usage example:

https://api.drupal.org/api/drupal/modules!search!search.module/7


How do I strip HTML markup or use plain text in the body field?

I was using Aggregation (Group Results Together) which caused body field to print the unrendered HTML which is fixed by checking the Format option in additional fields to true.


Apache Solr Framework with Views (for Facet Search)

I have typically achieved this type of thing using the Search API module which provides ability to select which fields are indexed and thus exposed to Views in turn along with Apache Solr integration.

The Search API provides a great base onto which to build very powerful search applications.


How do you create a link to a modal dialog?

This html looks ok, but did you include the core/drupal.dialog.ajax js library that attach event to your link ?

In twig :

{{ attach_library('core/drupal.dialog.ajax') }}

In PHP, it looks like this :

$renderArray = [
            '#title' => t('All Topics'),
            '#type' => 'link',
            '#url' => Url::fromRoute('XXX'),
            '#attributes' => [
                'class' => ['use-ajax'],
                'data-dialog-type' => 'modal',
            ],
            '#attached' => [
                'library' => ['core/drupal.dialog.ajax'],
            ],
];


You should replace

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

with

function mymodule_form_generate($form, &$form_state) {

I'm not sure if this fixes things for you, but that is the only thing I can see that is out of order.


floating an image above a specific taxonomy termed node

Put this into your themes:

function THEMENAME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $vars['new'] = FALSE;
  if ($terms = field_get_items('node', $node, $FIELD_NAME_OF_YOUR_TERM_FIELD_IN_NODE)) {
    foreach ($terms as $term) {
      if ($term['tid'] == THE_TERM_ID_OF_THE_NEW_TERM) {
        $vars['new'] = t('Maybe you can add something new text or simple set it TRUE');
      }
    }
  }
}

Then empty the theme_registry (clear caches) and change the
 to:

  <?php if ($new): ?>
    <?php print $new ?>
  <?php endif; ?>

Using the same ID in one page is not valid. Then you can target using CSS styles.


thanks all . my problem is come from the model is called views i18n cuase it is override the result to anther that i have translate it


If it is correct, should I also include print media queries in the print.css file?

It's correct, and there's no need for media queries in the CSS file.

(Separately, I'm still trying to determine what else is supplying the print styles in my site, aside from the ones I'm adding intentionally.  But I can confirm that the above annotation example works.)


So, I fixed this by writing a new module that creates custom panels panes.

Using the base Panels plugin code seen here http://fourword.fourkitchens.com/article/creating-custom-panels-panes-and-use-substitution-too I created a custom panels pane.

With the custom panels pane, I added a setting for bundles;

$bundles = paragraphs_bundle_load();
$options = array();
foreach ($bundles as $key => $data) {
  $options[$key] = $data->name;
}

$form['display_bundles'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#default_value' => $conf['display_bundles'],
  '#title' => t('What bundles should be displayed?'),
);

So when adding a pane in Panelizer, there is a setting for selecting which paragraph bundles are displayed.

Then, when rendering the pane, I check which bundles are allowed and then render them, returning an html block.

$nid = $args[0];
$node = $contexts['panelizer']->data;

if ($node->type == 'article') {

  $para_ids = $node->field_nova_section_main[LANGUAGE_NONE];
  $para_ids_array = array();
  foreach ($para_ids as $delta => $data) {
    $para_ids_array[] = $data['value'];
  }

  $return = '';
  $paras = paragraphs_item_load_multiple($para_ids_array);
  $idx = 0;
  $keys = array();
  foreach ($paras as $entity_id => $entity_data) {
    if ($conf['display_bundles'][$entity_data->bundle] !== 0) {
      $return .= render(field_view_value('node', $node, 'field_nova_section_main', $node->field_nova_section_main[LANGUAGE_NONE][$idx++]));
    }
    $idx++;
  }
}

$block = new stdClass();
$block->title = '';
$block->content = $return;

return $block;

So now, rather than adding the node field to a Panelized layout, I add my custom pane and select which bundles I display.


the Master display is the 1st Views page that you edit when making a new View. Typically this is a Page or Block in Drupal7. So you have a View somewhere that if you try to save it the View will say you need to supply at least 1 field for the completeness data field. So I suggest going through all of your Views and trying press Save on each 1 (because you dont know which 1 it is apparently or what exactly we're talking about) -- 1 will complain it cannot be saved until you fix this error in it.


Change wording of history (member since)

You could put this in your settings.php

$conf['locale_custom_strings_en'][''] = array(
   'Member since'      => 'Your new label',
);

Or you could change it in the form by preprocessing that form.  I think there are also language modules that allow you to change phrases/labels site-wide.


It looks like you are messing around with your naming.

Since your module is called test_twig_template you must use that name for hooks and namespaces etc.

Fix these things and it should work.

  Rename your hook_theme() from test_twig_theme to test_twig_template_theme.
  Call your route test_twig_template.theme.
  Your controller definition in your route must look like this, _controller: \Drupal\test_twig_template\Controller\TestTwigThemeController::content.
  The namespace in your controller must be namespace Drupal\test_twig_template\Controller;.
  Rename test_twig_template/src/Controller/TestTwigController.php to test_twig_template/src/Controller/TestTwigThemeController.php (the file name must match the class name).

That should be all, since your module is called test_twig_template it's important to use that name in all namespaces for your code to work properly :)

And then as @Hudri mentions your template shall only contain:

Test twig template!

test_var: {{ test_var }}

Head and body tags are provided by a general template in your theme.


It's where Drupal exports configuration (YAML files) to, and reads configuration from (for example using drush config-export and drush config-import respectively). The term "synchronising" refers to Drupal comparing the contents of those files to the site's active configuration, and applying any config that's changed.

You want to keep that folder out of the public web server for at least 2 reasons:

Those files could potentially contain sensitive data
You're potentially exposing the structure and configuration of your site to the world. Those details could be advantageous to an attacker.

Best to err on the side of caution and keep them away from prying eyes.


Insert value to field programmatically and remove cache from field

I also think you could use an integer field on the node for this - but keeping that aside, the  problem you are facing (the inserted value not being refreshed by the cache) is caused by the fact that you are trying to write in the database table field_data_field_hit_count_node directly. This is definitely discouraged, and you should be using the proper API instead.

Instead of db_merge('field_data_field_hit_count_node')->...->execute() you would want to do something like:

$node->field_hit_count_node[LANGUAGE_NONE][0]['value'] = $val[0]->totalcount;
$node->save();

Doing it this way ensures that the saving is done by Drupal, the caches are cleared as required, hooks as called as necessary, etc.

In addition if you don't mind using the entity module, then you can do this with Entity Metadata Wrappers in a simpler way:

$nw = entity_metadata_wrapper('node', $node);
$nw->field_hit_count_node = $val[0]->totalcount;
$nw->save();


How to use file_save to store pictures into a folder on server?

Try this:

$file = file_save((object)array(
    'filename' => $file_name,
    'uri' => $destination_uri,
    'status' => FILE_STATUS_PERMANENT,
    'filemime' => file_get_mimetype($destination_uri),
  ));
//at that point you can use the $file->fid
//do the magic on your custom table field_data_field_photo_de_couverture


What settings are there for sending an email to the users who create accounts?

In configuration > people > account settings or going to config/people/accounts you can set who gets what and even modify the text

Register without admin approval

Check this setting

Who can register accounts? : visitors

and the user that registers will receive Welcome (no approval required) email which will include a one time link to complete registration.  Upon clicking on the link and following the instructions he is a registered user.

Register with admin approval

check the following setting

Who can register accounts? : Visitors, but administrator approval is required

The user will get Admin (user awaiting approval) email upon registering and if enabled on Account activation the setting Notify user when account is activated is enabled the user will get a 2nd email upon admin approval.


Don't know where 404 error is coming from

If you go into inspector, you can see:

<object data="http://www.lostinthesmoke.com/sites/all/modules/lightbox2/images/blank.gif" width="0" style="position: absolute; left: -9999px; "></object>

is being added at the very bottom of your page.  Why?  I dunno, but it's there :)  The fact that it doesn't show up in "view source" suggests it's being added via javascript on page load.

Why isn't it finding blank.gif?  Again, I dunno.  It's here in my lightbox2 directory, so, perhaps your installation has been corrupted and thinks it is still installed.


In my observation it appears you are mixing some configurations here. Normally when you add Content: Nid, you are telling the view to get the NID from your URL like animal-info-view/% where "%" represents the node ID or somewhere else like Panels but notice that you don't have that. The view will now be asking "Where is my nid? I can't find it.". So now you're having issues with no data being displayed.
If you need a listing page, sometimes you won't need the Contextual and Relationship fields anymore. Just directly add the entity reference field into Filter Criteria and it should look like the Gender filter.
If you need a content/node view page, now you will need the Contextual fields but kinda not need the filter because you're just displaying one content.
EDITED
Apologies for the late reply. So on my research I found a module called Views Reference Filter that enabled you to assign a View to provide the selections for your filter. So install an enable the module.
Create the Entity Reference filter view

Create a new View.

Add a new Views Display called Entity Reference.

Select the Lab content type for the Show field.

Add the Lab Nid and Title/Name.

Under Format, replace it with Entity Reference List

Under the format's settings, choose Nid for Search fields.
You should have something like:

Tweak your Animal Info View

Remove all the Contextual filters and Relationships you have and the (Content entity referenced from field_lab_idc) Content: LAB ID filter you added.

And add the Content: LAB ID field that's in your Animal Info content type

On the LAB ID's settings pop-up, you will notice something new, it's the View used to select the entities. Select the entity reference view that we created a while ago.

You can leave the default Operator setting to Is one of.

Check the Expose this filter to visitors, to allow them to change it.
This would look like:

And click Apply.
Your Animal Info View should have something like this:

Hope this helps you.
NOTE: Please include your requirements so that people would know what you want the result to be like.


How do you programmatically hide a field based on another field on a custom content type?

In your template, instead of rendering the entire content array, you can break it down to print each individual item separately.  Then, you could wrap the printing of the images in a statement that checks if the boolean value is true/false.

<?php if ($content['field_boolean_hide_images'] === FALSE): ?>
  <?php print render($content['field_image']); ?>
<?php endif; ?>

This is just an example and shouldn't be used verbatim.

Also, to create a template for your content type, it would be node--yourContentType.tpl.php rather than a page template override.


you can add pattern like [node:content-type] or [node:content-type:name]. So the actual pattern will be [node:content-type]/[node:taxonomy_forums]/[node:title]


Use Hook form alter and find the id of user edit form. Unset all extra fields but username and password. In templates it is not recommended to add php. If you want to disable or hide something its better to disable it from the render array. here is an example:

<themnam>_form_<FORM_ID>_alter($form, &$form_state) {
 dpm($form);
 unset($form['your-field']);
}

I hope it helps


How to format JSON data response from a view defined by relationships to content types related by entity reference fields

Try the Views Field View module. It gives you exactly what you need. Just add a view in your view wherever you have 1:n relationships. Setup views for program, organizer and participant and add a contextual filter for the event.

The result will be one event appearing once in your view.


How to programmatically create a node when a payment is successful

Looks like hook_uc_checkout_complete() is called while the order is still in "in_checkout."

You might want to consider using Ubercart's Conditional actions module and add an action for "Trigger: Customer completes checkout"; it allows you to execute actions based on a range of conditions. You can then either execute custom PHP code to create the node, or implement the hook_ca_action() (see "ubercart/ca/ca.ca.inc" for reference).

As to how to programmatically create a node, you can either use node_save() or drupal_execute(). There's quite a few tutorials around that you can use as guidance.


How do I use paging in a content type containing a paragraph?

Build a view for paragraphs and place it in the content type with an EVA display  (Entity Views Attachment).

To do this add a EVA display, connect it to the node entity (content) and bundle (content type) in the Entity Content Settings, select as Arguments the ID of the entity the view is attached to and add a contextual filter for the parent id.

Now the view appears as field in the content type and you can use the pager from the view for the paragraphs inside of the field.


How can I filter content with conditional taxonomy terms?

You can use https://www.drupal.org/project/shs in combination with views.

From the project page:

Views (exposed filter)

add a new filter using the field set-up as "Simple hierarchical select" or
use "Content: Has taxonomy terms (with depth; Simple hierarchical select)"
as a new filter
use "Simple hierarchical select" as selection type
select "Expose this filter to visitors, to allow them to change it"
enjoy ;)


Error: Call to undefined function locale_translation_use_remote_source() in install_import_translations()

The error is caused from the fact install_import_translations() is calling a function that is provided from the Locale module (locale_translation_use_remote_source()), but since that module is not installed, the function is not found.

The Language module doesn't have the Locale module as dependency, so installing the first doesn't install the second. The opposite is true: One of the dependencies of the Locale module is the Language module.

I cannot say if this is caused by a bug on Drupal core that doesn't check the Locale module is installed before calling one of its functions, but installing the Locale module would resolve the issue. Once the Locale module is installed, Drupal will be able to find its functions, and you won't see that error again.


What is the proper permission settings to create a moderated, private organic group (in commons 3)?

I understand your confusion. In Drupal Commons, follow is not the same as registering as a group member.

If you check off the non-member checkbox on the Subscribe to group line then non-members can apply to register for that group. AS you have your other settings then an administrator can approve this registration.

Becoming a member of a group allows you to post. However, in the default configuration, posts in even private groups are visible unless additional permissions are applied and users may still follow the group.


Add link to view data if no matching record

Views PHP to the rescue:

<?php
if (is_null($row->nid)){
    print 'tid.'>add node for this term';
}
?>

I can even pass the tid through the URL and have it prepopulated on the form (using prepopulate).


URL alias not working in Contextual filters using node reference field

"node/%" is a system path, not an alias. When you use the path "node/%/foo", Drupal looks for an alias of "node/%/foo", and doesn't find one. Next, Drupal will "bubble" your request up to the system menu handler at "node/%" with the path argument of "foo".

When you use the path "alias/foo", Drupal looks for an alias of "alias/foo" but doesn't find one. Drupal does not bubble up your request to "alias".

This is a long-winded way of saying that if you want an alias like "alias/foo", you need to add it yourself. There are many ways to do this, e.g. use rules.


Matching values between two different fields, each of which have multiple values

You shouldn't use delta for such thing as data sometimes get reordered in the tables (ex: for node reference, the nid gets reordered regarding the title of the node referenced).
So I'll recommend you to create 4 fields for images and 4 for the URL and eventually put them in groupfields.

Also to make things prettier you can theme your form and put each group of field in a row using div or table.

Have a look at Theming Forms in Drupal 6 for information regaring form theming and the official documentation: The theme registry for special cases.

Another nice tutorial: http://www.akchauhan.com/theme-drupal-form/


How to create a custom Date Formatter for grouping in Views?

Views uses the rendered value for the field, including the field wrappers to do grouping. In your case, views is treating each date field differently.

There are 3 ways this can be fixed. One of the following methods should do it.

Remove the tags from the rendered output.

Using a custom template and a preprocess function, you can strip all markup and print the output only.

views-view-fields.tpl.php
template_preprocess_views_view_field

Turn off the RDF module. Views will take care of the grouping itself. The RDF module adds extra metadata to your markup, which makes views separate the grouping as shown in your example above instead of grouping the similar dates together.


How to alter rendered commerce line item on order entity view?

I know it is a bit late, but here is what I did to modify the line items on an order view.

For my example, I wanted the type field to be displayed, so I altered the view of the commerce_line_item entity using hook_views_pre_view(&$view).  Here the code that have:

switch ($view->name) {
    case 'commerce_line_item_table':
        $view->display['default']->handler->options['fields']['type']['exclude'] = FALSE;

This is all I needed to do since type was already there in the commerce_line_item_table view defined in commerce_line_item.views_default.inc, but if you want to add a field to the view, it would look something like this

        $view->display['default']->handler->options['fields']['type']['id'] = 'type';
        $view->display['default']->handler->options['fields']['type']['table'] = 'commerce_line_item';
        $view->display['default']->handler->options['fields']['type']['field'] = 'type';
        $view->display['default']->handler->options['fields']['type']['relationship'] = 'commerce_line_items_line_item_id';

Please note, that when you later the view for the user/%user/orders/%commerce_order page, it also alters admin/commerce/orders/%commerce_order/view since they both use entity_view


Drupal 8 recommend using Zend OpCache (a PHP extension), which is enabled at server side, and it caches PHP code; it is not used for caching data.
For data caching, Drupal 8 automatically uses APCu without requiring third-party modules, if the PHP extension is enabled. See Several cache bins now use APCu caching by default, which states:

  In order to improve cache performance, Drupal 8 now has:

  A cache.backend.apcu service that site administrators can assign as the backend of a cache bin via $settings['cache'] in settings.php for sites running on a single server, with a PHP installation that has APCu enabled, and that do not use Drush or other command line scripts.
  A cache.backend.chainedfast service that combines APCu availability detection, APCu front caching, and cross-server/cross-process consistency management via chaining to a secondary backend (either the database or whatever is configured for $settings['cache']['default']).
  A default_backend service tag (the value of which can be set to a backend service name, such as cache.backend.chainedfast) that module developers can assign to cache bin services to identify bins that are good candidates for specialized cache backends.
  The above tag assigned to the cache.bootstrap, cache.config, and cache.discovery bin services.

  This means that by default (on a site with nothing set for $settings['cache'] in settings.php), the bootstrap, config, and discovery cache bins automatically benefit from APCu caching if APCu is available, and this is compatible with Drush usage (e.g., Drush can be used to clear caches and the web process receives that cache clear) and multi-server deployments.

So, if you are using APCu as data cache on Drupal 7 (which require installing a third-party module), keep using it; when you will port the site to Drupal 8, you will not need anymore a third-party module, to use APCu to cache data. That is why the APC - Alternative PHP Cache module doesn't have a Drupal 8 version.

The module you are linking just allows Drupal to report status information about the cache and reset the cache; it is not a module you need to use Zend OpCache with Drupal.


How to change the labels TRUE and FALSE of a boolean field in views exposed filter

There is a number of ways how to do it, check out this thread for a lot of suggested options: Change the '- Any -' text in an exposed taxonomy filter.

You can change the themed output for that form and filter, you need a bit of custom code for that.

You could use Better Exposed Filters module, it lets you override each option text:

  Use this field to rewrite the filter options displayed. Use the format of current_text|replacement_text, one replacement per line. For example:

  Current|Replacement
    On|Yes
    Off|No

Without any additional modules or code changes you can use the Flagged Exposed filter Grouped filters option instead of the Single filter you're using now.

The Grouped filters allow you to enter a Label for each grouping. Only in your case you simply select "True" for the first grouping and "False" for the second grouping, which means you haven't grouped anything, you're just repeating the same options from the Single filter:


It was due to the multi-domain setup. I did not realize that you can/have to assign a different 404 page for each domain.


Designing different content types with the same fields' name (shared fields)

Performance isn't a huge issue in my opinion, the advantages you will gain from having correctly built relational data will outweigh any performance gains.

Use the same field across your different content types. If you are storing the same "thing" then semantically using the same field has many advantages.

Doing things that are common to that field work across content types. Eg, pulling out the subtitle and displaying it under the H1 in the page template.
Some common settings across the entities. This means that if you know a subtitle will never exceed 200 characters, you need only enter this one, keeping your models a little more dry.
If you would like to ever list these things together, you can use views to list the common fields with no extra effort.
CSS can be written more generically. Subtitles are usually grey and italic, this can be applied across bundles or entities much easier if the fields are common.

There are some disadvantages of creating lots of fields across entities to represent the same data:

Messy field lists and lots more database tables. While this wont have too much of an impact on performance, it's simply a technical debt that can be avoided.
Messy code. Having to reference ->field_articles_subtitle vs ->field_subtitle is simply duplicating information we already know (that we are working with an article).

In terms of CSS, if you would like to define custom types of formatting to different entities you can always use:

.node-type-article .field-field-name{ custom-css: true; }

In short, for the example you stated use the same field.


If you use (display: node) you can check:

admin/content/node-type/{Your-Content-Type}/display

else if you use (display: fields) check you add it to fields.


How to style the help text that appears at the top of pages?

What you're looking for is the $messages variable, which is given the following styling by core, yet seems to be removed from that contributed theme:

div.status {
  background-color: #f8fff0;
  border-color: #be7;
  color: #234600;
}
div.warning {
  background-color: #fffce5;
  border-color: #ed5;
  color: #840;
}
div.error {
  background-color: #fef5f1;
  border-color: #ed541d;
  color: #8c2e0b;
}


Method #1

Implement hook_preprocess_block() in your module/theme.

/**
 * Implements hook_preprocess_HOOK().
 */
function HOOK_preprocess_block__user_login_block(&$variables) {
  $variables['content']['user_links']['#access'] = FALSE;
}

Method #2

Override block--user-login-block.html.twig template and replace {{ content }} with the following {{ content|without('user_links') }}.

Note that hiding those links would not protect respective pages (user/register and user/password) from direct access.


how to know if a form_alter is being invoked through an ajax request?

This is likely an AHAH issue. See Adding dynamic form elements using AHAH. The form is loaded from the cache and then the form alter is called irrespective of whether it is full post request or via Ajax. You might want to change the logic in a way to save the result of checking the token the first time the form_alter is called in a $_SESSION variable (Save the token in the session variable). And change the logic to include an additional check for the presence of the same $_SESSION variable if there is no token value, and if present if that token is valid (for security reasons).


Custom block with configurable message inside it

This is a good example for a Drupal 8 custom block that is configurable by the user


Try replacing

ctools_include('node.pages', 'node', '');

with

ctools_form_include_file($form_state, drupal_get_path('module', 'node') . '/node.pages.inc');

It's possible that the node.pages.inc file isn't loaded if the form is found from cached data.


Defaulting a value for a new boolean field added to an existing content type with content?

If the field has a default value configured, you may be able to cause the "Pinned" field to be populated by bulk editing the nodes from the content overview page, and toggling a different value like 'Published', 'Sticky', or 'Promoted to front page'.

For a programmatic solution, implement hook_post_update_NAME to load the necessary entities and update the new field with the required default value.


Depending on what you want, you can either use a module like Insert View that allows to embed views as a token inside the newsletter body (dynamically, you can choose the view per newsletter issue) or you override the newsletter body template and embed the view there using views_embed_view() (hardcoded per newsletter category).


Why I am not able to add custom validate Handler function for UserPasswordResetForm on form_alter?

$form['#validate'] will not work as that form
"This form works by submitting the hash and timestamp to the user.reset"
aka redirects you to the user.reset from

what you can do is something like temp replace this form with a custom one though. however i don't really see the point

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'user_pass_reset') {
    $action = $form['#action'];
    // Set the original action.
    $form_state->set('original_action', $action);
    // temp replace from with custom one.
    $form = \Drupal::formBuilder()->buildForm('\Drupal\yourmodule\Form\AlterTheLoginResetFrom', $form_state);
    return $form;
  }
}

then do

class AlterTheLoginResetFrom extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'alter_the_login_reset_from';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get the stuff you need from ...
    dump($form_state->get('original_action'));
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      // @TODO: Validate fields.
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // redirect to original as uses get
  }
}

or alter the user.reset directly
see Drupal\user\Form\UserPasswordResetForm; line 60 & 71
and see how core does it (resetPassLogin)
\Drupal\user\Controller\UserController::resetPassLogin

if all else fails perhaps just validate the passwords in js.


How can I get a user by email address using a service?

Apparently Params are only for index functions. So you need to implement an index function, something like this from the user_resources.inc file in the Services module:

'index' => array(
    'help' => 'List all users',
    'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/user_resource'),
      'callback' => '_user_resource_index',
      'args' => array(
        array(
          'name' => 'page',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'The zero-based index of the page to get, defaults to 0.',
          'default value' => 0,
          'source' => array('param' => 'page'),
        ),
        array(
          'name' => 'fields',
          'optional' => TRUE,
          'type' => 'string',
          'description' => 'The fields to get.',
          'default value' => '*',
          'source' => array('param' => 'fields'),
        ),
        array(
          'name' => 'parameters',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Parameters',
          'default value' => array(),
          'source' => array('param' => 'parameters'),
        ),
        array(
          'name' => 'pagesize',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'Number of records to get per page.',
          'default value' => variable_get('services_user_index_page_size', 20),
          'source' => array('param' => 'pagesize'),
        ),
        array(
          'name' => 'options',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Additional query options.',
          'default value' => array(
            'orderby' => array(
              'created' => 'DESC'
            )
          ),
          'source' => array('param' => 'options'),
        ),
      ),
      'access arguments' => array('access user profiles'),
      'access arguments append' => FALSE,
    ),
  ),


There is no hardcoded limit, but sessions by default are kept in database, so user<->session queries will get slow like a hell pretty soon. Move sessions to memcache or apc if possible, and consider giving each of those 100 guys his own account.


Finding the code generating the menu with links

Have you tried this: http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_link/7#comment-24463


PHP 5.3 enforces a max_input_vars (see the accepted answer in PHP Warning: Unknown: Input variables exceeded 1000) and I've seen it create similar errors (page saves yet nothing is saved) when setting permissions for users on sites where there are lots of permissions and lots of roles, so, most probably the same is happening here with the menu UI when it has lots of menu items.  To resolve it, bump up the value on your system (see php.net documentation for max_input_vars) until things work again.


What causes 'sites/default/files is not writable' during Drupal 7 Install on Redhat w/ Apache?

I thought this would be a SElinux issue with security and I am a bit surprised that your solution worked.

For users with the "common" error, use the following command to provide apache with access despite SElinux security.

chcon -R -t httpd_sys_content_rw_t yoursite/sites/default/files/


my page.tpl.php overrides path of page display of views

Your issue seems to be in the file name - page.tpl.php will be used automatically for display of all pages.

If you want to have separate template, use hook_preprocess_page():

function MYTHEME_preprocess_page(&$variables) {
  if (arg(0) == 'library') {
    // This will look for template named page--library.tpl.php in your theme.
    $variables['theme_hook_suggestions'][] = 'page__library';
  }
}


How to set value in form validate for later validation functions

Is the problem just that your not passing $form_state by reference in your _editnode_validate validation function?

// note the & before $form_state to pass by reference
function _editnode_validate ($form, &$form_state)

   $test_value = $form_state['input']['name'];
   $form_state['values']['name'] = $test_value;


Install Commerce 2.x project template windows using composer and got HTTP 500 error

Retry ! It solves download issues.
Then find project location in C:\Users\current_user\project_name
Copy inside htdocs and browse localhost\project_name\web and continue installation.


The line 1762 is inside drupal_eval(), in Drupal 6. You need to check  those nodes that use the PHP filter and call getScriptTag() on a variable that doesn't contain a PHP object.

It happens during cron tasks because one of the implementations of hook_cron() indirectly calls node_view() on some nodes.


How can I replace certain strings in variable table all at once?

The variable holds serialized data, so you can't modify what you want with a simple query. You have you to get every variable value  with variable_get, process the value making the needed replacement and the save the variable using varaable_set.

You can get all vlaues with this snippet:

$variables = db_query('SELECT name FROM {variable}');

foreach ($variables as $variable_name) {
  $variable_value = variable_get($variable_name, NULL);
  $fixed_variable_value = your_replace_function($variable_value);
  variable_set($variable_name, $fixed_variable_value);
}

You will need the your_replace_function(). This function must deal with all possible values because $variable_value can be a number, a string, an array, object or any other PHP type. In case of arrays and object the function must process its nested components.


How to load taxonomy terms from user profile field using entityfieldquery()?

SOLVED with my module user_referenced_taxonomy_terms
code has quality 60%. you need to read it and correct if your fields has other names. this code works in my site.

/*displays only user checked companies in node addition form in field_company*/
/* field_companies - user profile field  */
/* field_company - node field */

function profile_taxonomy_on_node_addition_form_node_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  //if current user has roles administrator or editor return
  foreach ($user->roles as $role) {
      if (($role == 'administrator') || ($role == 'editor')) return;
  }
  if (isset($form['field_company'])) {
    //get user checked terms companies
    $terms = db_select('field_data_field_companies', 'c')
       ->fields('c', array('field_companies_tid'))
       ->condition('c.entity_id', $user->uid)
       ->execute()
       ->fetchCol();
    if ($terms) {
        //forming array of firms using $terms array
        $count=count($terms);
        foreach ($form['field_company']['und']['#options'] as $key=>$value) {
            if ($key == '_none') continue;
            $delete=true;
            for ($i=0;$i<$count;$i++) {
                if ($key == $terms[$i]) $delete = FALSE;
            }
            if ($delete) $form['field_company']['und'][$key]= array('#access' => FALSE);
        }
    }else {
        //hide field firm if user has no access to any term
        $form['field_company']['#access'] = FALSE;
    }
  }
}

PS: with ur comment i optimized this code.
fetchAll() gives array of objects i do not need in objects and this is not optimal.
fetchCol() gives array that exactly i need.
but fetchAllKeyed() gives only one element.
thank you Paul!


You can get it from the form itself:

$custom = $form['custom']['#default_value'];


Private files download permission

  Version 1.x provided "two useful features which Drupal itself is
  missing: a simple permission to allow downloading of private files by
  role, plus the ability to combine both public and private downloads".

  Version 2.x removes the "global" permission and implements a
  per-directory by-user and by-role filter instead, to let the
  administrator better tweak the whole website and increment the overall
  security.

with this module you can achieve your requirement by following this tutorial source

Hope it helps you!


Changing hash throw: Uncaught Error: Syntax error, unrecognized expression

Thanks to @Alfred Armstrong pointing down form.js. It seems this event is responsible of that behaviour:

 $(window).on('hashchange.form-fragment', debouncedHandleFragmentLinkClickOrHashChange);

It looks like unbinding it in my custom .js does the trick. We won't benefit from the scroll functionality form.js provides, but we could recreate it with:

$(window).off('hashchange.form-fragment').on('hashchange', function() {
    //something that scroll
});


Drush 9.2 - not working well / not installing with Composer

Thanks for the replies. Managed to get things working:

I created a new folder (drushtest), and ran composer init to create a drush-only project (myname/drush). Init runs an interactive series of question to create a valid composer.json (with only require: drush/drush [and a version constraint]).
Ran Composer to install, and it pulled down Drush and its dependencies.
Then went to remote server, and copied to /vendor/bin, the two drush files, and to /vendor, the various folders that were in my Drush-only install versus what was already on the remote folder.
Deleted the existing composer.lock. In require section of composer.json, added drush/drush: ^9.2 [with appropriate quote marks], and ran composer update. Which worked fine. [I still don't understand the effect of .lock on .json, but I guess we're all learning in the new Drupal 8 way.]
To keep things still simple, went to my Drupal folder (web), and (per Drush docs) ran Drush: "../vendor/bin/drush" -- the first time this generated a shell error re no permission. So ran that again under sudo, and got a no command error. Third time lucky, applied "chmod u+x" to that path-file, and Drush sprang to life, and even identified the correct Drupal installation (with all associated info that one expects when Drush is working) without an alias file. Hurrah!
More on file permissions: for ../vendor/bin/drush, added the x flag to the group (permissions are now 754), and can run that command without sudo (under my user name). Which I still find odd, in that my user is the owner (with rwx), and the user:group info is: user:user. But I'm quite new to Linux.
File permissions, again: With the above, commands like drush status worked, but running (as the user) drush cc (or cr) gave an error that pointed to another file permissions issue. (Sudo could run those commands OK, but it would be weird to use sudo for some drush commands and not for others -- and who could remember.) Which traced to: in the /home/user folder, there is a hidden .drush folder [with a factory subfolder containing a bunch of php command files]. The install process had set ownership of that to root:root. There is more than one way to handle this, but for now I changed ownership (chown) to user:user, and that at least allows drush cr to work.


dpm() does not display any results on screen

Make sure you have print $messages; in your page.tpl.phptemplate file. By default, devel (dpm) is configured to print it's content in the message area of the site. So if your template for some reason does not render the contents of $messages, you won't see anything.


How to avoid max execution timeout when importing a lot of nodes programmatically?

Yes, there is a way! It's built into Drupal core, and it's there for this exact reason and purpose. You need to use the Batch API. Batch lets you, well, perform operations in batches across page loads. It automates the carrying of information between these page loads and helps you to show a nice progress bar to the user.

See:

Batch operations reference
The Examples module (which contains a batch_example module)
Countless online tutorials


Help with Canada Post Shipping Quotes with Ubercart

Make sure you have the store address information all filled out properly in the Ubercart Store Configuration and in the Shipping module.  It seems like a duplication but it helped me.


How can I sort a view based on a rewritten field?

If you don't want to go for the module route, this is one alternative:

1) install Computed Field module
2) add a computed field to your content type
3) in the field settings, in the Computed code (PHP) textarea, you can access the field data.

Get your date fields in your current langugage to a variable.

$repeating_dates = field_get_items($entity_type, $entity, 'field_repeating_date_example');
$multidates = field_get_items($entity_type, $entity, 'field_multidate_example');

Your date values can now be found in

$repeating_dates[0]['value'],
$repeating_dates[1]['value'],
$repeating_dates[2]['value'], etc.

$multidates[0]['value'],
$multidates[1]['value'],
$multidates[2]['value'], etc.

Do whatever logic you need with your date fields and assign the result to

$entity_field[0]['value']

Now you have a sortable field you can use in views, but first you have to update all the nodes as the computed field will only be computed and saved to the database at node save. There are many ways to do this, one is using Views Bulk Operations, it gives you an option to re-save nodes at admin/content.


You can use views to get that.

Make sure you sort items descending and limit the result number to be 20.


Responsive not working after converting html theme to Drupal theme

To create or convert a Drupal 7 responsive theme, it is not a good idea to start with stripping down and modifying a fully developed, non-responsive theme such as Bartik.

Instead you start out with a responsive starter theme or base theme framework, where the css is already reset for you and where the the framework is already prepared for you to add your own classes to construct whatever look and feel you're after.  Basically, you install your framework, then create a sub-theme, and use that you build your own responsive theme.

Good foundations for this is IMHO Zen, Omega or AdaptiveTheme (suggested by @Kojo in a comment), but many other alternatives exist.


Multiple sites and performance in Drupal 7

My recommendation is to go with a multisite.

Multiple Drupal instances and multisite are about the same in terms of performance (multiple databases). One Drupal instance will not scale as well and thus will not perform as well. The database layer is a bottleneck of Drupal that is hard to work around.

You can create custom code for taxonomies to make them shared across all multisites; users can use something like https://www.drupal.org/project/bakery. Doing this for multiple Drupal instances is a little harder to pull off in comparison to a multisite.

To do a shared taxonomy you'll need a new database connection in your settings.php pointing to a new db. This will hold all of your taxonomy_* tables; or you can designate one already existing db to be the master record. Then using  hook_taxonomy_term_presave() and hook_taxonomy_vocabulary_presave() write the master taxonomy info into the correct db or if it already exists have it use that tid/vid. Then in hook_taxonomy_vocabulary_insert()/hook_taxonomy_vocabulary_update() and hook_taxonomy_term_insert()/hook_taxonomy_term_update() write the taxonomy info to the rest of the databases in your multisite. See taxonomy_term_save() and taxonomy_vocabulary_save() and use the drupal_write_record code to write. Use db_set_active() to change database connections. Have all multisites use the same settings.php file (symlink or include), and in there have a big array containing all your database connection info; create a path lookup function that uses conf_path() and readlink() if needed for knowing what db to connect to. You'll need to migrate all taxonomies before so they all match. This took a little while to code, about 2 weeks. The code I have is for D6 so it wont work for D7.

We used the shared taxonomy on around 80 databases using https://www.drupal.org/project/domain to give us 1300+ domains. It scaled very well.


Use the "Metatag Views" sub module that comes with Metatag module. Link https://www.drupal.org/project/metatag


How to use JQM theme and jQueryMobile plugin with Drupal?

Please make sure you've read the readme properly. The module requires that certain files be patched and you have the libraries in the correct place.

I have had jQuery Mobile theme working but found that it was far from usable so built my own simplified theme.


Remove taxes using Rules after coupon is redeemed

Yes, there is a core Drupal Commerce Rules action called "Remove taxes applied to a line item" in the Commerce Tax group. Additionally, via Rules you can inspect field values on any entity to see if they are empty or not. The coupons applied to an order are tracked through a variable called commerce_coupons.

Putting it all together, this means you need to create a custom product pricing rule that looks to see if the commerce_coupons field is non-empty. If so, it should use the action mentioned above to remove taxes. Make sure the weight of your custom rule is set such that it is calculated after the discount that gets added via the coupon.

Note: this cannot be achieved through the Commerce Discount module's interface. It must be done via Rules at Administration > Store > Configuration > Product pricing rules.


7 - Panels node form, file/image gets removed when field not present in the custom form

I've also encountered that. The node form and the image field's value will be submitted as empty and resulting in as you say that the image get removed from the node.

It is an unfortunate side effect of how the form api works. Someone could try to work around it in Panels, and/or limit panels to prevent you from doing this, but both of these would be hacks on top of form api.

One workaround is adding the pane General form that you will find under Form when adding panes. Then click settings for the pane and under CSS properties set the class to "element-invisible". This way all other form elements that you have not placed as panes will be present but hidden by css.

I know it feels wrong but at least it get's the job done :)


option to promote to top of list in drupal

By default, you will find a checkbox on every node-edit form called "Sticky at top of lists". It's under the "Publishing options". If you use that to identify the top content, you can add a sort criterion "Node: Sticky" (descending) to your view to make the selected nodes appear on top.

If you need even more control (ie. you want to specify the exact order) use a module like Draggable Views or Nodequeue.


how to make an existing listbox autocomplete

The list box field does not have autocomplete widget unless you use the taxonomy terms, and there are already 650 contents and you do not want to edit the content then you should use the Chosen module, the chosen module will allow you to search within the list. here is the examples page http://harvesthq.github.io/chosen/

following is the module page.
https://www.drupal.org/project/chosen


Best practice: content types with unique machine names

Counting content types should be as easy as:

$result = db_select('node_type')
        ->fields('node_type')
        ->execute();
$num_of_results = $result->rowCount();

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


How to make a child entity automaticially reference back to parent entity when created using inline entity form?

This has been acheived using Rules:

Export of Rule:

{
        "rules_ifs_backlink_populator" : {
        "LABEL" : "IFS backlink populator",
        "PLUGIN" : "reaction rule",
        "ACTIVE" : false,
        "REQUIRES" : [ "rules" ],
        "ON" : [ "node_insert", "node_update" ],
        "IF" : [
          { "node_is_of_type" : {
              "node" : [ "node" ],
              "type" : { "value" : {
                  "auction" : "auction",
                  "estate_sale" : "estate_sale",
                  "garage_sale" : "garage_sale"
                }
              }
            }
          }
        ],
        "DO" : [
          { "LOOP" : {
              "USING" : { "list" : [ "node:field-ifs-add" ] },
              "ITEM" : { "list_item" : "Current list item" },
              "DO" : [
                { "component_rules_create_entity_reference_back_link_" : { "child_param" : [ "list-item" ], "parent_param" : [ "node" ] } }
              ]
            }
          }
        ]
      }
    }

Export of Component:

{ "rules_create_entity_reference_back_link_" : {
    "LABEL" : "create entity reference back link ",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "child_param" : { "label" : "Child Parameter", "type" : "node" },
      "parent_param" : { "label" : "Parent Parameter", "type" : "node" }
    },
    "IF" : [
      { "AND" : [
          { "node_is_of_type" : { "node" : [ "child-param" ], "type" : { "value" : { "ifs" : "ifs" } } } },
          { "entity_has_field" : { "entity" : [ "child-param" ], "field" : "field_auction_ref" } },
          { "data_is_empty" : { "data" : [ "child-param:field-auction-ref" ] } }
        ]
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "child-param:field-auction-ref" ],
          "value" : [ "parent-param" ]
        }
      }
    ]
  }
}


How to prevent users with negative balance of user points from viewing nodes?

Your question actually contains 2 challenges:

Which Rules Event to use?
Check the current balance of user points of the user?

Read on for an answer to address each of those challenges.

1. Rules Event to use

If you'd use Rules event node_view, then you're too late, because the node is already being viewed (which is exactly what you want to prevent). Instead you need to use (System) event "Drupal is initializing" (= init), which is actually BEFORE the node is actually being viewed.

2. Check current balance of user points

However, you also want to disallow viewing nodes for users who have a negative user points balance. The challenge with that is that there is no out-of-the-box Rules Condition to check that balance.

Have a look at this Rules example (in Rules export format):

{ "rules_stop_node_access_for_user_with_negative_points" : {
    "LABEL" : "Disallow node/* access for a user with negative points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "0" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have insufficient points (you only have [total-points:value] points ...)." } },
              { "redirect" : { "url" : "no_access" } }
            ]
          }
        ]
      }
    ]
  }
}

The Rules Condition added here, is to only perform the Rules Action for attempts to browse a path like node/* (adapt to what fits for your case).

This rule retrieves, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If it is negative, it will display an appropriate message starting with "You have insufficient points ...", and it redirects to a relative path like no_access (adapt to what fits for it).

This rule uses the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module.

The clue to make this rule work is the very first Rules Action "Load user points of a user". Refer to my answer to "How to access current amount of earned userpoints in a Rules Condition?" for more details on this.


Add custom ajax command to ajax response after webform is submitted

I had this same issue, what worked for me was under webform settings > Confirmation > Confirmation Type. Change the confirmation type to 'Inline (reloads the current page and replaces the webform with the confirmation message)'

This returned true for $event->getResponse()->getWebformSubmission()->isCompleted()


Below is a sample of a rule (in Rules export format) that will send an eMail similar to what is asked in the question:

{ "rules_notify_author_of_selected_field_updates" : {
    "LABEL" : "Notify author of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_check_in" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-check-in" ],
          "value" : [ "node:field-check-in" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:current-user:mail]",
          "subject" : "Notification about a node with an update field_check_in value",
          "message" : "Go checkout the node with nid [node:nid] and title [node:title]: it has a field with an updated value (which is [node:field-check-in]) you wanted to be informed about ..."
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event I'm using is "After updating existing content".
It's about updates to the field field_check_in.
The Rules Condition checks if the "The value changed".
If the Rules Condition is true, then (as Rules Action), an eMail will be triggered to the editing user.

Adapt the actual eMail details (subject, etc) to fit your needs. Then import it in your own site (using the Rules UI). That's it.

Note: I'm assuming this is about D7.


Maybe you should investigate to what extend the IP Geolocation Views & Maps module could help you. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Its project page contains even more information ...


making a views grid go from right to left?

As far as I am aware, there are no settings in views to change this behaviour. However you can change the view format to "Unformatted" and give the .views-row a width and float:right (tweak as desired). This will line them up as a grid rtl.