Advantages of running cron via drush rather than via curl?

Advantages is a loaded term, but I'll describe the differences.

If you compare https://github.com/drush-ops/drush/blob/master/commands/core/core.drush.inc#L647 with http://cgit.drupalcode.org/drupal/tree/cron.php?h=7.x, you'll notice that they both ultimately execute drupal_cron_run(). The only difference at the code level is what happens before that.

cron.php checks that a cron_key is passed in the query string and that maintenance_mode is not on.  It also logs to watchdog.

Drush doesn't check either of those things and uses drush_log which is very different than watchdog (see Where are logs created by drush_log() stored?).

Finally, wget uses the service configured to handle http requests (most likely Apache or Nginx) even when configured to request cron.php through localhost.  Drush is PHP running in Bash which executes the Drupal functions like  drupal_cron_run() directly.

There are several reason you may or may not want to trigger cron through an http service, but here is one use case that might help illustrate a big difference.  Let say you have a Drupal site that is moving to a new server and domain and you configure a redirect at the .htaccess level to send all http requests for olddomain.com to the new site at newdomain.com.  Requests to execute cron using wget in a crontab would also be redirected, but calls to drush would continue to run cron.  If the wget requests being redirected to the new site used the old cron_key, you would begin seeing errors about that in your logs.

Someone could make the case that the memory and CPU footprint of the Drush request is smaller, but that should be very trivial compared to what happens in drupal_cron_run().

I don't think one is necessarily better than the other, but they are different.


Couple things you can try.

Clear the session table, as it sounds like there may be some preexisting sessions left over from the archive.
Clear the cache tables as well
Make sure the folders/files are owned by the Apache user


You might want to have a look to the Features module.

By creating a feature, you can export entities, fields and many other settings created using the admin UI to a module, that then can be installed to your target site.

You may also consider creating a dedicated custom module that holds all your database-stored settings and pre-populated entities/content (e.g. basic taxonomy vocabularies, user roles, permission assignments, ...) set by code instead of the admin UI.

Every setting you can do within the admin UI can be done by code as well, using according hooks, function calls or database queries. And each time you extend your site and settings, you will add an according update hook to keep sites up-to-date that have your module running already. (Staging / Production)

This approach is considerably difficult for beginners to work with, but once you know how to do it, it's worth the efforts. (Speaking from experience.)

Last but not least, you can always synchronize entire databases. For example using the Backup & Migrate module or manual database exports/imports. You just need to make sure to do your settings on a clean version without test data. This approach starts becoming messy once your site is live, but may suit your needs while you still create it.

In Drupal 8, I'd suggest configuration export/import instead, which makes the entire process of configuration management a whole lot easier.


Drupal views relationships to an indirect referenced contenttype

The node reference fields in both the person and the workgroup both point to the same organization. Set up a relationship between person and workgroup on the organization field. That should make the workgroup name available to the view.


I found the solution. The |filter has to be included while calling macro like this:

{{ macro.input('text', 'name', 'Name...' | t) }}


You're currently escaping a bit too much...you only need to use the {} placeholders for table names. With an extra small change to protect you from SQL injection, your code should be something like:

$args = array(':id' => $l_ID);
$dbresult = db_query("SELECT * FROM {places} Where ID = :id", $args);


How can my Drupal module expose custom URLs?

You need hook_menu in your .module file.

  This hook enables modules to register paths in order to define how URL requests are handled. Paths may be registered for URL handling only ...

example:

function MY_MODULE_menu() {
  $items['path/callback/%/%'] = array(
    'page callback' => 'my_callback_func',
    'page arguments' => array(2, 3),
  );

  return $items;
}

function my_callback_func($arg2, $arg3) {
  //your process here
  $data = array($arg2, $arg3);
  return drupal_json_output($data);
}

in js call this url with 2 arguments: path/callback/VAR_1/VAR_2 - VAR_1 is second argument, VAR_2 is third as defined in "'page arguments' => array(2, 3)" (path is zero argument, callback is first argument)

The $data may be returned in what you want format. In this example this is JSON.

More for hook_menu - http://api.drupalize.me/api/drupal/function/hook_menu/7


Form validation not triggered at first submit, but on second submit

I added your code to a quick dummy function, tested it, and the it seems to be working fine. I created a dummy item, added it to my cart, and the that produced a print out like:

I also added a watchdog() call to the validate function and that confirmed the validation was being called when it should be. I'm not sure if maybe you have something else interfering with your form alter or possibly your dpm is printing out late (I know it can happen with themes, not sure with modules), but you might want to try using watch dog to see if the validation form isn't being called when it should.


how to get valid URL in combination of text and field content in VIEWS

Yes you can use the Rewrite results option on your Field settings. Use the Output this field as a link option and enter only the URL with the field token replacement pattern at the end of it.

You can look up the token under Replacement patterns under the Rewrite results option.

If you need some more control over the link HTML you can use the Rewrite the output of this field where you construct the entire link HTML <a href="....


Now that the topic is open again I will try to answer the questions:

  Does the #cache property for render arrays cache content from a query
  when used in a controller?

Yes, it does. The cache metadata will be used to cache the render array if you set cache keys and the metadata bubbles up to page level.

  The database query is executed on every page request. I am not sure if
  this is due to the fact this page is an administrative page and users
  must be authenticated.

On page level this is true, as for now it is presumed that admin pages are not cacheable, see Change Dynamic Page Cache's response policy from "deny admin routes" to "deny html admin routes"

  I expect the content to be cached and the query that generate the
  result to not run on every page request.

See the comments from @Berdir and this blog post how to do this by moving the query to a #pre_render callback:

https://dev.acquia.com/blog/drupal-8-performance-render-caching


Drupal 8 uses the page alias to build up the breadcrumb trail. Your "node page" would need to contain the "list page" alias to make it work e.g.
List page = /mylist
Node page = /mylist/mynode

If you want to use the menu structure then you could try this https://www.drupal.org/project/menu_breadcrumb


Populating fields from the User entity during a Commerce checkout

You could attach the fields from the user to the form, but you would need to handle saving the user in the form submit. You could in form alter do something like this

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id') {
    $form['user_fields'] = array();
    global $user;
    field_attach_form('user', $user, $form['user_fields'], $form_state);
  }
}

You also need to add validate and submit handlers in the form_alter in the validate handler do

 field_attach_validate('user', $user, $form['user_fields'], $form_state);

And in the submit handler do

field_attach_submit('user', $user, $form['user_fields'], $form_state);
user_save($user);


Why am I missing 'notification' features on my entityforms?

Because... I have different versions of Entityforms on staging and production.  In the more recent version (7.x-2.0-beta2), they just moved things around.

You can get to the notification rules now by going to Structure > Entityform Types > [form] and clicking the Rules tab.


#ajax->wrapper refers to an ID. Where as you have class="giftcards-wrapper". Change it to ID and it should replace it.


How to display the first child of a book with the title of the book and keep the url by using a view

It's not at all a problem to override the link text with another field. Title field settings have the Rewrite results with the Override the output of this field with custom text, with available tokens listed below that under Replacement patterns.

To get the top level Book information add the Relationship Top Level Book.
Edit the Title Field and make sure it uses the Relationship, this will display the main Book title for each of the book Pages in the results, instead of the Pages titles. (I'm assuming you've created the Content Views showing Book pages.)
Edit the field settings to Exclude from display and untick Link to the Content while keeping the Formatter Plain text, so the main book link doesn't interfere with overriding.
Add Field Link to Content, configure it under Rewrite results with Override the output of this field with custom text, Output this field as a custom link, enter token for your title field into the Text field, something like {{ title }}

Now you have links for each Views result that link to Book Pages but the link text is the main Book title.
Book pages weight
The real problem is showing only the first Book pages. Weight is available as a Field within Views, so you can show and sort the book pages in the results according to their set order. Lowest numbers float to top, large numbers fall to the bottom, as is always the logic with weight in Drupal.
But there doesn't seem to be a Filter available for the Weight, at least I'm not seeing any right now, so it doesn't seem possible to filter out only the first child page of every Book.
It is possible to work around it by creating a separate Views Display for each Book you have in Drupal. Set Sort criteria to Book Weight, and Pager to only show 1 result. This way only the first Book page will be shown, but you'll have a separate Block for each Book to show this.
If you have more than one level of the book pages use the Filter Depth with the value 2. (1 depth is the main Book page and 0 is for book pages that don't belong to any Book.)
You can make it look like it's the same Block with some styling after you display all those Blocks in the same theme region.


That should be rather easy.  You have to use two arguments, a regular taxonomy argument for your important term, and the global "Null argument" to ignore the unimportant term.  The null argument is added the same way as all other arguments, just have a look through the list.

I assume you know, that you have to set-up a "page" display, specify a path and insert the argument placeholders.


Is it possible to add to different aliases to the same table in a dynamic query?

The best answer I have at this point is to simply execute the subquery first using fetchAssoc() to return an array.

$subquery = db_select('nested_category', 'parent');
$subquery->addField('parent', 'lft');
$subquery->addField('parent', 'rgt');
$subquery->condition('name', $name, '=');
$parent = $subquery->execute()->fetchAssoc();

$query = db_select('nested_category', 'node');
$query->addField('node', 'name');
$query->condition('node.lft',$parent, 'BETWEEN');
$results = $query->execute()->fetchAll();


What is wrong with my custom Entity form validation?

Documentation of ContentEntityForm::validateForm:

  Button-level validation handlers are highly discouraged for entity
  forms, as they will prevent entity validation from running. If the
  entity is going to be saved during the form submission, this method
  should be manually invoked from the button-level validation handler,
  otherwise an exception will be thrown.

Even if you don't use button-level validation this should be the cause for the exception. Did you call the parent method?

parent::validateForm($form, $form_state);

If you don't run the entity field validation in some way the exception is thrown.


In views under advanced->theme you can see template naming conventions you can use. Copy the views-view.tpl.php to your themes templates folder and rename it to one of the suggested names in views->advanced->theme. Clear your cache and the template will be used. Now you can alter the output of the whole view.

You can also do this for the fields as a whole, or a specific field.

Mind that views has so much power through UI that you seldom need to go through themefiles.

Wrapping the views field(s) in a link can be done also by rewriting field output.


Where to write a jquery script for a registration form page which created using webform module in Drupal 7?

First off, as rooby very accurately suggested in the comment section, you should not tamper with the Bartik theme directly. You have many possibilities on where to include a js script. You can read all of them in the relevant documentation in drupal.org.

The closest to what you describe is to subtheme Bartik and put all necessary js there, or even create a small custom module.

Apart from that, jQuery in Drupal uses the noconflict mode. Try to avoid the dollar sign but rather call jQuery. Although in your particular code should be ok as it is, there may be other instances in your script using $ that would prevent it from working. More on that here. Check your browser for js errors.

Last, there is no way for us to evaluate your jQuery code if it works properly or not as we do not have the produced HTML output nor the context of your provided js code.


node anchors on single front page website

We created the Single Page Site module, to incorporate one page websites into Drupal. This is an example of a website using it: http://starfisk.com
Some more details about this module (from its project page), which is available for both D7 and D8:

This module provides functionality to create a single page website.
It allows you to automatically create a single page from a menu. The module will render all the content from the links, that are configured in the menu, on one page. It will then override the menu links so that they refer to an anchor instead of a new page.


"user:one-time-login-url" token not getting replaced by token_replace

To replace that token, you need to call token_replace() as token_replace($email, array('user' => $_user), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE)).

The function user_mail_tokens() is described in the documentation as:

  Token callback to add unsafe tokens for user mails.

  This function is used by the token_replace() call at the end of _user_mail_text() to set up some additional tokens that can be used in email messages generated by user_mail().

The code used by _user_mail_text() to call that callback is the following one.

// We do not sanitize the token replacement, since the output of this
// replacement is intended for an e-mail message, not a web browser.
return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE));

The Token module is not necessary to replace tokens, in Drupal 7. The code to replace tokens is part of the Drupal 7 core code; the Token module in Drupal 7 defines extra tokens that Drupal core modules don't define.


defining relationships between terms in a taxonomy

The relationship functionality exists in Drupal core - no need for a contributed module.

Go to /admin/structure/taxonomy/YOUR_VOCABULARY/fields and add a new field of type Term reference, click Save.

On the next screen

change Number of values from 1 to Unlimited
choose the same vocabulary you added the field to in the Vocabulary dropdown.

Then edit each term and add the neighbouring regions to it.


Filter User in Views based on taxonomy contextual filter?

You are on the right track, but the contextual filter has to be changed. The user ID is not the region. If you wish to filter on the Region, you must first determine the Region for the user page you are on.

Switch the Provide default value to PHP Code. Then enter something like:

$user = menu_get_object('user');
return $user->field_region['und'][0]['taxonomy_term'];

This will load the term object for the region of the current user, and the filter can then limit the user list based on that term.

To eliminate the current user from this list, set upa second contextual filter in User:UID and set default value to Use ID from URL. Then open up the 'More' settings and check exclude.


Hide option Generate automatic URL alias for all languages on user register form?

You can use CSS to hide it or set the option's #access value to false using a custom module.  The first will hide it but leave it available to be ticked, the second will completely remove it from the page.


Copy taxonomy term name to another field

I am assuming you have a content type with a field
"Title" of type "Term Reference"... and you want to pass an address from this existing field to a hidden field for Geo coding or whatever else for that specific page.

I would suggest using views and entity reference to do this. This method is useful for passing multiple fields, but can be used to grab just one...

Once you have the Entity Reference module enabled and installed create a view. For the view's display options (that + sign) add 'Entity Reference'.

Add a field to this view of type: "Content: All taxonomy terms"

In the next options screen you can limit the options here to your specific 'Cities' vocabulary.

You now need to add a contextual filter 'Content:NID' to get this view to only display the city term reference for the page that it's on.

Now go back to your content type and add a field of type 'Entity Reference'. Configure it like this:

Target Type - Node
Mode - Views (filter by an entity reference view)
View used to select the entities - 'my entity reference view'

Now add your Geofield and configure it to 'Geocode from another field' - i.e. your entity reference field (which you can hide in the display options)

In the event that a city name alone is insufficient to geocode from consider adding other fields to your content type and passing them to your entity reference view.


Combine all nodes of two content types as table rows / columns

its very easy if contentypes are "entity reference" related, on "less important" contentype add an entityreference field and relate that node to "main contentype", in views add a relationship with your entityreference field, filter (not exposed) to display only "main contentype", and when adding fields to your view (now both contentypes fields are listed in drop menu field listings), specify if you use or not the relationship, for fields on "main contentype" do not use relationship, do it in all "less important contentype" fields. done.


How to make the date field of authoring information in Create Article page a date field?

Use Date Popup Authored module.

  Date Popup Authored provides a jQuery UI datepicker for the Authored
  on date field found on node submission forms.

  This allows content editors to pick a human-understandable date and
  not have to type the exact date format of the default Authored on
  field.


A lot of core JavaScript files not being included

I figured out that using drupal_add_js outside of a hook_js_alter function in another file was causing the issue.

drupal_add_js($form_js, array('type' => 'inline', 'scope' => 'footer'));

Now that it is within the function, it's working fine.

I don't see anything in the documentation saying that this is required -> also, drupal_add_css works fine outside of a function. I'm not altering any existing JS files, only adding new ones.

So while I don't understand why this is an issue, this is the solution


Count number of values within a field that accepts unlimited values

There is a way of doing this natively in Drupal 7.

Set 'Use aggregation' to Yes
Add a field that contains multiple values, such as a file field
Set the aggregation settings for it to COUNT DISTINCT

Simple. This will however enable aggregation for all fields, but the default settings for other fields will make them behave normally.


Drupal will not look for template overrides in custom modules, only themes.

If you really want to put a template override in a custom module see the answer to this question.

Extra notes are:

Make sure to handle punctuation and any other undesirable characters in your field value.
field_get_items() is a better way to get the value of a field from a node.
It is generally best to keep your template suggestions in line with what is already there. For example starting this suggestion with 'node__' followed by your custom stuff, like maybe 'node__event__' . $field_template_list or something like that. It makes it easier in future to know what kind of template it is.


I want to override results of an autocomplete field (Entity reference in a content)

It's pretty much the same as Show node IDs along with titles in Entity reference Autocomplete list except you use content type name instead of node id.

Currently there is a bug in Drupal 8 where this does not work properly. Here is the issue: Views Filter by an entity reference view not working as expected you could try the patch in comment #26 or the module in comment #13. I have not tried them yet.


I get 404 when uploading private *image* files in D7

First, have you already checked the status report (/admin/reports/status)?

If that's all green then do you can dig around the content type field settings and also the content type view fields settings to see if you're using any image styles on the images. If you are you need to make sure the folder sites/default/files/styles has proper access perms.


Using video module with ffmpeg to convert; how do I display converted files?

Solved this by modifying the custom module. Test if file has been converted, by looking in sites/default/files/videos/converted/nnnn, where nnnn is the File ID of the original file. If not then display the original video file. If conversion completed successfully, then display the converted file from sites/default/files/videos/converted/nnnn. There is only one file in the nnnn directory.


How can I output the absolute URL as link text for internal links on link fields?

Inspired by Link field title from entity/route, I created a preprocess function.
/**
 * Prepares variables for link fields.
 */
function mytheme_preprocess_field__node__field_links(&$variables) {
  /* If it's an internal link and there was no link title provided by the editor,
then use the entity label as the link text.*/
  $i = 0;
  foreach ($variables['element']['#items'] as &$item) {
    if($item->getUrl()->isRouted()) {
      $parameters = $item->getUrl()->getRouteParameters();
      if (!empty($parameters)) {
        foreach ($parameters as $entity_type => $id) {
          if ($entity = Drupal::entityTypeManager()
            ->getStorage($entity_type)
            ->load($id)) {
            $variables['items'][$i]['content']['#url_title'] = Link::fromTextAndUrl($entity->label(), $entity->toURL())
              ->toString();
            break;
          }
        }
      }
    }
    $i++;
  }
}


setcookie doesn't work in submit function nor tpl.php

Thank you everyone, I got the answer.
It seems Drupal supports session instead of cookie.(Sorry I cannot find the reference again.) Therefore, I used session to implement my function.

Here are some reference:

Example for session:
https://www.drupal.org/node/360542

How to set session expiration:
https://www.drupalgardens.com/documentation/cookie/expire


Can we call submit handler of one form into another form?

You could pass the page number as argument to your hook_menu()

<?php
function mymodule_menu() {
    $items['abc/def/%'] = array(
      'page callback' => 'mymodule_abc_view',
      'page arguments' => array(2),
    );
    return $items;
  }

Then if it is step-one for example, get your subscription plan form, render it then submit.
In the submit function use:

 <?php
// Force the form to rebuild. If we do not do this, the value(s) in $form_state['storage'] will be lost
$form_state['rebuild'] = TRUE;
//Redirect to step two
$form_state['redirect'] = 'abc/def/2';

In step 2 get the user profile so that in the next submission you'll have the data from both forms in the submit function.


"This view has been automatically updated to fix missing relationships" - fields removed from a working view for no reason

EDIT: It turned out after all that this behaviour was related to the "Administration Language" module https://drupal.org/project/admin_language.
Disabling it made the problem disappear for good.
It seems as its is related to access permissions.
A similar problem was encountered in creating product views in drupal commerce. If you want to relate to the fields of the referenced product, you have to grant the View permisssion to all products (non-node enitities of DC). Otherwise the users without permission to view the product enitities will see an empty view (see Views results empty for unprivileged user when using Relationship: Content: Referenced Product). What makes it especially difficult to track that the problem does show up only when one uses Relationship & "Fields" display. A similar view with content / teaser etc renders the same content without problems.

Now, I wanted to add an image of the product to the cart view. I referenced the Image field of the product in the cart ((Line Item) Commerce Line item: Product), and put the image field from there.

I understand that the permissions problem prevent the view from functioning properly. It seems to be that it's a bug that
a) the view itself functions well
b) that the problem appears in the Views UI
c) that the error message is not informative.

It seems to me that this behavior is just a side effect of a number factors in how the Views work.


How to add a class to the  link elements within a Multiple Values field in a View?

Just rewrite the lot with appropriate Replacement Patterns.

In Views:

Rewrite Results:

Rewrite the output of this field : Tick
Text : Add as appropriate, ie [field_link-title]
Output this field as a link : Tick
Link path : Add as appropriate, ie [field_link-url]
Link class : Add as appropriate

Above assumes your multi-value field is Link.

If any other field you can just Rewrite with output as link, link path and link class.

THERE does not seem to be a way to write the other original attributes back into the link. They can be obtained from a Replacement Pattern, but there is no form input to add them back.


You can implement hook_init in a custom module.

function my_module_init() {
  // Since this file should only be loaded on the front page, it cannot be
  // declared in the info file.
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  }
}

But note that this WILL NOT work if the page is cached or if you are using a revers proxy cache. If you need to do this on cached pages look into using hook_boot

That being said, there is often better ways to accomplish a redirect based on certain conditions. Update your question with more details and perhaps we can find more suitable solutions.


$content is to be rendered and obeys what you have set in node(other other entity) type's Display Settings (Administer > Structure >Content Types).

What you should use is, $node object.

<pre>
<?php
print_r($node);
?>
</pre>

Now you will see a nicely formatted information of $node object which also has the NID you want.

You will be able to access it with this:

$node->field_call_to_action_1['und'][0]['target_id']

Quick hint:If you are trying to build a URL link from this value, have a look at url() and l() functions!


What's the default weight of a form's submit element?

A submit button appears at the bottom of the form usually because it's simply added last in the form definition.

A submit button can still be placed anywhere and weighted using the #weight property.

The default weight is assigned automatically.

The relevant core code is in

form_builder

// Assign a decimal placeholder weight to preserve original array order.
if (!isset($element[$key]['#weight'])) {
  $element[$key]['#weight'] = $count/1000;
}
else {
  // If one of the child elements has a weight then we will need to sort
  // later.
  unset($element['#sorted']);
}

If not present the#weight property is calculated dynamically based on the count/item position while looping over the form element set.


I have begun running Drupal 7 on PHP 5.4 myself with only minor problems in the form of notices and warnings.

On top of 7.12, you will need these two patches to fix the issues causing PHP to complain:

http://drupal.org/files/menu-link-save-1338282-15-d7.patch

http://drupal.org/files/database-query-clone-1414412-11-d7_0.patch

One of these patches has already been applied to -dev, so will be in 7.13, and the other is likely going in soon. In all cases that I can immediately think of, the bad practice causing 5.4 warnings has been bad use of array keys.

The first version of this looks like this:

$some_key = function_call();
return $some_array[$some_key];

Some times, the function call will return an array or an object, neither of which is a valid array key. In PHP 5.3, what actually, and silently happens, looks like this:

$some_key = function_call();
return $some_array[(string)$some_key];

PHP 5.4 however, warns that this may not be what you want. The second version is exactly the same, but the other way around.

$some_key = 'a_valid_key';
$may_be_a_string = function_call();
return $may_be_a_string[$some_key];

which yields an error message like

  Illegal string offset 'a_valid_key'

whenever $may_be_a_string is actually a string, not an array, since the only valid string indexes are integers.

As the problems are easy to understand and the fix is (mostly) easy to apply, I've found that in several cases, -dev versions are already updated, or patches posted in the queue, that are likely to quickly go in due to their simple nature.

After some testing, I don't feel like 5.4 is "dangerous" to run in production, and I have begun running my small and personal sites on it already. I would encourage other to do the same, so we can avoid the historically slow uptake of new PHP versions.

At the time of writing, APCs latest version, 3.1.9, does not work with 5.4. I have successfully built and used it from git though.

Using APC will likely reduce the performance benefit of upgrading the PHP version, but not remove it.


How to make a word/pdf type doc clickable

I know its not a complete answer, but may help.
Icon:

$icon = theme('file_icon', array('file' => $file));

File size:

format_size($file->filesize);


What is the form id used in user profile edit form?

To override the user form (when editing user profile) you can use hook_form_alter with user_form id.

On the following example code the current_pass is required so anyone making changes will need to enter it.  Also we assume that any administrator would not be forced to enter the password.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  $user = \Drupal::currentUser()->getRoles();
  //admin's probably should not be forced to enter password
  if(!in_array("administrator", $user) && $form_id == 'user_form') {
    //$form['account']['pass']['#required'] = TRUE;
    $form['account']['current_pass']['#required'] = TRUE;
  }
}

The user register form can be overriden with either one

function MODULENAME_form_user_register_form_alter(&$form, &$form_state, $form_id) {
   //
}

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "user_register_form"){
    //
  }
}

The module has to be enabled and/or the cache should be rebuild for the system to see those functions


How to refer to a custom field in a node template?

The issue occurred because

{{ content.field_login_required }}

was used. Node should be used in place of content. The proper code is

{{ node.field_login_required.value }}


schema_fields_sql empty on entity_get_info

My first guess would be that the cache is somehow corrupted. To fix that you'll need to clear the drupal caches

If that doesn't help you'll need some more in-depth debugging.

For further debugging you'll need some easy way to execute code in your drupal environment. I'd suggest to use drush ev or drush php-script for that. -- Here is some information on how to install drush if you don't have it installed already.

At this point I think there are only two causes left:

entity_get_info() only populates schema_fields_sql if the base table key is present. So it might by that somehow the base table is not set. To check that take a look at the return value of module_invoke_all('entity_info'). For debugging you'll need to take a look at all modules in module_implements('entity_info').
If the original data in module_invoke_all('entity_info') includes a base table the only other way to corrupt the information is some implementation of hook_entity_info_alter(). Use module_implements('entity_info_alter') to find all modules you need to check.

If you need further help please provide at least the dump of entity_get_info() and module_invoke_all('entity_info').


find out object properties passed to a function

You can make use of the devel module for debugging.

Download and install the latest version of the Devel module.

dpm()
Prints a variable to the ‘message’ area of the page using

dvm()
Uses var_dump() to print a variable to the ‘message’ area of the page

So in your situation in your function use dpm($account)

function election_example_conditions_access_gmail($post, $account) {
   dpm($account)
  if ($account->uid == 0) {
    return FALSE;
  }
  return (bool) preg_match('/g(oogle)?mail\.com$/i', $account->mail);
}

and go to the page normally and you should see the debug backtrace appear in the message area


What's the best way to assign variables for use in multiple form modules?

It's hard to say what is the "best", but you can write a class, add the variables as constants, and then import the class wherever you need it.
For example, in MYMODULE/src/MyVariables.php:
<?php

namespace Drupal\MYMODULE\SharedStuff;

/**
 * Defines variables that need to be shared throughout the site.
 */
class MyVariables {

  // Seconds in an hour.
  const HOUR = 60 * 60;
  // Seconds in a day.
  const DAY = 24 * self::HOUR;
  // Seconds in a week.
  const WEEK = 7 * self::DAY;
}

And then in the PHP files where you need the variables:
use Drupal\MYMODULE\SharedStuff\MyVariables;
And then for the variable: MyVariables::HOUR


how to display a list of OG content depending on user group membership?

There is a pretty good tutorial of OG at https://drupal.org/node/1603460.

If you already know the basics and have provided proper access fields using the Organic groups access control module, you should next explore the views that come with OG and edit them to your liking.

Also the OG Extras module at https://drupal.org/project/og_extras has lots of stuff for practical use.


Prevent ajax submit function being called when it fails validation

Only thing you should have to put in your AJAX submit callback is this

  if (!form_get_errors()) {
    // Do your processing
  }
  else {
    // Return your form with errors.
   return $form;
  }


Change 'href' attribute in AJAX enabled links

Drupal link based Ajax, correspond to a Drupal.ajax['#id'] element object and drupal works with them not with DOM Objects.

So you don't have to change the href attribute you need to change the URL where it's doing POST in the Drupal.ajax element, in this case do this:

// Confirm structure first executing on console 'Drupal.ajax['#id'].options.url'
var href = 'hook_url/ajax/parameter1/parameter2';

// And change the href POST parameter
Drupal.ajax['#id'].options.url = href;

And it's done!


hierarchical select not working in multistep form

I'm hoping this will add more info to the above reporting, even though we have different websites, to hopefully enable a fix.
I have a 2 level hierarchical select taxonomy.  Refer to it in my people pages.  Created as Term Reference - Hierarchical Select. When registering a user go to select this term, which is supposed to save term lineage, forces user to select term from deepest level.

Selecting from pulldown menu and clicking add, it appears that the item is being selected correctly and shows up below the pulldown menu, with the option to remove the selection.  I then save, it says everything was saved correctly.  I scroll down to my selection, and it says nothing has been selected.

    If I go to a view based off of this information, it indeed finds no data.
    I do get data if I change the field from hierarchical select to List Select or check boxes and have the view be rendered taxonomy term.  If I have to use List Select I will have to change the terms to include the first level since it doesn't show or save this way. This list is going to expand as new courses get added.  We can't do check boxes perpetually.  It will get crazy long.

I did find this error message log, but I don't know after which change this appeared.
Notice: Undefined index: value in views_handler_filter_term_node_tid->value_validate() (line 219 of /var/www/vehicledev_ccom_nh/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc).

Severity
notice


Programmatically speaking, for term references you need to use the Term ID rather than the actual term name.

Luckily, the D7 Feeds module comes with a feature where it fetches the Term ID automatically for you based on the Term Name.

Here is an example of one of my mappings:


You can use the #tree property on both fieldsets, e.g.

$form['fieldset_1'] = array(
  '#type' => 'fieldset',
  '#title' => t('Title 1'),
  '#tree' => TRUE,
);

$form['fieldset_1']['name'] = array(
  '#type' => 'textfield',
  ...
);

$form['fieldset_2'] = array(
  '#type' => 'fieldset',
  '#title' => t('Title 2'),
  '#tree' => TRUE,
);

$form['fieldset_2']['name'] = array(
  '#type' => 'textfield',
  ...
);


Filtering Views to make several users see the node

It depends on what kind of view you're creating. You are probably working on a view for content. So the filters are limited to those related to content. You can add a relationship "Content: Author" (Relate content to the user who created it.) under "Advanced Options" to add more filter criteria to the filter criteria list (User will show up in the filter list then, too).

Or you try creating a view for users.

use the Views module to create the list – actually a list of users (rather than nodes/content).
use relationships settings to add in the interests, and finally
add a contextual filter on "user: uid" with a default value fetched from the currently logged-in user.


How can I show the latest added content to a specific link?

You can create a views page that shows the most recent video.

Structure > Views > Add new view

Title: "Videos"
Show content of type "Video" sorted by "Newest first"
Check "Create a page" option
Page title: "Video"
Path: "videos"
Display format: "Unformatted list" of "Full posts"
Items to display: "1"
Save & edit
Save again

Now go to the url: http://my-drupal-site.com/videos and it will display the most recent video via the view you created above


Download and enable Twig tweak module:

  Twig Tweak module provides a Twig extension with some useful functions
  and filters that can improve developer experience.

And then on your twig template put:

{{ drupal_view('view_name', 'block_1') }}

{{ drupal_block('block_id') }}

Themers Little Helper

  Some of the Filters and functions, backported from TFD7 theme engine
  and other things that can help a themer getting stuff done without to
  much hassle :)

{{ drupal_block(block_delta) }}

Bamboo Twig

  The Bamboo Twig module provides some Twig extensions with some useful
  functions and filters aimed to improve the development experience.

  Bamboo Twig has a lot of advantages and brings a lot of new features
  to the Twig landscape of Drupal 8. It boosts performance by using lazy
  loading, improves the code quality with automated workflow. It also
  includes automated unit and kernel tests to ensure stability.

{# Render the `system_powered_by_block` block #}
{{ bamboo_render_block('system_powered_by_block') }}


have a look at l() function in includes/common.inc:

...
if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
    (empty($options['language']) || $options['language']->language == $language_url->language)) {
  $options['attributes']['class'][] = 'active';
}
...


Just display list of all presets, there are links for flushing presets.
Presets list is available at /admin/build/imagecache/list

Flushing urls of respective presets would be /admin/build/imagecache/[preset_id]/flush


Patches uploaded on issues are automatically tested if they meet the right conditions which include:

not excluded based on name (described in description on upload field)
project has testing active
patch is again d6-8 banch

For core, testing is enabled; if you upload a patch against Drupal 7, for example, it will automatically be tested. For other projects, it can be enabled if you are a maintainer by looking at the "Issue" settings tab, there is a checkbox to enable testing.


How can I unset an option provided by the User Relationships module on the user edit page?

You also don't need to redeclare the $access variable, as you are just removing a field from the form array:

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (($form_id == 'user_register_form' || $form_id == 'user_profile_form') && $form['#user_category'] == 'account') {
    unset($form['user_relationships_ui_settings']['user_relationship_mailer_send_mail']);
  }
}

That should be all you need.


Sounds like you want to use search facets.  Facets are ways of showing various search 'tag' information for the current results with/without counts.  Note that this is slightly different from a filter which will show all values even if there is no result with the specified search criteria.

That said, there is a defunct facets core search module. As the module page says, the best way to approach this with Drupal 8 is to use the Facets module which requires the Search API module with the included Search API DB engine (no Solr required).

This will add a bunch of extra functionality that the core search will not handle.  Stuff like full text search across multiple text fields, stemmed searches (e.g. search for work also finds working, works, and the like), ability to show extracts (were the word was found), and much more.


Hi You have to follow below steps in order:

disable and uninstall module.
remove from settings.php and delete folder of module.
clear cache (make sure all tables are empty)

For users using drush:

drush dis memcache

The following extensions will be disabled: memcache
Do you really want to continue? (y/n): y

Thanks


Please check your theme's jQuery and Drupal jQuery conflicts. Check 'View source' and check the jQuery version the page using.

I had similar issue when used latest jQuery in my theme.


Migrating content with referenced taxonomy field is to be migrated by term name

i guess entity_lookup what you looking for:
here is an example from migrate_plus/src/Plugin/migrate/process/EntityLookup.php

field_tags:
       plugin: entity_lookup
       source: tags
       value_key: name
       bundle_key: vid
       bundle: tags
       entity_type: taxonomy_term
       ignore_case: true


Try Date module. This provides the cck widget to select the date.

The Select List date widget presents users with a drop-down list or textfield for each part of the date (year, month, day, hour, etc.). The whole selector is collapsed onto a single line using css (except for the timezone selector, if date-specific timezones are collected). The selector is highly configurable and you can set it up to use 5, 10, or 15 minute increments for minutes and seconds, or make some parts of the selector use textfields instead of drop-downs, useful to allow any year without creating a huge drop-down selector.

For more Documentation See here


Is there a better way to get a uid in a block than using Input Format PHP?

You should be creating your own block module for blocks that require custom PHP, custom PHP inside a form field is not very good security wise because of the way the PHP is parsed.

A custom block meaning

custom_hook_block() with the $block['content'] =>


Drupal commerce. How to show only products suitable for selected vehicle?

General solution is to use Entity reference.

You need two entity types:

Cars
Products

Products you have already, thanks to commerce. Cars can well be nodes so you can create content type for them using GUI. To products add entity reference pointing to cars. Then create a view with product to car relationship, filtered by car.

For categories, use regular taxonomy.


The ThemeKey module may be able to accomplish what you're looking to do.

The granular control it gives you as to when to show a specif theme is very impressive.


Save image from URL to a field from a custom module

Hope this will help  you,

In Drupal 7,  for your requirement I made some changes.

As system_retrieve_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file_managed table if you want it to be managed.

$node = new stdClass();
$node->type = "node_type";
node_object_prepare($node);
$node->title    =  'your title here';
$node->language = LANGUAGE_NONE;
$node->uid = 1;
$url = 'https://ssl.gstatic.com/gb/images/k1_a31af7ac.png';
//I have used picture folder to store images using image field settings
$file_info = system_retrieve_file($url, 'public://pictures/', TRUE);
if($file_info->fid){
    $node->field_image[LANGUAGE_NONE]['0']['fid'] = $file_info->fid;//assign fid
}
$node->field_test_field[LANGUAGE_NONE]['0']['value'] = 'test';//other fields
if($node = node_submit($node)) {
    node_save($node);
    drupal_set_message('submitted successfully');
}

Make changes as per your requirement.


Which hook can I use before or after submitting a webform form?

Take a look at the answer to Add a custom submission handler to a form. This will tell you how to add a submit handler to a form. You can use the same approach to add a custom submit handler to the webform and then perform the operations you want from the submit handler.


Quick fix: declare the class in template.php but instantiate it in your node template (if you check your php error log you probably had something like "Call to a member function red_form() on a non-object in ..." in it).  Also, I am assuming it's a typo that you had $colorforms and $color_form in your example above.


How to add "Content type B" from within "Content type A" and then display both together?

For the first part of your problem you can use Entity reference to create the relation between the content types:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

For the second part, one content type form inside another content type form you have this modules:

The Inline Entity Form module:

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.

Entityreference Autocreate

  A deliberately simple way to invent nodes on the fly in order to refer to them via entityreference.

References dialog (beta2 release only)

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog.

Autocreate Node Reference

  Autocreate Node Reference adds a node reference field and automatically creates the referred node by cloning a template node.

Node Reference Create

  Node Reference Create is an enhancement to the nodereference
  autocomplete widget that allows users to reference non-existent nodes.

Entity connect (rc5 release only)

  It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.

  The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.

Important: The module most used is Inline Entity Form, but it doesn't works with the Automatic Nodetitles module, but I know that Entity connect works fine with it. In addition with Entity connect you can edit existing entities. In my case I prefer Entity connect.

For the third part, the visualization of one entity (or more entities) inside another entity I think that you can use the EVA: Entity Views Attachment module, is very easy to use.

  "Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity. The body of a node or comment, the
  profile of a user account, or the listing page for a Taxonomy term are
  all examples of entity content.

I think that you should see this: Drupal 7 Node Reference Tutorial


Adding html subsites to Drupal 7 installation

I don't know anything about BlueHost or their tools, but the normal way to do that would be along the lines of:

Make a folder to house your HTML-only site
Put your site files in the folder
Set your webserver (Apache/Nginx/IIS) to direct requests for subsite.mysite.com to that new folder

Drupal is not involved in any way, shape or form.

So the answer is likely that there will be no problems, however I suggest asking this question of BlueHost as it really has nothing to do with Drupal.


How to add more field columns using Inline Entity Form table display

Consider using ief_table_view_mode module or hook_inline_entity_form_table_fields_alter()

For more information see answers to a similar question: How to show fields in the Inline Entity Form display widget?


XML feed data's are importing with the XML tags

You could use -

  tag/text()

This worked for me. It retrieves all the data that matches the tag.


Drupal best way to render content type data and meta-data

If I have understood well, here is what I would do:

Create a content type "Room", with specific fields and configuration (I guess you already did that).
Create several nodes of type "Room", one by actual room.
Create a View (using Views module) to display a list of all my nodes of type "Room" (I can tell you more about that if you need it) and where you can access the rooms page automatically. Of course, you can create a menu item in the same time. Very easy.
Create a custom static block with the banner, text, or whatever you want to be displayed on your View page.
Configure the block to be displayed only on your View page (path/to/your/view).

This is how I would have do that if I had to. I don't know if there is a better way but it seems quite logic and simple to me.

I hope it was the answer you wanted!

EDIT: I just remember the active menu item thing. I did that once in a project, it is a bit tricky but I can explain to you my method.


You need a derivative plugin, see views module for an example, it dynamically generates menu links for views configured to have a menu entry


How to create a Content Type field that will be only set by query parameters?

The Prepopulate module appears to be what you're looking for.


Drupal 7 requires a minimum of 32MB (see - http://drupal.org/requirements/php) however in reality it will require much more, simple sites with a few contributed modules should be around 96MB.

Personally I'd recommend 128MB minimum and then tweak as required.

You can use the Devel module to output the pages memory usage to help you.


If you don't need taxonomy you can always just disable the module.

If you still need the functionality but don't want the display pages to exist I guess you could implement hook_menu_alter() to remove them from the registry:

function MYMODULE_menu_alter(&$items) {
  unset($items['taxonomy/term/%taxonomy_term']);
  unset($items['taxonomy/term/%taxonomy_term/view']);
  unset($items['taxonomy/term/%taxonomy_term/feed']); // If you want to hide the feed as well.
}

I'd do some thorough testing after doing that though, I'm not sure if it would have any knock-on effects. Also if you're using the default taxonomy View for your taxonomy pages you'll obviously need to disable that as well.


How to display the TID of a term reference field in a content type?

One "hacky" way to do this:

{# First step: capture the rendered output of the internal path link for a term #}
{% set tid %}{{ content.field_category.0['#url'] }}{% endset %}

{# Second step: do some string processing on the captured output, removing the /taxonomy/term/ prefix and getting the TID #}
{{ tid|trim|replace({ '/taxonomy/term/' : '' }) }}

Good luck!


Context.module fires blocks on access denied pages. How do I stop this?

Use Context Error, and set the proper condition.


How to record unique hits in node counter stats?

Node view count

You may want to use the Node view count module for this. Here is a quote about it (from its project page, bold markup added here):

  ... allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

  This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

Specific to the D7 version of it, this is what is included also on the project page:

  Also now we count node views for anonymous users.

Statistics Advanced

Be aware of the  Statistics Advanced (*) issue "Port Statistics Advanced Settings to D7", with current status = needs review.

My "recommendation" for anybody looking for a D7 version of it, is to review what is attached to Comment # 55 in that issue. And report any potential deficiencies in that same issue (confirmations that it works fine would be appreciated too, also via that same issue).

Other modules to consider

If the Node view count and/or Statistics Advanced (*) module doesn't fit your needs, then you may want to consider reviewing this shortlist of possible alternatives (quotes are from their project pages).

Visitors (*):

  Displays information about visitors, and integrates with the WhoIs Lookup module

Better Statistics:

  introduces a Statistics API, which allows for a way to collect, limit, and route custom access statistics and data.

Piwik Web Analytics:

  Adds the Piwik web statistics tracking system (free open source) to your website.

  Related module: Piwik Reports, which provides graphical reporting of your site's tracking data inside Drupal.

Chartbeat:

  ... to provide third party integration with Chartbeat, for real-time site monitoring statistics.

Stat Counter:

  ... provides an integration between Drupal and StatCounter web statistics.

Enough options to "explore"?

Disclosure: I'm the maintainer of the modules marked with (*).


Customising Views Serializer JSON Output

You can create a module and extend ContentEntityNormalizer to provide a custom structure.

Example:

<?php

declare(strict_types = 1);

namespace Drupal\mymodule\Normalizer;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\image\Entity\ImageStyle;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\node\NodeInterface;

/**
 * Converts the Drupal entity object structures to a normalized array.
 */
class NodeEntityNormalizer extends ContentEntityNormalizer {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = [
    'Drupal\node\NodeInterface',
  ];

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function normalize($entity, $format = NULL, array $context = []) {
    $type = $entity->getType();

    $methods = [
      'library' => 'normalizeLibrary',
      'collection' => 'normalizeCollection',
    ];

    if (isset($methods[$type])) {
      return $this->{$methods[$type]}($entity, $format, $context);
    }

    return parent::normalize($entity, $format, $context);
  }

  /**
   * Normalize a library content type.
   */
  protected function normalizeLibrary($entity) {
    $attributes['id']       = $entity->id();
    $attributes['featured'] = !empty($entity->get('field_is_coming_soon')->value);
    $attributes['external'] = !empty($entity->get('field_is_stub')->value) && !empty($entity->get('field_website_link')[0]);
    $attributes['name']     = $entity->label();
    $attributes['subTitle'] = !empty($entity->get('field_subtitle')->value) ? $entity->get('field_subtitle')->value : '';

    return $attributes;
  }

  /**
   * Normalize a collection content type.
   *
   * @param \Drupal\node\NodeInterface $entity
   *   The node entity.
   *
   * @return array
   *   The item attributes.
   */
  protected function normalizeCollection(NodeInterface $entity) : array {
    $attributes = [];
    $attributes['id'] = $entity->id();
    $attributes['title'] = $entity->label();
    $attributes['subtitle'] = $entity->get('field_subtitle')->value;
    $attributes['summary'] = $entity->get('field_summary')->value;
    $attributes['card_type'] = $entity->get('field_directory_view')->value;
    $attributes['list_image'] = NULL;
    $attributes['card_image'] = NULL;
    $attributes['url'] = Url::fromRoute('entity.node.canonical', ['node' => $attributes['id']])->toString();

    $media = $entity->get('field_featured_image')->getValue();

    if (!empty($media)) {
      $item = $this->entityTypeManager->getStorage('media')->load($media[0]['target_id']);
      $image = $item->get('image')->getValue();

      $attributes['list_image'] = [
        'src' => ImageStyle::load('collection_listing')
          ->buildUrl($item->image->entity->getFileUri()),
        'alt' => $image[0]['alt'],
      ];

      switch ($attributes['card_type']) {
        case 'wide':
          $attributes['card_image'] = [
            'src' => ImageStyle::load('collection_listing_wide')
              ->buildUrl($item->image->entity->getFileUri()),
            'alt' => $image[0]['alt'],
          ];
          break;

        case 'tall':
          $attributes['card_image'] = [
            'src' => ImageStyle::load('collection_listing_tall')
              ->buildUrl($item->image->entity->getFileUri()),
            'alt' => $image[0]['alt'],
          ];
          break;

        case 'standard':
          $attributes['card_image'] = $attributes['list_image'];
          break;

        default:
          break;
      }
    }

    return $attributes;
  }

}

This code only applies to Node entities, and only for two content types (you will want to specify them, since this will override anything matching the $supportedInterfaceOrClass property.

You will need to add it to your custom modules services.yml file:

services:
  mymodule.node_entity:
    class: Drupal\mymodule\Normalizer\NodeEntityNormalizer
    arguments: ['@entity_type.manager']
    tags:
      - { name: normalizer, priority: 8 }

The View will now use this normalizer if the conditions match and you can structure the output however you like. This gives you the power say, to reach into entity references and pull in values or do conditional things (like the custom image size I am passing in normalizeCollection depending on a field value).

Note that my example is custom and does not do things like check field level access for the user, since we do not have any restricted fields.


How to bypass menu link access permission

You could create your menu links as /user/login?destination=/my-path and that will mean authenticated users would get taken to /user/login but then instantly redirection to /my-path because they're already logged in

Anonymous users will see the menu links and be taken to the login page if they tried to click them


Edit you field in Manage fields section of your content type and set default value for that date field.


How can I grant permissions to anonymous users per session to download a file?

Take a look at Webform protected downloads. It's a module I wrote a while ago to tackle this kind of situation.

Edit: Ah, sorry, just read your question again. The part with the modified pdf content depending on user input is not addressed by my module. Though, as the system uses the private file system you could maybe hook into there. This is not trivial though.

I see another easier option. You create a custom menu callback and use webform hooks or the redirect configuration of the webform to send the user to this url that contains the submission id of the webform (say, special-pdf-access/SUBMISSION_ID). With this information you can load the submission, thus accessing all the data entered by the user, then create a pdf file with this info and display a link to that file.

You have to pay attention to security though, so as not to allow arbitrary users to load pdf files they shouldn't have access to. For this you can use the global $_SESSION variable, to store the submission id after webform has processed the submission, and then check in the custom menu callback if the submission id in the session equals the requested submission as given in the url.


How to create a menu navigation on a Views page that uses contextual filters?

Open the view where you had created the pages at projects/%/details or projects/%/people.

Under page settings where you had the path filled, add these additional settings to create a Menu tab or a Contextual link.

Go to Menu and select Menu tab as the type and fill in the title. If you want the link to be present as a contextual link, check the box which says context.

You can also set access permissions on who can see this tab depending upon the permission type you had selected.


How to set one content type to only one language in a multilingual site?

Install the Entity Translation module then go to edit your content type and under Publishing options in Multilingual support check the option  Enabled, with field translation

Go to: YOUR_SITE/admin/config/regional/entity_translation and configure your content type like this:

Obviously I select French but in your case you must select Arabic.


You can use the link directly as /user. It also goes to the profile page which is similar to the /user/{$GLOBALS['user']->uid}
Now if you want user id also with it, e.g profile in edit mode (user/10/edit) then you need to add Menu Link module. It provides  you option to use Token to make the link dynamic for every user profile instead of static path.
Hope it will help.


Error while loading / saving taxonomy term on external DB

SOLVED!
after long head bashing, what fixed this for me was to manually empty the "cache" tables with PMA on the "shared" DB!

important to notice that Drupal native Clear Caches didn't do the work, it had to be removed from the DB!


The first mistake in the code is how the additional submission handler is added. You should add it with the following code:

$form['actions']['delete']['#submit'][] = 'delete_mem';

If you want to be sure that submission handler is executed first, you should use the following code:

array_unshift($form['actions']['delete']['#submit'], 'delete_mem');

The second error is the argument declared for the form submission handler that, as shown in this documentation page, should be:

function delete_mem($form, &$form_state) {}

As consequence of this, if you defined your function as function delete_mem($node) and you call node_delete($node->nid) from that function, node_delete() doesn't work because what you are calling $node is really a form array, which doesn't contain the nid property; what you are passing to node_delete() is NULL, and the function doesn't delete any node. Eventually, NULL could be converted to 0, but there aren't nodes using 0 as node ID, and the function will not find any node to delete.
If you are using a Drupal development snapshot, you would get a warning about accessing a property of something that is not an object.

Supposing that you are altering the node edit form, the submission handler you are writing has access to the node object through $form_state['node']; the node ID can then retrieved with $form_state['node']->nid.

You can check the code executed from the default submission handler added from the Node module to the "Delete" button, which is the following one.

function node_form_delete_submit($form, &$form_state) {
  $destination = array();
  if (isset($_GET['destination'])) {
    $destination = drupal_get_destination();
    unset($_GET['destination']);
  }
  $node = $form['#node'];
  $form_state['redirect'] = array('node/' . $node->nid . '/delete', array('query' => $destination));
}

It uses $form['#node'] to get the node object, and $node->nid to get its node ID. Consider the note added in node_form() about $form['#node'].

  // @todo D8: Remove. Modules should access the node using $form_state['node'].
  $form['#node'] = $node;

This means that using $form['#node'] would not working anymore on Drupal 8 (or any future version), while $form_state['node'] would still work for Drupal 8 and any future Drupal version.

In this case, your submission handler doesn't need to call node_delete() as the function is already called from the submission handler added from the Node module to the "Delete" button. If you really need to delete information about a node that is being delete from a database table that your module uses, then you should implement hook_node_delete().

  I have also tried to figure out a way to use the default callback hook_node_delete()

hook_node_delete() is a hook that needs to be implemented. If your module is bhl.module, the function that needs to be written has the following signature:

function bhl_node_delete($node)

That hook is implemented when you need to delete data saved from your module in its own database table, where you save some custom data and the node ID. It is not required to delete a node, which a task already done from node_delete_multiple(), which contains the following code.

try {
  foreach ($nodes as $nid => $node) {
    // Call the node-specific callback (if any):
    node_invoke($node, 'delete');
    module_invoke_all('node_delete', $node);
    module_invoke_all('entity_delete', $node, 'node');
    field_attach_delete('node', $node);

    // Remove this node from the search index if needed.
    // This code is implemented in node module rather than in search module,
    // because node module is implementing search module's API, not the other
    // way around.
    if (module_exists('search')) {
      search_reindex($nid, 'node');
    }
  }

  // Delete after calling hooks so that they can query node tables as needed.
  db_delete('node')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('node_revision')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('history')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('node_access')
   ->condition('nid', $nids, 'IN')
   ->execute();
}

Inside the implementation of hook_node_delete(), you don't call node_delete(), or you cause an infinite loop. In fact, node_delete() calls node_delete_multiple(), which then invokes any implementation of hook_node_delete(), including yours that would call node_delete(), that would call node_delete_multiple(), which again would invoke any hook_node_delete() implementation, including yours.

As general suggestion, the functions defined from a module should always be prefixed from the short module name. In your case, if the hook function is bhl_form_alter(), the submission handler should be bhl_delete_mem().


How to apply Simple Regex Filter to forum signature?

It's impossible without your own coding. Currently this module works only on nodes and comments, and this is hardcoded. Given that it is:

  Development status: Maintenance fixes only

you can't hope maintainers will add functionality; they already told they will not.

If you are using Signatures for Forums for Drupal 7, you can try with modules working generically on Entities. As far as I remember Rules could be used for something like that. For Drupal 6, I'm not prepared to even speculate.


Node.tpl.php file: Check is several fields are empty

Put all the logic in your template.php (or wherever your preprocess functions go) with THEME_preprocess_node():

function THEME_preprocess_node(&$variables) {
  // Grab the node
  $node = $variables['node'];

  // Only run for your content type
  if ($node->type == 'your_content_type') {

    // Grab your fields with field_get_items so that it is translation friendly
    $location_field1 = field_get_items('node', $node, 'location_field1');
    $location_field2 = field_get_items('node', $node, 'location_field2');
    $location_field3 = field_get_items('node', $node, 'location_field3');
    $object_field1 = field_get_items('node', $node, 'object_field1');
    $object_field2 = field_get_items('node', $node, 'object_field2');
    $object_field3 = field_get_items('node', $node, 'object_field3');

    // Check if all location fields are set or not
    if (isset($location_field1[0]['value']) && isset($location_field2[0]['value'] && isset($location_field3[0]['value'])) {
      // Create a variable that can be used in your node.tpl.php
      $variables['messages']['location_message'] = 'All location fields are set...';
    } else {
      // Create a variable that can be used in your node.tpl.php
      $variables['messages']['location_message'] = 'All location fields are not set...';
    }

    // Check if all object fields are set or not
    if (isset($object_field1[0]['value']) && isset($object_field2[0]['value'] && isset($object_field3[0]['value'])) {
      // Create a variable that can be used in your node.tpl.php
      $variables['messages']['object_message'] = 'All object fields are set...';
    } else {
      // Create a variable that can be used in your node.tpl.php
      $variables['messages']['object_message'] = 'All object fields are not set...';
    }
  }
}

Then, in your node.tpl.php you will have access to the message and you can print it anywhere with:

print $messages['location_message'];

and

print $messages['object_message'];


How copy file field data from one file field to another using Views Bulk Operations?

Here is a pure site-building approach:

Install File Field Rules
Define a new Rule Component (an "Action set"), named e.g. "Copy file"

Define at least one input/parameter, e.g. node_source
Define optionally a second input/parameter, e.g. node_target

Configure your Rule component to perform a "Copy file field contents" action, with the following settings:

Source entity => e.g. 'node_source'
Destination entity => e.g. 'node_target': This depends on your case, you may even want to copy a file inside the same node, between different fields. You can in that case, use 'node_source' again as your target entity.
Select the Source and Destination fields
Save our component and you are done with Rules configurations.

Back to your View and VBO field configuration, you can now select the "Copy file" action.

I tried this and was able to copy an image file between two different article nodes, hope it works for you too.


Twig: How to show static text in the template to the Anonymous User?

Add a page--403.html.twig template to your theme.
See this change record: https://www.drupal.org/node/2960810
If you only want to change the default message you don't need a template. You can configure a node as access denied message in /admin/config/system/site-information.
Caveat for the non-template solution (as commented by @FreeRadical): If you restrict access to all nodes you have to find a different type of content. Could be a small module providing a custom controller which returns the static text.
BTW the themed page--403.html.twig is built in a subrequest which only job is to return a themed page with blocks. It's too late to make decisions on what to do with a 403 exception at this point. If you want to replace the core handling of a 403 exception (returning a themed subrequest) use an exception subscriber with default priority. See https://drupal.stackexchange.com/a/245211/47547


Drush can not connect to mysql when run a Drupal in a Docker/Azure

It looks like the environment variables are defined only for HTTP requests. In other words, they seem to be set in FPM, NGINX, or Apache, but not in your shell.

Try typing echo $MYSQL_DATABASE in your shell. If that outputs nothing, you'll have to export the environment variables first, so Drush can see them.


You've simply used the wrong template. page--user.tpl.php affects "user pages" like, as you've discovered, the user login.

The template you want to create and modify is user-profile.tpl.php https://api.drupal.org/api/drupal/modules%21user%21user-profile.tpl.php/7


Create update table of features vs plans

You might want to give a try to Editable Views module. So you would create a view page with columns and rows as you desire, making all the fields editable. Then you could change any field value (boolean if checkbox is used) just in place.


Getting the logged in username and email in a view

Yes. Just create a view with base table of (user). Then add your fields of username and email. Then add a contextual fileter of uid and set a default value for logged in user.


Here is a link that shows all the arguments you can pass to MigrateFileFieldHandler. As you can see description is the 7th argument.

If you don't want to specify any of the arguments before description, you still have to pass NULL to them e.g.:

$arguments = MigrateFileFieldHandler::arguments(
  drupal_get_path('module', 'my_migrate').'/docs',
  'file_copy',
  FILE_EXISTS_RENAME,
  NULL,
  NULL,
  NULL,
  array('source_field' => 'migrate_source_description_field'), //Can also pass a string here
);


Login form and registration form not properly displayed

Modal forms (with ctools)

  Supported forms Log in
  (modal_forms/nojs/user/login) Request new password
  (modal_forms/nojs/user/password) Create new account
  (modal_forms/nojs/user/register) Contact
  (modal_forms/nojs/user/contact)

It is also possible to build links manually.

    Modal Login
    Modal Login


You should use the node_view() function to prepare the correct output for your required view mode:

$view_mode = 'teaser'; // Or 'full' for example

$node = node_load(1473);

$view = node_view($node, $view_mode);

print render($view);


How do I theme a blog listing page for a specific taxonomy term?

Blog list pages render node teasers. I think that the automatic template suggestion patterns would only operate on node attributes and taxonomy is not one.

You can add this to your theme's template.php file

function THEME_preprocess_node(&$variables) {
  // check for blog and teaser
  if ($variables['type'] == 'blog' && $variables['view_mode'] == "teaser") {
     // check for taxonomy term on node
     dpm($variables);
     if ($variables['field_TAXONOMYFIELD'][LANGUAGE_NONE][0]['tid'] == TAXONOMYID) {
       // change the readmore link here or add code for template file
       $variables['content']['links']['node']['#links']['node-readmore']['title'] = "Custom Read Me";
     }
  }
}

If you don't want to override the readmore link inside the preprocess function but absolutely want a template file, then you can instead do this:

array_unshift($variables['theme_hook_suggestions'], "node__blog__blahblah");


How do I choose a default theme if the theme gives a white screen?

You can update in database.

Change the active theme in the database

The default theme setting is stored in Drupal's database, and thus can be changed by manipulating the database from the command line or an administration overlay or client like PHPMyAdmin or MySQL Workbench for MySQL.

Always make a backup of your database before changing values in it directly, as it is possible to destroy data and render your site unrecoverable at the database level. You have been warned.

In Drupal 6 and 7, the setting is stored in the system table:

activate a trusted theme

UPDATE system SET status=1 WHERE name = 'garland';

change the default setting

UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';

clear the cache tables

TRUNCATE cache;
TRUNCATE cache_bootstrap;
TRUNCATE cache_block;

Another way

sites/default/settings.php:
$conf['theme_default'] = 'bartik';


Can use taxonomies to I build a list of "conditions" that can be added to and referenced from different nodes?

I'm not sure if you can get this done with taxonomies. However I would recommend you to have a look at either of those modules also (or "instead"?):

Entity reference.
Entity connect.

These 2 modules are also recommended in the (illuminating) article "Relativity Model for Drupal", for which this is an introduction to it (quoted from this linked page):

The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:

Data architecture and data modeling merging as a single step through a documentation procedure.
Customized user interfaces that cater to individual workflows throughout permission roles.
Multi-level relational data structures that relate to other multi-level relational structures.
Mimicking the concept of database joins within Drupal's UI's.
Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The small handful of modules (cfr. the last bullet) is detailed on Interface elegance and experience.


How can i fix broken link of an image being viewed in Drupalgap after being uploaded with Drupalgap also

It sounds like you need to add this to your settings.php file:

$conf['image_allow_insecure_derivatives'] = TRUE;


How do I create a custom field storage back end?

Field types implement FieldStorageDefinitionInterface. In Drupal core, there is FieldStorageConfig and BaseFieldDefinition.

So if the desire is to change field storage to an arbitrary file store, then you should create an abstract class similar to BaseFieldDefinition, and have your Field Type classes extend it.


Returning an entity from a custom Rules action

If you check the rules hook hook_rules_action_info docs, you'll see the provides element:

  provides: (optional) An array describing the variables the action provides to the evaluation state with the variable name as key. Each variable has to be described by a sub-array with possible attributes as described afterwards, whereas the name of a parameter needs to be a lowercase, valid PHP variable name.

Usage example from commerce_cart module:

  $actions['commerce_cart_product_add_by_sku'] = array(
    'label' => t('Add a product to the cart'),
    'parameter' => array(
      'user' => array(
        'type' => 'user',
        'label' => t('User'),
        'description' => t('Specify the user whose shopping cart order the product will be added to, typically site:current-user.'),
      ),
      'sku' => array(
        'type' => 'text',
        'label' => t('Product SKU'),
        'description' => t('The SKU of the product to add to the cart.'),
      ),
      'quantity' => array(
        'type' => 'integer',
        'label' => t('Quantity'),
        'default value' => 1,
      ),
      'combine' => array(
        'type' => 'boolean',
        'label' => t('Combine similar items in the cart'),
        'description' => t('If checked, the product will be combined added to an existing similar product line item in the cart by incrementing its quantity.'),
        'default value' => TRUE,
      ),
    ),
    'group' => t('Commerce Cart'),
    'callbacks' => array(
      'execute' => 'commerce_cart_rules_product_add_by_sku',
    ),
    'provides' => array(
      'product_add_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Added product line item'),
      ),
    ),
  );

Note that you need to return an array from your action with the parameters named, for this example, 'product_add_line_item':

// Only return an added line item.
if ($line_item = commerce_cart_product_add_by_id($product->product_id, $quantity, $combine, $uid)) {
  return array('product_add_line_item' => $line_item);
}

So potentially you could provide as many elements as you need in your actions for further actions or rules components.


Use a field collection instead of the straight up image field. The field collection would have an image field and a term reference, plus maybe more things once you see its power.
The trade off is that your views will become a bit more cumbersome to build, but only slightly.


Export/Deploy Drupal site/page to static? (no cache)

I use HTTrack for this, also there's this article on drupal.org: Creating a static archive of a Drupal site.


The solution was to implement entity-level constraints. This allows Drupal to manage the data that gets typed into the widgets, and no additional (widget-dependent) validation is necessary.

Apparently, the idea in Drupal 8 is that most entity-related validations are not done via the form validations. Instead, so-called constraints can be added, either on the field level to affect only one field, or on the entity level to affect multiple fields.

This GitHub repo contains example files for creating entity-level constraints, which were very helpful. You will need to create files for the Constraint and for its Validator. Furthermore, you will need to attach the Constraint to the Entity, which can be done either using hooks (as demonstrated in the .module file, see link above) or by adding this to the annotations of your entity:

 *   constraints = {
 *     "ExampleConstraint" = {}
 *   }


Entity field value inherited from another entity programmatically?

The way I would tackle this is to create a new field type called “parent_value”.Design it in such a way that it doesn’t actually store any data in the database but instead uses the existing object’s entity reference value to look up the value from the parent. This way you don’t have to rely on any sort of Dripal trigger to alter the value in the child, which will ensure that if values are updated programically, they will still match.

There is also the added advantage that creating a custom field will teach you everything you need to know about Drupal 8 plug-ins.


Got error message from Deleting Vocabulary

Please see this post https://drupal.org/node/1719600 as it explains that the function has a typo. I would recommend updating to the latest version of the metatag module.


The default for an unprovided uid property to a comment entity is 0, so with your current code it will always be owned by an anonymous user. If you want a specific user, you have to be specific in the request.

It can just go straight in the payload though:

{
  "nid": "401",
  "uid": "123",
  "subject": "Comment Subject sdfsdf ",
  "comment_body": {
    "und": [
      {
        "value": "Comments body sdfsnd fsd fds "
      }
    ]
  }
}

You have access to uid from the return value from the login, so it's easy to get hold of.


Using hook_form_alter() to prevent free email addresses from registering on a Drupal 6 site

A very simple example would be:

function example_mail_form_user_register_alter(&$form,&$form_state) {
  $form['mail']['#element_validate'] = array('example_mail_validate');
}

function example_mail_validate($element, &$form_state) {
   //block gmail addresses
   if (stripos($form_state['values']['mail'], 'gmail.com') > 0) {
     form_set_error('mail', t('Free email is not allowed.'));
   }
}

However you should lookout for more advanced solutions:

Simple email verification: email verify
http:BL

  http:BL can prevent email address harvesters and comment spammers from
  visiting your site by using a centralized DNS blacklist.
  Mollom which also prevent spam on all your content/comments forms.


User with permission can't add an event to calendar by clicking

Can you clarify? You said:

  users, who are allowed to add an event, can't do it. They can add an
  event by navigation and clicking on"add content", but they can't do it

what do you mean they can't do it? Can they navigate to /node/add/[event] (I'm not sure what your event node type is called)? Or when they do go to /node/add/[event] does something happen when they try to save the new event?

Are you sure you have the permissions set correctly for their role? Check out the permissions at admin/people/permissions. Double check the permissions under Node.


Do 'edit node' redirect via custom PHP code?

Here is the right code, or at least code that works:

$nid = db_result(db_query('SELECT nid FROM {node} WHERE uid = %d', [account:uid]));
$_REQUEST['destination'] ='node/' . $nid . '/edit';


Drupal 8: How to retrieve field values when i use loadMultiple to load multiple node ids

You should do like

$node_storage = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($node_storage as $node){
   $field_merchant_id = $node->get('field_merchant_id')->value;
}

Here you are using "user" which should be replaced by "node" to access node values.
And also to access "field_merchant_id", you need to get that from $node.


Passing variables from modulefunction to theme

Short but painfully: there is no way to achieve that. The page.tpl expects that your part of the code is a renderable array or HTML output fully generated in your page callback show_uspage(). Your part of the code is injected into the $variables of hook_preprocess_page() where ever the content block is placed in region settings for your theme. Your page callbacks really just handles the part of the output where the content block is placed. You can not store any data from your page callback for later use in theme layer or send the data by any mean to the page preprocess function or any other theming function for the page.tpl.

The only way would be to use hook_preprocess_page() and to add any data here again. You must use this hook even when you add data just for a specific page - you just need to assure to do that in this case and not on every page. Maybe by checking on which path the user is (like if(current_path == 'uspages')).

Another way would be to store the data in session in re-use it in hook_preprocess_page.


How to programmatically create an entity and fill in entity reference fields

The column name for a field isn't always value; in the case of entity references it's target_id if I remember rightly.

Try this:

$entity = entity_create('mytype', $values);
$entity->field_ref = array('und' => array(0 => array('target_id' => "2")));


How to adjust the length of [node:summary] for metatags?

You can do a few different things.
Assuming you are using the metatag module.

1) Prevent metatags from saving with more than 150 chars using a presave hook:

function hook_metatag_presave(&$metatags, $entity_type, $entity_id, $revision_id, $langcode) {
  dsm($metatags);//debug what the array is. You can trim the values for the metatags here.
}

2) Alter the metatag before bing cached:

/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 * @param array $options
 *   All of the options used to generate the meta tags.
 */
function hook_metatag_metatags_view_alter(&$output, $instance, $options) {
  if (isset($output['description']['#attached']['drupal_add_html_head'][0][0]['#value'])) {
    $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'] = truncate_utf8($output['description']['#attached']['drupal_add_html_head'][0][0]['#value'],150);
  }
}


Below are a couple of things you can try to reduce duplicates caused by a multi-value field. Results will vary depending on your particular view.

1. Use aggregation

Under "Other" in Advanced options, enable Use aggregation.

Locate the offending field under "Sort criteria". Click on Aggregration settings, then select Aggregation type: Maximum.

2. Filter by delta

Under "Filter criteria", add the delta equivalent of your multi-value field; e.g. if your field is "field_artist_bio", there should be another field available called "field_artist_bio:delta".

Add the field. Set Operator: is equal to, Value: 0.


How to split content over different regions... views?

An simple solution is to use the Panels module and Page Manager from ctools module to override the default node page for your content type.  That way you also do not have to worry about menus, sitemaps etc.

The downside is that you cannot easily use the blocks defined in the template to position parts of the nodes content.


How can i hard-wire a link, in blocks, using $base_url or something similar?

Hard wired to what?

Personally I like to hard wire my URLs the the root of the site. If my site is always a full domain name as wwww.mysite.com The url would be:

 Archives

This is relative to the root of the website. Which makes sense to me. You can move your site to a new domain, www.mysite2.com, and this Path will still work.

If you move your site to a sub-directory later then .htacess BaseRewrite rules can still allow this to work.

I find trying to make a url work for any combination of directory prefixes or a subsite in a folder, etc .... to much of a pain to deal with.


Why isn't the user #1 able to edit the user details?

This is probably a conflict/misconfiguration of some module (or permissions) you have installed on the site and that deals with users or permissions.

Super user (uid: 1) has all privileges, whether or not the admin role exists.

Make a dev version of the site and start disabling modules one by one to find which one caused this.

Which modules do you have installed? Any custom modules? Is there anything in the database/error log?


HTML Mail not working with custom module

The configuration can be done through the Mail System UI.  Here is how I send HTML messages with a custom module without a template.

First, install HTML Mail and Mail System as you already have.

Next, create your module and implement hook_mail() and add an identifier (key) to use when sending.

function hook_mail($key, &$message, $params) {
  switch ($key) {
    case 'MODULE_unique_sending_key':
      $message['Reply-To'] = $params['Reply-To'];
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];
      $message['headers']['Reply-To'] = $params['Reply-To'];
      break;
    }
}

Next, implement drupal_mail().

$key = 'MODULE_unique_sending_key';
$message = drupal_mail('MODULE', $key, $to, LANGUAGE_NONE, $params, $from);

Lastly, you will need to tell Drupal to use the HTMLMailSystem to send when using the 'MODULE_unique_sending_key' key.

To do this, go to admin/config/system/mailsystem and go to 'New Setting.'

Under module, choose your custom module.

Under Key, enter your unique message identifier you used in drupal_mail().

Now, while still on the admin/config/system/mailsystem page look under 'MAIL SYSTEM SETTINGS' look for the Module+Key combination you just created.

From here, you will need to select the HTMLMailSystem as your sending class.  Save and test your module.  HTML mail should now be working without using a template.


How to load a view via ajax without breaking ajax functionality?

After examining the ViewAjaxController.php ajaxView() function, I came up with the following solution, which seems functioning for me. I created an ajax endpoint which extends ViewAjaxController and sets the requested view and display in the Request object then calls the parent ajaxView() method.

1. Define the route

my_module.routing.yml

my_module.views_ajax:
  path: '/admin/views/{nojs}/{view_id}/{display_id}/{args}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleViewAjaxController::ajaxView'
  requirements:
    _permission: 'access content'

2. Create the controller

src/Controller/MyModuleViewAjaxController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\views\Controller\ViewAjaxController;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MyModuleViewAjaxController
 */
class MyModuleViewAjaxController extends ViewAjaxController {

  public function ajaxView(Request $request) {
    $view_name = $request->get('view_id');
    $display_id = $request->get('display_id');
    $dom_id = "{$view_name}__{$display_id}";

    $request->request->set('view_name', $view_name);
    $request->request->set('view_display_id', $display_id);
    $request->request->set('view_args', $request->get('args'));
    $request->request->set('view_dom_id', $dom_id);

    return parent::ajaxView($request);
  }

}

3. Create a wrapper
 to embed the view

The
 where you want to load a view via ajax has to have a specific css class in form of: .js-view-dom-id-{view_id}__{display_id}. Here replace the placeholders for view and display ids with the actual ones you want to embed.

4. Load the view via ajax link

Now you can load the view creating links like:

    This link will load the view {view_id} display {display_id} with the
    arguments {args}


Set author to the node automatically whenever the new user registered and also automatically authenticate the user

Create a custom module and  Use below logic hope it will work.

function hook_user_insert(&$edit, $account, $category) {
  $email = $account->email;
  $uid = $account->uid;

  $query = db_select('field_email', 'e');
  $query->addField('e', 'entity_id');
  $query->condition('e.field_email_data', $email, '=');
  $nids = $query->execute();

  foreach($nids as $nid){

    //Update node user
    $node = node_load($nid); // ...where $nid is the node id
    $node->uid    = $uid;
    node_save($node);

   //Add role to user
   $role_name = 'member';
   if ($role = user_role_load_by_name($role_name)) {
     user_multiple_role_edit(array($uid), 'add_role', $role->rid);
   }

  }

}


How to display articles based on group combinations of various group types?

I think your understanding of membership is not correct. So first a clarification:

Users can be member of one or more groups.
Content, such as articles, can be assigned (= belong to) a single group.

With that in mind, you may want to try an approach like so:

Create a group type of, say, Regional departments (a single group type should be enough for your case).
Create various groups, of group type Regional departments, named something like so (with names that should be self explaining):

Paris - Sales
Paris - Support
Paris - Accounting
Paris - R&D
Paris
Nice - Sales
Nice - Support
Nice - HRM
Nice

For any user, create group memberships depending on their region (Paris or Nice), and depending on their (what you call) departement (Sales, Support, etc). Special case: for each user, also create a group memberships depending on their region (Paris or Nice).
Whenever you create content (articles), you assign it to the appropriate group. Special case: if you assign it to (e.g) group Nice, then any Nice departement has access to it.

That's really it. But on top of that, you can optionally:

Change to which group an article belongs (e.g from 'Paris - Sales' to 'Nice - Sales', eg when sales territories get reorganized).
Grant or revoke access for selected user(s) to specific content (articles), simply by changing their group memberships (e.g if a user gets tranfered to another departement).


Some obvious giveaways to the site being drupal 7:

RDF in the <head> section in the HTML
Meta tag of <meta name="Generator" content="Drupal 7 (http://drupal.org)" />
Executing jQuery.fn.jquery; reveals the jQuery version to be 1.4.4 or 1.5.2 (with jQuery update)
Only a single <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> - this is a famous drupal 6 bug (it has two in the <head> section
HTTP response header of X-Generator: Drupal 7 (http://drupal.org)

Other options include using 'sniffers', my favourite being 'Whatweb' - https://github.com/urbanadventurer/WhatWeb. Whatweb is a (ruby) command line tool that can sniff not only the fact that the site is using drupal, but often the major and minor version as well


The user login block form is a special case.  You will see that in the #action property, it defaults to /node?destination=node.  The "destination" is the important piece, as it will override many of the normal avenues you would take to redirect the form including a $form_state['redirect'] in a submit handler.  The code below is an example of how you can redirect the user_login_block form by modifying the #action property.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ('user_login_block' == $form_id) {
    $path = 'path/i/am/redirecting/to';
    $form['#action'] = url($_GET['q'], array('query' => array('destination' => $path)));
  }
}

Also, take a look at hook_form_FORM_ID_alter(), which is the preferred method for altering the form for performance reasons.


Translate dynamic variable that is an array in twig or using t()

I think it's better to split the content in translatable parts:
  <p>{% trans %}The variables are{% endtrans %}
    {% for i in array %}
      {% trans %}{{ i.number }} times {{ i.name }}{% endtrans %},
    {% endfor %}
    , {% trans %}and {{ last.number }} number of {{ last.name }}{% endtrans %}
  .</p>

Haven't tested this so I'm not sure if it works. Also, you could use trans as a filter, check this question.