How can I have a view to load more rows on clicking a "Load more" button?

Looks like Views Infinite Scroll  is a good option for you:

  Views infinite scroll allows you to load and display pages of any view inline, using AJAX (this has been called infinite scrolling, load more, autopaging, endless pages and more). The pager can be triggered with the press of a button or automatically as the user scrolls to the bottom of the view's content.

Here's the pager settings:


Display webservice response in a paged table

You need a generic array pager for paging data that isn't available in your Drupal database.
There's a community documentation page available providing information about the subject.

From the page Paging non-SQL data:

With the following function, you can use the Drupal core pager with any array with only two lines of code:

/**
 * An generic array pager for Drupal.
 * For Drupal 5 and 6, the default limit is 10. For Drupal 7 it is 9.
 */
function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

The usage is as simple as:

  $output = '';
  $tree = taxonomy_get_tree($vocab->vid);
  $tree = pager_array_splice($tree, 5);
  // Do something with the 5 terms
  $output .= theme('pager', array('quantity' => 5));


Treating string field as numeric to use as an exposed filter

Excellent question!
You only need the hook_views_query_alter function, here is what it should look like:

function MY_MODULE_views_query_alter(&$view, &$query) {
  if ( $view->name == 'manage_users' ) {

    // For filtering
    foreach($query->where[1]['conditions'] as $key => $condition) {
      if ( $condition['field'] == 'field_data_field_count.field_count_value' ) {
        $query->where[1]['conditions'][$key]['value'] = array(':val' => (int)$query->where[1]['conditions'][$key]['value']);
        $query->where[1]['conditions'][$key]['field'] = 'CAST(' . $query->where[1]['conditions'][$key]['field'] . ' AS UNSIGNED) >= :val';
        $query->where[1]['conditions'][$key]['operator'] = 'formula';
        break;
      }
    }

    // For sorting as well
    foreach($query->orderby as $key => $condition) {
      if ( $condition['field'] == 'field_data_field_count_field_count_value' ) {
        $query->orderby[$key]['field'] = 'CAST(' . $query->orderby[$key]['field'] . ' AS UNSIGNED)';
        break;
      }
    }
  }
}

Most important parts in this code snippet:

Using CAST to change the varchar into an integer [doc]
Using the 'formula' operator to instruct views that you are using a complex SQL expression, check the source code of add_where_expression!  [doc]

Good luck!

Update Note: Even though this is working fine, the more elegant/readable way would be to have a function (equivalent to add_where_expression) that would allow overwriting a where/having condition.


How to fix Admin Menu that's broken on live site, working on identical dev site

It was a file permission problem!

It turns out that, as per Apache's and Drupal's recommendations, I had set the permissions for all folders/directorys in my sites/all/* folder to be 750, and 640 for files. So for those who don't know, that means that 'others' (people who don't 'own' the files or folders) can't access them in any way.

It seems that my web host had incorrectly not assigned Apache to the correct group so that it would be able to run using those safe permissions (I know why, and I'm going to send them an irritated email asap).

I simply used Filezilla to recursively change the permissions to 755 and 644 respectively. Not quite safe, but I can change them back later.


Why does core uses the lib directory instead of the src one, for its classes?

The following document explains the differences between PSR-4 and PSR-0, and the reason why PSR-4 was suggested.

It also explains that PSR-4 complies with the PSR-0.

Basically, when working with packages (modules) PSR-4 is preferable.
But the base package can still use PSR-0 and be readable.


How to define an entity type within entity_get_info()

I found it. You use the hook_entity_info() hook.

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


How to Add rel="nofollow" in "Add new comment" link in teaser?

You could do this by implementing hook_node_view_alter in your custom module or theme.

//replace MODULENAME below with your custom module's name
function MODULENAME_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    $build['links']['comment']['#links']['comment-add'] = "rel=\"nofollow\"";
  }
}

This is for node type book, you could replace it by the content type you are using.

Here is the Module developer's guide, which should get you started.


The reason you see so many abandoned projects is that instead of maintaining multiple separate modules for individual packages, work has gone into making those packages compatible with the WYSIWYG API module. By abstracting the editor library from the editing interface, you gain the ability to use different editors for different input formats, and it becomes quite simple to swap one out for another.

According to the project page, WYSIWYG API has direct integration with

CKEditor
FCKeditor
jWysiwyg
markItUp
NicEdit
openWYSIWYG
TinyMCE
Whizzywig
WYMeditor
YUI editor

as well as a whole host of useful plugins.


try checking the "media library" in the settings of the field, as seen on the picture in the Quick Start Guide


ubercart invoice generation to allow user to request funds withdrawal

If you are implementing the "service" as part of your site, you can attach the "services" to the user by assigning permissions to the "service" to a role, then create a content type, enable it as product and attach a "feature" to a product to enable the role for a limited amount of time (if this is your business model).

This would use CCK (to define the product) + Ubercart (for setting up the shop and attaching Product + feature to product) as well as Permissions (to your "service") and Roles (to apply to the permissions).

I hope this has been of some help!


8 - Views: list pages that are child menu items to the current node

I hate answering my own question here, but just to save the effort anyone might be going through, here is a module that worked for me:

Views Menu Node Children Filter

Using this module I was able to pass the node ID of the current node and filter the node's children in reference to the menu structure. Works perfectly on 8.4.


Update field data added in user form using a hook?

Hook implementation depends on when you want to manipulate the user account data.

Before creation of a new user account, hook_user_insert().
Before updating any user account, hook_user_update().

If you need to update existing users with new data you need your own custom function that makes user of user_load() (to load a user object) & user_save() (to save your manipulated user object with new data).


How to implement redirect to custom 404/403 pages?

This is build in to Drupal and the simple way to do this is to create separate pages for both error codes and add your own wording as necessary.

Then go to the error pages section of site settings at /admin/config/system/site-information and add the path of your custom error pages.


Validate all instances of a field programmatically

You could implement hook_field_validate and check if its the correct instance. Doesnt work if the field is not defined by the module.

One way to build that would use hook_form_alter and add element_validator if the field exists on the form.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if (isset($form['field_phone'])) {
      $form['field_phone']['#element_validate'][] = 'mymodule_somevalidator';
    }
 }

function mymodule_somevalidator($element, &$form_state) {
  if (!empty($element['#value']) && !is_numeric(parse_size($element['#value'])) {
    form_error($element, t('The "!name" must be x', array('!name' => t($element['title']))));
  }
}


Using Commerce, how do I create a filterable view of "Who Bought What"?

Use Views! I guess you saw that coming, right? If you're in need of great examples, check out the default Views shipped with the Commerce Reports module.

In your case, I'd create a View using Commerce Order as the base entity. I'd filter it by order state or status so you only show completed orders. I'd then add relationships to the user table and to the line item table. Through the line item table, I'd add a relationship to referenced products. This will get you all the data you need in your query, and you can then add display fields pertaining to the user / order / line item info and filter based on the SKU / title of the product. You'll probably need some sort of aggregation to group multiple purchases of the same product by the same user.

That is by no means a complete recipe, but it's basically the only way you're going to solve this short of coding a custom interface and doing it all through EntityFieldQuery.


Drupal, Displaying a Content list of a User from their Profile, accessible by anyone via Views

It seems like you were very close.  I would add on to the contextual filter.  You need to provide a default value for the filter.  Either of the following will work:

Using PHP Code.  Enter the following into the box "return arg(1);" without the quotes.
Raw value from URL.  Change Path component to 2.


How to set menu items on mobile as stacked full-width items?

I've only used Responsive menus on one project and it seemed to work fine, outputting the mobile menus when viewed by a device, and the normal menu when viewed by computer with some margin of error but in general it seemed to work well. You can see a demo here: http://drastikbydesign.com/demo/responsive-menus-demo-1-mean-menu and how it shows on a mobile and/or computer.


Use the theme 'item_list':

$content = [
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#title' => 'My List',
  '#items' => ['item 1', 'item 2'],
  '#attributes' => ['class' => 'mylist'],
  '#wrapper_attributes' => ['class' => 'container'],
];

The wrapper_attributes are not used in all themes. In core this is classy and bartik, which is based on classy.


Bind payments and auto return a certain amount of it with PayPal

this would get complicated with paypal .. as only a transaction is refundable .., and no 'payouts' are supported in commerce ..

why don't you convert payments to userpoints, and safe the paypal refund fee. and do the payout of the points on request manually or with massrefunds.com ?


Adding 'AddThis' sharing functionality to a Drupal Commerce Checkout page

As you discovered in your comment, the recommended approach would be to have the AddThis block show up on the checkout/* pages. The question is: what are you sharing, exactly?

If you're wanting to include the sharing process as part of checkout, a new, custom pane would be the best place for this.


Is it possible to replace the original RSS content?

When editing the Feed display of your view you have the Feed settings box with two settings there - Path and Attach to. If you set Path to 'rss.xml' or if you're using a view for your frontpage and you choose it in "Attach to", that should do the trick.


How do I link menu to certain section in one page theme?

You can do this by giving path of your menu to id of that block. BUT there is a problem, Default Menu path in Drupal will show you invalid entry as ID of the block are not real path so it is not allowed.

To solve this Void Menu module comes in picture,

Follow following steps:

Download and enable the Void menu module.
Get your block-id by inspecting the HTML.

Go to Modules/Void menu/Configuration, in the section of <void1> save the Id of that block e.g. I have a id="block-block-4", so I will paste #block-block-4 and save it.

Go to Structures/Menus/Your menu/About link, In the path just paste <void1>, save it.

Now, you are good to go, when you will click that about menu link it will scroll you down to that block on same page.

Note: In  Drupal-8, You do not have to do anything, just save the Id in path, and that's it. This feature is provided by default in  Drupal-8.

JQUERY Effect

Till above procedure it is just fine, you can go ahead with that. BUT if you want the Smooth JQUERY effect like whatever is provided in your example website.

Just download Scroll to destination anchors, enabled it, That's it. Now it will Scroll down with smooth Jquery Effect.


Form returned by drupal_get_form() won't submit

It's not working because the form builder function user_register_form() is expecting a couple of arguments, $form_id & $form_date, that you're not passing (see the drupal_build_form() docs to know more about what they're for).

If you want to provide a wrapper function around the user reg form, you can do something like this:

function my_module_customer_registration($form, &$form_state) {
  $form = user_register_form($form, $form_state);
  return $form;
}


Make sure you include the following:

use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;

I'm assuming your function mymodule_form_field_config_edit_form_builder() looks something like this:

/**
 * My module form builder to map values to third party settings.
 */
function mymodule_form_field_config_edit_form_builder($entity_type, FieldConfig $field, &$form, FormStateInterface $form_state) {
  $field->setThirdPartySetting('mymodule', 'help_page_id', $form_state->getValue('help_page_id'));
}

In your widget form alter you'd access the settings with with FieldConfig. This would add it to all field types, you can check $field_name if you want to filter it a bit.

function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_name = $context['items']->getName();
  $field = FieldConfig::loadByName('node', 'myentity', $field_name);
  $help_page_id = $field->getThirdPartySetting('mymodule', 'help_page_id');
}


url alias not working when logged in as admin

After dealing with this exact issue for a while in drupal 8, this thread made it click as to what the solution was.

For me, it was my choice of detection for the language that was causing the issue.

Go to /admin/config/regional/language/detection

And make sure that the only checked is the "selected language"

I had the User method checked "Follow the user's language preference." and that was what was causing the issue.

Now this might not work for a multi language site, but my site was originally in danish and I only wanted to have an english version.


One alternative could be adding a regular term reference field that has the particular taxonomy term you want referenced set as the default value. Then in a hook_form_FORM_ID_alter call the node edit form for the specific content type and set the #access value to FALSE for that field.


The new version of my module depends on more modules than the old version ... how to ensure module users install them?

You could use hook_requirements(), which should allow you to display an error when the module is installed/updated.

Alternatively, if that doesn't work you can implement hook_init() to run a check for the modules and react accordingly.

Update: I've just run into the same issue myself and here is the code that I have used:

/**
 * Implements hook_init().
 */
function MYMODULE_init() {
  if (!module_exists('ctools')) {
    module_enable(array('ctools'));
    if (!module_exists('ctools')) {
      drupal_set_message(t('MYMODULE has been disabled as the required !ctools module is not present.', array('!ctools' => l(t('Chaos tool suite'), 'http://drupal.org/project/ctools'))), 'error');
      module_disable(array('MYMODULE'));
    }
  }
}

This will try to enable the required module and if it is unable to do so it will display an error message to the user and disable the my module.


Someone very kindly posted an example https://www.drupal.org/node/2883734.
Module creator also suggested here https://www.drupal.org/node/2824714 that documentation is being updated.


How to get a section of the menu tree based on the current node?

Found a way to satisfy all the cases without having to create multiple blocks (visibility rules would be odd) or create different menus. I could not achieve this by assuming a content type like in the question, because you could have the same content type nested until multiple areas of the menu, and not really know if the current depth you were at for it qualified as the parent (where the menu block should "begin" - not necessarily the parent of the page).

I decided to cheat a bit and use the URL and the alias pattern. If the current path matched a pattern, and the URL consisted of a certain amount of segments, I could tell I was in a specific part of the menu where the behavior should be different than others. In this case, it should use the current page and its children, instead of the parent of the current page and its siblings:

class MenuBlockEnhanced extends MenuBlock {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');

    // If we are not on a node route, get out.
    if (!$node) {
      return parent::build();
    }

    // If the menu being rendered is not specifically the sub nav, get out.
    if ($this->configuration["suggestion"] != 'subnav') {
      return parent::build();
    }

    $current_path = \Drupal::request()->getRequestUri();
    $parts = explode('/', $current_path);
    $build = parent::build();

    /** @var \Drupal\Core\Menu\MenuLinkManager $menu_link_manager */
    $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    $route_params = array('node' => $node->id());
    $menu_links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', $route_params, 'main');
    $set_parent = TRUE;

    $params = new MenuTreeParameters();

    // I don't really know of another way to 'tell' we are on a project, since
    // a project can have projects under it. We can only rely on the path and
    // how many 'parts' are in the path - anything over 4 parts would be anything
    // nested in this section.
    if (preg_match('/programs-projects/i', $current_path) && count($parts) == 4) {
      $parent = reset($menu_links)->getPluginId();
      $set_parent = FALSE;
    } else {
      $parent = reset($menu_links)->getParent();
    }

    $uuid = str_replace('menu_link_content:', '', $parent);
    $parent_menu_content = current(\Drupal::entityTypeManager()
     ->getStorage('menu_link_content')
     ->loadByProperties(array('uuid' => $uuid)));

    $params->setRoot($parent);
    $params->setActiveTrail([$parent, reset($menu_links)->getPluginId()]);
    $tree = $this->menuTree->load($parent, $params);

    // Transform the tree using the manipulators you want.
    $manipulators = array(
      // Only show links that are accessible for the current user.
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      // Use the default sorting of menu links.
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $this->menuTree->transform($tree, $manipulators);

    $link = end($parent_menu_content->link->getValue())['uri'];

    $element = $this->menuTree->build($tree);
    $build['#items'] = $element['#items'][$parent]['below'];

    if ($link != 'route:<nolink>' && $set_parent) {
      $build['#top_parent'] = $element['#items'][$parent];
    }

    if (empty($build['#cache']['contexts'])) {
      $build['#cache']['contexts'] = ['user.permissions'];
      $build['#cache']['tags'] = ['config:system.menu.main'];
    }

    return $build;
  }

}

The caching strategy comes right from what would normally be there, frankly I probably do not even need to specify it since I am already calling parent::build() and just reduce that code.

In the template, I resolve the "do I print just siblings, or this page and its children?" by using the in_active_path check, and faking a control break in Twig macro (see: break = true):

{% import _self as menus %}

{{ menus.menu_links(items, attributes, 0, top_parent) }}

{% macro menu_links(items, attributes, menu_level, top_parent) %}
  {% import _self as menus %}

  {% if items %}
    {% if top_parent %}

        {%
          set parent_list_classes =
          [
            'secondary-nav__item',
            'secondary-nav__item--parent'
          ]
        %}

        {% set parent_link_classes =
          [
            'link',
            'link--left-arrow',
          ]
        %}

          {{ link(top_parent.title, top_parent.url, { 'class': parent_link_classes }) }}
          {{ menus.menu_child_links(items, attributes, 0) }}

    {% else %}
      {{ menus.menu_child_links(items, attributes, 0) }}
    {% endif %}
  {% endif %}
{% endmacro %}

{% macro menu_child_links(items, attributes, menu_level) %}
  {% import _self as menus %}

    {% set break = false %}
    {% for item in items if not break %}
      {%
        set list_classes =
        [
          'secondary-nav__item',
          item.in_active_trail ? 'is-active'
        ]
      %}

        {{ link(item.title, item.url) }}

        {% if item.below and item.in_active_trail %}
          {% set break = true %}
          {{ menus.menu_child_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

{% endmacro %}

The menu works exactly as asked for all cases, and will go all the way down to its maximum depth and back up the chain (with the parent blue link appearing up top).


Install using Composer doesn't create .htaccess file

Both drupal-composer/drupal-project and drupal/recommended-project create Drupal installations with a relocated DOCROOT, or web root.  So, the .htaccess folder isn't in the root of the installation.

You need to point Apache to the 'web' directory, which is where the .htaccess and index.php files are.  This is done at the Apache config level, not .htaccess level.

For example, on one of my servers, I have my git checkout in /var/www/prod.  The config looks like

DocumentRoot /var/www/prod/web
<Directory /var/www/prod/web>
  AllowOverride All
  Options -Indexes
  Options +FollowSymLinks
  Require all granted
</Directory>


Pop-Up E-mail subscription ( module) or appearing form?

You can try the Lightbox2 module

  The Lightbox2 module is a simple, unobtrusive script used to overlay images on the current page. It's a snap to setup and works on most modern browsers.

or the CTools Auto-modal module

  Provides automatic modal support for any hook_menu() paths that have 'modal' => TRUE defined. This makes it easy to add optional modal support in any contrib module and helps reduce the burden on module developers to support modals.


How can I Eliminate render-blocking JavaScript and CSS in above-the-fold content?

They are not render blocking. That is the main Drupal's js and css aggregated. Because they have most of the site's js and css in them, they end up quite large, and that makes most optimizers detect them as problematic.

There is a high probability that you don't want to do anything about this.


How to sort view by the weight of referenced nodes?

I found out that the :delta component of the field (e.g. field_authors:delta) can do this trick.

-- EDIT--

Some more explanation: Let's say field_authors contains the reference to connected authors. Among the sorting options there's a field_authors:delta which contains numbers for each referenced node (0, 1, 2...) and represnts their actual order.


Render arrays look like this:

$build = array(
  '#prefix' => '
',
  '#suffix' => '
',
  'select_floormap' => array(
    '#markup' => '
Markup for the first bit
',
  ),
  // drupal_get_form() returns a render array.
  'setup_cameras_form' => drupal_get_form('setup_cameras_form') + array(
    '#prefix' => '
',
    '#suffix' => '
',
  ),
  'expectation_form' => drupal_get_form('set_expectations_form') + array(
    '#prefix' => '
',
    '#suffix' => '
',
  ),
  'new_floormap' => array(
    '#markup' => '

',
  ),
);

See the render array docs and What are "#" properties? for a bit more explanation.


Unable to set file upload destination private when programmatically creating new content type with file field

If your issue is that the radio buttons are greyed out when trying to select the 'private' folder.

I needed SQL access for this one;  I emptied the SQL table that relates to the field that stores the images.  In my case deleting all items was not enough and I need to manually remove all rows from the table and then put them back after the next stages.   in my case table field_data_field_upload_private files .


User registration form validate and submit hooks not called

Add this in your hook_form_alter:

$form['#validate'][] = 'your_validation_function';

This way you can define an additional validation functions. Make sure you report all validation errors using the form_set_error() function.


How to "disable" certain paragraph types?

Sure this is. Per field. So let's say you have a "Paragraphs" field (field_paragraphs in the screenshot below) in the "Article" content type. Then you edit this field and there you have to select which paragraph types you want to include or exclude.


Is it possible autoload PHP classes in themes?

There's an interesting development going on regarding themes and OOP. Look at Allow themes to provide services.yml which finally got closed as Won't Fix. From Mark Carver's closing comment:

  I really don't think we should be opening up themes to services
  anymore.

  A lot has changed (for the better) in the 5 years I've been following
  this issue (closely).

  If this were to happen... there wouldn't be any real delineation
  between what a module is vs. what theme is, would there?

Instead as a result Allow themes to declare dependencies on modules is the route to go now. To move all the OOP stuff out of themes as the theme layer is for theming things, as JayPan said in the comments.

My answer to that problem is that I now always create a themename_companion module where I provide Drush 9 commands, helper functions, services etc. for my themes.


How to let users post questions and appear anonymous?

To my knowledge, the Answers module (you know the drill .. Disclosure: I'm a co-maintainer) does not have such setting that you were looking for. However, by using the Rules module (also), you should be able to get this to work, as further detailed below ...

Step 1: Create a (blocked) user 'Somebody'

Create an extra user with a user name that will be shown instead of the user name that you want to appear anonymous. I decided to name such user "Somebody", and it was created with uid=68. Moreover, I decided to make it a blocked user (not to be used for any other purpose).

Step 2: Add a dedicated field to relevant content types

For every content type for which you want this facility to be available (e.g for types Question and Answer), add an extra field that an editor (author) of a node can use to indicate if the node should  appear anonymous.

In my case I have a selection list field with machine name field_optionlist and which has 2 possible values, like so:

A (= Appear anonymous).
S (= Standard author display).

Step 3: Create a custom rule

Below is custom rule (in Rules export format) that will set the node author to "Somebody" (= the user name from Step 1) whenever value "A" is selected via the dedicated field from Step 2 (and whenever a node of type Question or Answer is saved):

{ "rules_optionally_hide_node_author" : {
    "LABEL" : "Optionally hide node author",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : {
              "answers_answer" : "answers_answer",
              "answers_question" : "answers_question"
            }
          }
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : "68" },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "data_set" : { "data" : [ "node:author" ], "value" : [ "user-fetched" ] } }
    ]
  }
}

Adapt the uid=68 value in the above rule to fit your dedicated user, and replace the machine name of field_optionlist to fit your case (prior to trying to import the above rule).

That's it ... at least to make it work in my setup.

Step 4: Extra refinements

For the sake of completeness, you should create a variation of this custom rule to set the node author to "current user" whenever the field value is different from "A".

Bonus feature ...

By using the above approach, and by using a user name like Wiki, you can implement logic that is pretty close to "wiki" questions / answers on SE-sites also. Because for those kinds of questions/answers the original author will not have any user points (like reputation) changes anymore for any upvotes or downvotes of such question or answer.


One of two field is required in drupal 7 view?

An approach could be adding a previous radio button field where the user must select which field is going to fill, and the show this field with conditional field. (Both fields should be required)


Tokens keep 'disappearing', drush rr fixes the website for a time, sometimes hours sometimes seconds

We've run into this problem as well on a shared hosting production environment, as well as our staging environment. The first on PHP 5.5.9 with Zend OPcache v7.0.3, the latter with PHP 7.0.22 with Zend OPcache v7.0.22. In both environments some site un-deterministically "forgets" tokens. I debugged this down to function_exists() in the implementation of the hook system of Drupal. It seemed PHP just forget that modules implement the hook_info() functions.

A restart of PHP (PHP-FPM in these cases) fixes the problems, so my best guess is that the Zend OPcache is responsible for this erratic behavior. Note that the fact that environments are shared will probably increase the odds of this bug to surface.


You can add new field to taxonomy terms. Go to vocabulary and than to Manage Fileds tabs and add new textfiled. After that you can edit you tems and add seecond values.


Which hook do I use to alter product entity data in a product display?

hook_entity_load may be the answer that some folks are looking for in situations that differ from mine.

For my specific need, I discovered that everything I needed to accomplish could be done with hook_form_alter.  The form_state holds the value of the currently selected SKU in $form_state['default_product']->sku.  Here is a hook_form_alter function I wrote to accomplish my goals:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if(strstr($form_id, 'commerce_cart_add_to_cart_form_')) {

        // Load the current product entity
        $prod = commerce_product_load_by_sku($form_state['default_product']->sku);

        // Check and see if the produt is customizeable or not, and then react
        $customizeable = $prod->field_prod_customizable['und'][0]['value'];
        if(isset($customizeable) && $customizeable == 1) {
            // Grab the custom label and instruction
            $customize_label = $prod->field_prod_customize_label['und'][0]['value'];
            $customize_instruction = $prod->field_prod_customize_instruction['und'][0]['value'];

            // Alter the field to display the custom label and instruction
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#title'] = $customize_label;
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#description'] = $customize_instruction;
        }
        else {
            // If not a customizeable product, then make the field hidden and not required
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#type'] = 'hidden';
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#required'] = 0;
        }
    }
}

Note that the textarea field I added to my Product line item type is called field_prod_comments.  The fields I added to my product entity are field_prod_customizable, field_prod_customize_label, and field_prod_customize_instruction.


When using the webform module, is it possible to get information on the submitter's device (Mac/Win/Android), browser version, etc.?

It appears webform allows a default value using %server variables, but only for authenticated users.

  In addition to %get and %post, the following super tokens may be used,
  though only with logged-in users: %server, %cookie, and %request. For
  example %server[HTTP_USER_AGENT] or %session[id].

For authenticated users, try adding a User Agent field with a default value of %server[HTTP_USER_AGENT]

If your form submissions come from anonymous users, you may need an alternative way to add the %server tokens.

Other $_SERVER variables documented here: http://php.net/manual/en/reserved.variables.server.php


Serving CSS, images and JavaScript in Drupal

Nope, it does not.
But if you have let's say in one of your stylesheet files a reference to a missing image, or your code is trying to load a missing js file then because of the Rewrite Rules in .htaccess this requests are redirected to index.php and that causes the bootstrapping of the whole system to render the 404 page.


Can Drupal Commerce and Ubercart be installed on the same site?

These two modules define the same menu entries - so you can use only one of them.


Note that the entity id is the gid in the current OG 2.x version(s) (there is some confusion around the change from earlier OG versions where GIDs were NOT entity ids)

From

  ... the group ID is the identifier of the entity. if i have a group which is a node the group ID will the be node ID. If i create a group which is a user the group ID will be the user ID and if i have a group which is a taxonomy term the group ID will the term ID.

Use og_is_group to determine if the node in question is acting as a group.


How do I pass contextual filters to a view via services

pass your filter as follows:
yourendpoint?args[0]=value&args[1]=value

Good luck


How to add a new user badge after earning a certain number of user points?

First of all, add the badge(s) you'd like to use at Configuration > People > Badges > Add new badge. Afterwards, create a rule for every badge, similar to the following one:

{ "rules_new_badge" : {
    "LABEL" : "Add new badge",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "user_badges", "userpoints_rules" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "IF" : [
      { "php_eval" : { "code" : "$current_points = userpoints_get_current_points($userpoints_transaction-\u003Euid, \u0027all\u0027);\r\nif ($current_points \u003E=7) {\r\n  return true;\r\n}" } }
    ],
    "DO" : [
      { "add_badge_by_name" : { "badge" : "1", "user" : [ "userpoints-transaction:user" ] } }
    ]
  }
}

Import it and modify it, according to your needs. To delete a badge, you can add another Rule with the action 'Remove badge by name'. Mind that I used a PHP Evaluation condition in order to use your PHP code in the Rule. I would, however, advise against this and use the Conditional Rules module instead.

Displaying the user badges next to the user names can be achieved by theming the comments in the comments.tpl.php file. This answer might help.


How do I bulk update the alt and title tags of images

Rewriting the D7 code of How to bulk update image alt and title?

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties(['type' => 'article']);

foreach ($nodes as $node) {
  $node->field_image->alt = $alt;
  $node->field_image->title = $title;

  $node->save();
}


The itok is defined in ImageStyle@getPathToken entity when building the URL (ImageStyle@buildUrl):

  /**
   * {@inheritdoc}
   */
  public function getPathToken($uri) {
    // Return the first 8 characters.
    return substr(Crypt::hmacBase64($this->id() . ':' . $this->addExtension($uri), $this->getPrivateKey() . $this->getHashSalt()), 0, 8);
  }


How can I get the group id of a node using tokens?

In Organic Groups 7.2 the Node idea and Group id are the same. So if you are using views you can do the following:

Add field "Content: Nid" and exclude if from display.
Any field arranged below the above can use [nid] as a rewrite giving you the Group ID.

Does this help?


In Drupal.org, for projects that are enabled, patches in the issue queues are passed to a test server, which executes the following steps:

It creates a Drupal site
It copies, and installs the module for which the patch has been written
It applies the patch being tested
It runs a set of SimpleTest tests, which has been written by the maintainer of the project wrote for his own module, to verify the patch doesn't introduce any problem

Once the tests are done, the test server reports to Drupal.org the result, which is then shown in the issue where the patch is attached.

This is what essentially happens. I didn't mention all the details, such as:

The Drupal site is created before to run every test
The test server executes also its own tests to verify the created Drupal site is running correctly
The test server periodically executes tests to verify it is running correctly
The Drupal version, and the version of the module that needs to be installed are taken from the issue itself; if the issue is for version 6.x-1.0 of a module, then the test server creates a Drupal 6 site, and installs the version 6.x-1.0 of the module, to which it applies the patch found in the issue report


Location module should lookup address before saving

This doesn't help you with the Location module, but OpenLayers will map the location before the node is saved.


You can use a destination parameter in URL to retain those values. There is a good read on drupal.org (https://www.drupal.org/docs/7/theming/overriding-themable-output/how-to-add-a-destinationurl-to-the-request-new-password)

Let me know if you need any help.


How to disallow some emails in Drupal 7?

Use the User Restrictions module. This module allows you to block both emails and usernames based on certain patterns.

For example, to block mails from spammers.com create a user restriction with:

Access type: Denied
Rule type: Email
Mask: %spammers.com


Content type - field type - Select list: Add options: Existing content on the website

Assuming you are using Drupal 7, I think you need the Entity Reference module.

This module provides a field that you can add to your content type peaches and provides the requested widget that allows you to select from all the bananas nodes your website has. When outputting the peaches node, the standard formatter (that the Entity Reference module offers) creates a link using the selected bananas node's title.


How to count the number of unique views of a node?

It depends how much traffic you site has and how big your server is. If you need to create a view count like this, it will require that you disable page cache making your site slower and demanding more resources from your server, or run expensive queries on every node view.

You could do this with Drupal, but there isn't a module that provides this functionality for you. The statistics module will count all views of the node. To implement this you would need to use either hook_node_view or hook_boot and write to a database the nid of the node being used and a token for the user. If you don't want to count anonymous users, you can use the uid, else you would have to use a combination of uid and session id to try not to count the same anonymous users twice.

A better way if you have a lot of traffic is to use an external tool like Google Analytics and then draw data from there.

Both solutions will require custom code though.


I found a solution. I compared the output from a dump of user_pass $form and contact_message_personal_form $form variable.
My problem was, that my $form['actions']['submit']['#submit'] array was empty. So I added the missing '::submitForm' parameter
and everything works.

function module_form_alter(&$form, $form_state, $form_id) {
  if($form['#form_id'] == 'user_pass') {
    $form['actions']['submit']['#submit'][] = '::submitForm';
    $form['actions']['submit']['#submit'][] = 'user_pass_redirect';
  }
}

function user_pass_redirect(&$form, $form_state) {
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', [
    'node' => '87',
  ]);
  $form_state->setRedirectUrl($url);
}

I have no idea why my variable was empty but this works for me.


We can easily change the From with hook_mail_alter using 'from'
key from $message.

function mymodule_mail_alter(&$message) {
  $message['from'] = 'Your Name ('. $message['from'] . ')';
}

Also, Please check hook_mail function https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_mail/7 which needs to be written for your module and then you need to call drupal_mail function.

hook_mail_alter is just for modifying the variables passed to drupal_mail.


There is something wrong in the error handling with recoverable fatal errors.

They're not displayed but the affect the page title. Have a look at the watchdog output, there you should see some PHP errors.

This is a bug, so not really a good question for here, but for the time being, might help others.

Opened https://drupal.org/node/2100123


$base_url variable in settings.php is not being read. How do i set this variable?

Use a virtual host in your webserver configuration with the DocumentRoot to your drupal installation:

<VirtualHost *:8888>
   DocumentRoot "/var/www/website"


Create hierarchical taxonomy url alias with token term:parents using a field other than term:name

Option 1

You could copy the token created by the taxonomy module for [term:parents:join:/] and recreate it in your own module, using your field as a substitute for title.

This would require some familiarity with the token system. There is also a module entitled 'Custom Token' that might be worth a look, though I have not used it.

Option 2

One divergent way I could suggest to get around this is to use drupal's title field to store your english language title, and another field to store the chinese title (*field_chinese_title*).

You could then preprocess the node title within your theme/module to replace $variables['title'] with *field_chinese_title*. You might also have to do this for menu entries and search results, and you would also have to remember to use *field_chinese_title* for views fields etc.

YOURTHEME/template.php:

<?php
function YOURTHEME_process_page(&$variables) {
  if (isset($variables['node']->field_chinese_title['und'][0]['value'])) {
    $variables['title'] = $variables['node']->field_chinese_title['und'][0]['value'];
  }
}

function YOURTHEME_preprocess_search_result(&$variables) {
  // use chinese version of title for search results
  if (isset($variables['result']['node']->field_chinese_title)) {
    $variables['title'] = $variables['result']['node']->field_chinese_title['und'][0]['value']);
  }
}

I admit I have little experience of multi language sites, and I do realise that this method might look a little crude, but I have used a variation (with autonodetitle) to differentiate the titles used by menu entries and nodes (so that menu entries can optionally be more concise) and it works beautifully. For my use case, I later found a module for that...


single exposed filter for two displays in same view

Under Advanced > Other You have to set the "Use AJAX:Yes" for both the views.
At the Quick tab setting page select the following radio button -
Yes: Load only the first tab on page view".


If you're looking for uniformity across the view, I'd go with a teaser view mode on the nodes.  It's under display settings.  In view mode, you can control the length of the text that is trimmed, the size of the image,or whether or not you want field labels, or taxonomy terms showing, etc. In fact you can show a completely different set of fields that weren't visible on the default view mode. The upshot of this is the content will display exactly the same across the entire site without having to re-theme it in a block, in a different view, & so on.


How to auto-assign a term based on a combination of terms from three other vocabularies?

These are some ideas to accomplish this through Drupal (rather than Excel).

You could do this with a combination of custom modules and Rules, or solely with Rules (which might be a bit more laborious). I'm focusing on the version only with Rules. I haven't tested this, so there may be some adjustments needed.

1. Create a "Catalog" content type that catalogs all combinations of codetypes

Create a content type that will act as a "catalog of codetypes", containing all possible combinations of codetypes and their unique keyword assigned to each combination. This would take an initial investment of time for someone to enter all combinations. Be sure to enter a special code (like the string "empty") when a codetype is not present in a specific combination.

2. Create a View of the "Catalog" content type with three Contextual Filters that filter for a specific combination of the 3 codetypes

(This step needs to be tested and possible tweaked quite a bit). You would need to define the path as /catalog/%/%/% to create placeholders for empty codetypes. There would be 3 Contextual Filters for each of the 3 codetype fields in the catalog. Be sure to provide the fixed default value "empty" in the configuration of When the filter value is not in the URL. The result of this View would be a single record that contains the specific combination of codetypes.

3. Install View Bulk Operations and add it to the View

After enabling it, add a VBO field to the View created in step 2. There is no need to select a specific operation. This field will be used to load the single catalog record into Rules later on.

4. Create a Rule that reacts to new (imported) Product nodes being saved

This Rule will react to the Products being created through the use of Feeds. Basically it needs to load a list of entity objects from the VBO you created above. Pass the three codetypes as arguments the the View.

5. Use the Rule to Set data value of the Keyword field in each of the imported Products.

This step may require some tweaking. You will need to bring into scope the Keyword field of the Catalog record provided by the View. That may involve creating a separate Component that has a condition that brings it to scope, or installing Conditional Rules to create an if statement that brings it to scope. Once the Keyword field of the Catalog node is brought into scope, you use its value to assign it to the Keyword field of the imported Product

So, that's it in a nutshell. You could replace several of the steps with code in a custom module, and avoid using VBO and Rules altogether - you would use EntityFieldQuery to load the Catalog node with the three codetypes, and hook_node_insert() to react to the Product node being imported/created. There may be alternative hooks in the Feeds API that may make this possible too.

I hope this helps... Let me know if you have questions.


Customizing and Overriding User Login page, Register, and Password Reset in Drupal 6 and 7

Customizing the user login, register, and password reset pages is fairly simple, and uses the following concepts:

preprocessing to set variables
registration of functions in the theme registry
creation of one or more theme templates.

Step 1.
In the site theme directory, create or edit your template.php file.

Step 2.
The first step is to implement hook_theme for your theme. In the template.php file for your theme, look for a function named yourtheme_theme() and modify it to add these return values. If the function doesn't exist, add the following:

For D6:

<?php
/**
 * Registers overrides for various functions.
 *
 * In this case, overrides three user functions
 */
function yourtheme_theme() {
  return array(
    'user_login' => array(
      'template' => 'user-login',
      'arguments' => array('form' => NULL),
    ),
    'user_register' => array(
      'template' => 'user-register',
      'arguments' => array('form' => NULL),
    ),
    'user_pass' => array(
      'template' => 'user-pass',
      'arguments' => array('form' => NULL),
    ),
  );
}
?>

Notes about that code:

Change the function name by replacing "yourtheme" with the name of your theme
The template can be the same for all three. The example above uses a different template for each case: user-login, user-register, and user-pass
The template names must use a dash, not an underscore
Note: It's user_pass not user_password

For D7:

<?php
function yourtheme_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'yourtheme_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_pass'
    ),
  );
  return $items;
}
?>

Notes about the D7 version:

The 'path' lines tell Drupal where to find the .tpl.php files. This is optional, and in the code above, 'path' tells Drupal to find the files in the templates subdirectory of the theme's base directory.
Note the "_form" added to the user_register element.
Note: As it is the case for D6, it's user_pass not user_password

Step 3.
Now you implement three preprocess functions. There may be more concise ways to code this, but this works very well and is easy to read, so here we go!

For D6:

Notes about that code:

Change the function name by replacing "yourtheme" with the name of your theme
The line $variables['intro_text'] adds the text that follows to the $variables array, which gets passed to the template as $intro_text
The second line renders the form and adds that code to the $variables array, which gets passed to the template as $rendered

For D7:
The code is even simpler for D7 because we don't need to pass a variable containing the form content we want rendered. The variable exists already in the $vars array and can be rendered in the .tpl.php file.

The above preprocess functions simply add a variable into the $vars array that is then displayed in the .tpl.php file. Much more complex manipulation of the content of the render array is possible.

Please note, that the preprocess functions should go into the template.php file.

Step 4.
Create template files to match the 'template' values defined above.

For D6
We need the following template files (make sure to use a dash, not an underscore) :

user-login.tpl.php
user-register.tpl.php
user-pass.tpl.php

For D7
Same as D6, except using user-register-form.tpl.php instead of user-register.tpl.phpfor the register form.

Step 5.
Paste the following into user-login.tpl.php. Modify as necessary for user-register.tpl.php (D6) and user-register-form.tpl.php (D7):

For D6:

For D7:

Note the change to the syntax for causing Drupal to render the form. Also, the D7 sample uses a different class for the div, but that's just a matter of preference.

Step 6.
Save your template.php file to the theme's main directory. Save your .tpl.php files in the same place for the D6 examples, or, in the case of the D7 examples, to the directory you specify in the 'path' element of the $items array.

Step 7.
Rebuild the cache. Go to Administration > Performance and click on "Rebuild Cache" on the bottom of the page.

Now, the user login page will contain the new text from the preprocess function, and the tpl.php file(s) can be modified to suit the site's needs.

reference : Customizing and Overriding User Login page, Register, and Password Reset in Drupal 6 and 7


How can I translate the  option for a grouped exposed filter in Views?

It turns out that there is a bug in Views at the moment, so I wrote a patch.

Once you apply the patch (or once the patch is committed to Views), you can translate  as part of the built-in interface through the Translate Interface screen.


How to get the translated term name by tid?

I managed to make it work! This is my code

$tree = taxonomy_get_tree(9); // Your taxonomy id

foreach ($tree as $term) {
  if (module_exists('i18n_taxonomy')) { //To not break your site if module is not installed
    $term = i18n_taxonomy_localize_terms($term); // The important part!
  }
  print l($term->name, 'taxonomy/term/' . $term->tid); //print the terms
}

That sould do it! Diadeuf!


This is a bit tricky, since the order total is calculated from the line items. Either you would need to add/remove a line item that has the fee, or you would need to add the price to the order after it has been loaded, using hook_commerce_order_load.

I would prefer the line item solution, as it is more robust, but it also requires more work, as you will need to define the line item and either create custom code for adding/removing it.


"Drupal\Component\Plugin\Exception\PluginNotFoundException: The 'integer' plugin does not exist."

As an option just try to add this code in the enabled custom module in your project.

/**
 * Implements hook_entity_base_field_info_alter().
 */
function custom_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
  if ($entity_type->id() === 'menu_link_content' && isset($fields['weight'])) {
    $options = $fields["weight"]->getDisplayOptions('view');
    // Lets check if field definition is buggy.
    if ($options['type'] === 'integer') {
      $options['type'] = 'number_integer';
      // @TODO: This should be fixed in the menu_link_content core module.
      // @see https://www.drupal.org/node/2903161
      $fields['weight']->setDisplayOptions('view', $options);
    }
  }
}

Or try to use this patch from this issue


Custom grouping by taxonomy term in view

Groping things in view not that easy, and what i suggest you here to save your time to use views_field_view which allowed you to insert view inside view.

So simply make 3 displays each one for level and pass the argument between them, that should not take more than 5 min


How to render HTML into a variable programmatically

To render a plain node view, for example for emails, use this code:

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$build = $view_builder->view($node, $view_mode, $langcode);
$html = \Drupal::service('renderer')->renderPlain($build);

If you want to customize the output, use a special view mode and a template node--[view-mode].html.twig.

Edit: Full page

You can build more complex render arrays:

  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $content = $view_builder->view($node, $view_mode, $langcode);
  $build = [
    '#type' => 'html',
    'page' => [
      '#type' => 'page',
      '#theme' => 'page',
      '#title' => 'Title',
      'content' => $content,
    ],
  ];

  $html = \Drupal::service('renderer')->renderPlain($build);

This is only a basic version of a page, if you want the full version with all features like attachments and libraries you need a request on Drupal.


Add a variable amount of time to a date field via rules

The interval module provides an action "Apply an interval to a date" (you find it in the "data"-section of the action list). The module supplies a "interval field", but surprisingly, instead of providing integration between rules and that field, it provides that action, which provides integration between rules and an integer field. The action allows you to specify a data value and specify which interval that number is to be interpreted as (days, months, ...)


Tpl for page having url like product/checkout/%/%

In your page callback, you would have to set '#theme' on a renderable array.

You can use an existing theme function, or create your own using hook_theme.

If creating your own and you prefer to use a tpl, you can set the template option in hook_theme and bypass having to create a theme callback function.


Theme setting to change block position (region)

First of all you should change each desired block region for your theme manually at Administration>Structure>Block layout Tab and then go to the config export function at:  Administration>Configuration>Development>Configuration synchronization>Export Tab>Full archive to export all the block settings for your theme.
Then you should take a look at to the generated YAML files and placed them in a new folder within your theme at /config/install. you then uninstalled the theme and then reinstalled it as the default.


How to disable and grey out a form button if the textfield is empty?

Obviously you will want to do this with some jQuery...And of course there is more than one way to do this, but:

$(function(){
      //Set button disabled
      $("input[type='submit']").attr("disabled", "disabled");

      //Append a change event listener to your input
      $("input[name='nickname']").change(function(){

            if($(this).val().length > 0) {
              $("input[type='submit']").removeAttr("disabled");
            }
      });

      // You could then trigger the a change event on load just to check
      $("input[name='nickname'").trigger('change');
});

That should be the gist of it.  Of course you would want to change your "name" value to whatever your input name is.


Allowed HTML tags in "Allowed value list" are not working

According to your question comments, you are trying to create a form with an options list element using the core select element widget.

This widget is intended for creating select lists. Markup within select list options is considered invalid HTML. That's why the select options widget has a sanitizing function for its option labels, namely OptionsSelectWidget::sanitizeLabel(). This sanitizer is used on each widget settings form submit and cleans your labels from any HTML.

If you really require an options element with HTML in the option labels, you have three choices:

(1) Choose another widget type for the list field that supports HTML markup natively. Obviously you choose the select widget. Choosing checkboxes or radios as widget type in the "manage form view" tab will use the less restrictive satitizing function of the the abstract OptionsWidgetBase class.

(2) If you need an entirely unfiltered list, create a custom field widget for your list field. Make sure to also implement a form element different from select that supports HTML in its labels.

(3) Leave the sanitized labels in the Core widget configuration as is and use hook_field_widget_form_alter() to add your markup to the labels of the element you intend to replace the Core elements with.


How can I use the Mail System module to send one e-mail differently than others?

These are the keys uses by the core user module:

'register_admin_created': Welcome message for user created by the admin.
'register_no_approval_required': Welcome message when user self-registers.
'register_pending_approval': Welcome message, user pending admin
approval.
'password_reset': Password recovery request.
'status_activated': Account activated. 'status_blocked': Account blocked.
'cancel_confirm': Account cancellation request.
'status_canceled': Account canceled.


How to add exist taxonomy term field to custom form

Not exactly i think, but you can implement next:

$form['node_taxonomy_term'] = array(
  '#type' => 'textfield',
  '#autocomplete_path' => 'ntt/autocomplete',
);

add menu callback for autocomplete path

function HOOK_menu() {
  $items = array();

  $items['ntt/autocomplete'] = array(
    'page callback' => 'node_taxonomy_term_autocomplete',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

and add callback function

function node_taxonomy_term_autocomplete($str = 0) {
  $matches = array();
  //vocabulary id
  $vid = 2;

  $result = db_select('taxonomy_term_data', 't')
    -> fields('t', array('tid', 'name'))
    -> condition('vid', $vid, '=')
    -> condition('name', $str.'%%', 'LIKE')
    -> range(0, 10)
    -> execute();

  foreach ($result as $term) {
    $matches[$term -> tid] = check_plain($term -> name);
  }

  drupal_json_output($matches);
}

enjoy


How do I count the number of items of same product class in cart?

Your code is wrong because, instead of comparing the value of $item->qty, you are setting them in each control statement. Replace = with ==.

if ($item->qty == 1) {
  $item->price = $firstPrice;
}
elseif($item->qty == 2) {
  $item->price = $secondPrice;
}
elseif ($item->qty == 3) {
  $item->price = $thirdPrice;
}

The code you wrote works because an assignment statement is also an expression that have the assigned value as its value.

Instead of writing an IF-statement, you could used a SWITCH-statement.

switch ($item->qty) {
  case 1:
    $item->price = $firstPrice;
    break;

  case 2:
    $item->price = $secondPrice;
    break;

  case 3:
    $item->price = $thirdPrice;
    break;
}


how to compare two content type fields and filter the output by drupal views?

Seems to me that you're going to need this:

views_embed_view()  inside of the user_profile.tpl.php

more specifically:

First set up a view to return content type 1 nodes, that takes an argument of taxonomy term id.

Then, assuming you can get the content type 2 node into user_profile.tpl.php, grab the select list value like so:

<?php
    $selected_value = $content_type2_node->field_selectlistname[0]['value'];
    $term_id = taxonomy_get_term_by_name($selected_value);

?>

note use of taxonomy_get_term_by_name()

and use of a cck select list field named is field_selectlistname, update that to your field name.

then you can use this:

<?php
   print views_embed_view("view_name","block_1",$term_id);
?>

to print out your view.

Note that the first two arguments are the view name of your view, and the display id, which is going to be something like 'block_1', 'default' or 'page_1'

I'm assuming here you know how to set up the view, and know how to get that user_profile.tpl.php to work for your role.. (if isset($account->roles[ role id ])... )

good luck!


Request::create is not working in EventSubscriber service class

You forgot to assign the value returned from Request::create() to a variable, and the rest of the code. The code shown in that documentation page, merged with the code shown in one of its comments is the following.
$request = \Drupal::service('request_stack');
$current_request = $request->getCurrentRequest();
$sub_request = Request::create('/my-url', 'GET', $current_request->query->all(), $current_request->cookies->all(), array(), $current_request->server->all());
return Drupal::service('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);

Since you want to write code to redirect users to a different page, the equivalent of what you would write in Drupal 7 hook_init(), check also hook_init() removed; it contains example code for that case.
namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {
  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }
}

See also the LocalRedirectResponse class.
The event subscriber for the example is described with the following, in mymodule.services.yaml.
services:
  mymodule_event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}


After creation template you need only implements form_alter and set this custom theme for whole form - $form['#theme'] = 'user_profile_form' and then you will be able to build form structure inside your template.

You can check diff module ( 'diff_node_revisions' theme ) as an example.


You can use themename_form_element() to remove asterik as given in the link.

function YOURTHEMENAME_form_element($element, $value) {
  $output  = '
\n";

  //REPLACE THIS
  //$required = !empty($element['#required']) ? '*' : '';
//WITH THIS

  if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= ' ' . t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "\n";
    }
    else {
      $output .= ' ' . t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "\n";
    }
  }

  $output .= " $value\n";

  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . "
\n";
  }

  $output .= "
\n";

  return $output;
}


How to get author_picture URL from a template?

URL FORMATTER module

This module add a url formatter for image field. Then you can output image url directly.

Once enabled, go to your user manage fields, and change the picture field formatter to url.
{{ author_picture }}  // will display url instead of picture

If you are using views, views will give you an option to change the format to url.


Go to your content type and click edit on your file field in question.

Click on File Sources.
☑ Remote File.


Ubercart - Manual Credit Card Processing

I believe this is more of a workflow question than, a lack of module(s) question.    You can setup Ubercart so that you accept an order without accepting a payment.   You can set the status of the order as non-processed.   You then process their payment manually (via phone, online, inperson, etc), then, manually, change the status of their order to process.


Patching docroot htaccess: file not found

Look your patch already has the path to web/ in it:
--- a/web/.htaccess
+++ b/web/.htaccess

Just remove the cd web &&  and adjust the path to the patch accordingly.
"post-drupal-scaffold-cmd": [
     "patch -p1 < patches/htaccess.patch"
]


How can I make my main menu link text dynamic?

Drupal menu's are cached and this makes it hard to change then on the fly when the page is rendered. It is possible though using the functions aimed at translating menu items: see hook_translated_menu_link_alter.

This hook is called before every menu item is rendered IF it has the property ['options']['alter'] = TRUE.

You can set this property to menu items using hook_menu_link_alter.

Example code would be:

function MY_MODULE_menu_link_alter(&$item) {
    // add in an if statement here to just target the links you want to change on the fly
    $item['options']['alter'] = TRUE;
}

function MY_MODULE_translated_menu_link_alter(&$item, $map) {
    if($item['mlid']==89) {
        // this line is actually to change the link however if you inspect the $item
        // variable then you will be able to see the other property that you can change.
        $item['link_path'] .= 'my-new-path';
    }
}


How can I change a file field description?

I have accomplished similar by using a hook_form_alter() in a custom module and altering the field's #description property.


How to remove nodes with the same title from views listing?

You can achieve this goal via using Views Distinct Module.

For more information go through the project documentation.


Set the value of a hidden form component

You should use the presave hook provided by webform instead of adding additional submit handlers to the form.

/**
 * Modify a Webform submission, prior to saving it in the database.
 *
 * @param $node
 *   The Webform node on which this submission was made.
 * @param $submission
 *   The Webform submission that is about to be saved to the database.
 */
function hook_webform_submission_presave($node, &$submission) {
  // Update some component's value before it is saved.
  $component_id = 4;
  $submission->data[$component_id][0] = 'foo';
}

This is a lot cleaner than adding custom submit handlers to the form (your custom handler is called after the webform submission handler, which can be a big part of the problem).

You have access to the node object in the presave hook so additional checks can be added beforre altering the component.


Adding group manager email to "membership pending" text


It is a known issue you can try this patch  and Suppose if that patch not workout for you check the other patches here  https://drupal.org/node/920840  and if any of that patches not solved your issue then the best option is you have to submit a bug report.


How to trim content from a heavy database

For content, I know two options, both based on Views:

Create a view of old content only, and use Views Bulk Operations to purge it from your site. This is literally what you asked for, but also something I would discourage.
Create a view of new content only, and use Views data export to only export nodes recent enough to matter. That way you will still have old content on site, and only lose it if site crashes and you need to restore from incomplete backup.

Also, I suggest you to evaluate Universally Unique IDentifier, it helps with consistency if you are exporting data individually, not as a complete snapshot of entire site.


Is there an issue reporting module with these features?

The Webform module might do what you want. It lets you create forms using the user interface. You can configure which actions happen when a user submits a form, such as email one or more users and store it in a table.

Update about your comment, which looks like so:

  Webform seems good but i drop it by one important reason. that is it doesn't give a privilege form submission only the authenticated user!

Forms created with Webform are just a type of node. If you want to restrict access to the forms you create, you can either not allow anonymous to access any node or you can use more fine grain permissions with another module like Nodeaccess. If this is for an intranet site, the first option might be the best


Can drupal_http_request be secure (https)?

Yes, it can.

case 'https':
  // ***************
  // Note: Only works when PHP is compiled with OpenSSL support.
  // ***************
  $port = isset($uri['port']) ? $uri['port'] : 443;
  $socket = 'ssl://' . $uri['host'] . ':' . $port;
  $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
  break;


Is there an example OAuth2 client module anywhere?

A year later, there is OAuth2 Server which provides the server part only, but has tests which are a good demonstration of client code in Drupal (using drupal_http_request()), so that code can at least be used as an example.
The module documentation also tries to explain basic OAuth2 concepts and potential pitfalls.


Drush on production server without Composer

If you don't want composer in production on your server, you can run the composer commands locally to install Drush, then make sure to push the vendordirectory to the server. Make sure to also commit the composer.json and composer.lock files, so that anyone else working with the codebase can handle composer on their own local machines as well.

In this way you never need composer on the remote production server, but can get drush.


Remove items from a menu based on node type efficiently

Gathering node paths for the book_section nodes in a function cached with drupal_static and using removing items from the menu based on that, rather than loading node objects for each menu item removed thousands or surplus DB queries.

Refactored code

function amoss_menu_link(&$variables) {

  // Hide book sections from the menu;.
  if (isset($variables['element']['#original_link']['link_path'])) {
    if ($variables['element']['#original_link']['menu_name'] == 'book-toc-1') {
        $book_sections = book_modifications_get_book_section_paths();

      if ( in_array( $variables['element']['#original_link']['link_path'], $book_sections ) ) {
        return '';
      }
    }
  }

  // Output a menu link.
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

function book_modifications_get_book_section_paths() {
    $book_section_paths = &drupal_static(__FUNCTION__);

    if (!isset($book_section_paths)) {
        $book_section_paths = array();
        $nids = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('type', 'book_section', '=')
        ->execute()
        ->fetchCol();

        foreach ( $nids as $id ) {
            $book_section_paths[] = 'node/'.$id;
        }

    }

    return $book_section_paths;
}


How to redirect particular page after login via social networking site?

You can use user_login_destination() for your requirement which third-party authentication modules may use to determine the proper destination after a user has been properly logged in.

function user_login_destination() {
  $destination = drupal_get_destination();
  if ($destination['destination'] == 'user/login') {
    $destination['destination'] = 'user';
  }
  return $destination;
}

You just need to change line 4 to:

$destination['destination'] = '<path you want to go to after login>';


How to get user id of order from order entity metadata wrapper

It's the same as any property on a metadata wrapper:

$uid = $order_wrapper->uid->value();

  Or should I think of loading order object?

You can't have an entity metadata wrapper without an underlying entity, so the object you're referring to is already 'loaded'. You can get it with

$order = $order_wrapper->value();


How to pass metatags from a node into a view?

There is a sandbox project call Metatag Views Field, which provide metatags as a field into Views.


Automatic Node Expire / Unpublish with Renew Option

I would have opted for a custom code solution with the above work-flow.As an alternate contrib module option classified Ads module can be potential option.

Module Features:

  Renewable expired ads during the 'grace period' Simple taxonomy-based
  browsing Ad expiration depending on category selection Per-user
  classified ads lists – custom lists totally sortable Length-limited
  body text with live counter of characters Advanced Help, CCK, Context,
  Panels, Token and Views support


On hook_entity_presave how do I now if it is a new node?

Use the Entity::isNew() method:

if ($entity->isNew()) {
  // ...
}


If you want to remove product programatically, and still allow other modules to interact with this event, you should invoke hooks explicitly just after deletion using module_invoke_all:

module_invoke_all('commerce_cart_product_remove', $order, $product, $quantity, $line_item);

That way you have a choice - you can call it and emulate regular deletion, or you can omit it, and prevent any marketing interactions etc that your user did not trigger.

Alternatively, because line items are entities, you should be able to hook into their deletion with generic hook_entity_delete, without any modifications to the way you invoke deletion.


Replace the date of a filtering criterion with "Views PHP"?

Don't.

Views PHP or any other method of stored PHP is a bad idea (What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?). It's also extremely slow, because it usually involves loading all data and then doing all the processing in PHP.

Instead, build a module and define a views filter plugin there, then you can build the query there how you like it. How exactly to do that is IMHO too complex to answer in a single question, you should find plenty of examples and tutorials on how how to create views filter plugins (there are dozens of plugins in core alone), look for something similar to your use case and start from there.


Getting error 'Redirects to external URLs are not allowed by default'

If you still haven't figured this out, check this comment on d.o: https://www.drupal.org/project/drupal/issues/2612160#comment-11767977

It suggests a workaround by removing the subdir from the script name, adding to settings.php the following:

if (isset($GLOBALS['request']) and
'/subdirectory/index.php' === $GLOBALS['request']->server->get('SCRIPT_NAME')) {
$GLOBALS['request']->server->set('SCRIPT_NAME', '/index.php');
}


Webform submission token for multivalue download field

One approach to this issue is to interpret tokens on your own via hook_tokens().
hook_tokens() is called every time a token is interpreted and gives you an opportunity to determine how that token is interpreted. Even though the token [webform_submission:node:field_gated_download:entity:field_media_file:entity:url] is already defined, it may be necessary to also implement hook_token_info() or hook_token_info_alter() in order to define additional modifiers to the token.
It's possible that you might discover the exact token syntax that you need by inspecting the arguments passed into hook_token_info_alter().
Here are two tutorials that cover using both hook_token_info() and hook_tokens() in order to perform custom token processing.

https://www.cloudways.com/blog/create-custom-drupal-token-modules/
https://medium.com/thefirstcode/tokens-replacement-patterns-in-drupal-8-d309132ba13d


Create a content type, e.g "Website"

Add fields:

URL ( link field )
Banner ( image field )
Category ( term reference field, create taxonomy vocab 'Category' first )

Name and Description will be the default node title and body fields

After that, you can create / manage your content.

Use Views and/or Panels to control the output on your site.


How to call a function of one module in another module

To call the function of one module in another module:

If the function is not in the .module file, call module_load_include()

//Load node.admin.inc from the node module
module_load_include('inc', 'node', 'node.admin');

Call the function from the other module

function_you_want_to_call();


user login screen is gone after using panels

Used drush to disable panels ( drush dis panels).

Thanks to 4life for the suggestion.  (i don't know why it won't let me credit him with the answer on here)


How to show only content created by the user in the find content (administrative) page

I've found that it's better to leave the admin areas to the admin user alone, and to build custom Views for "manager/editor" users.  This gives you more control over the presentation and lets you easily add in additional information and links that aren't normally available in the admin screens.  Not only that, you get easy access control to the listings.

If you really must do it the way you're talking about, there's an article on the drupal.org site discussing the theme hook for that screen, which I believe you could override and then filter based on ownership of the nodes in the node listing:

http://drupal.org/node/108986


Here is what I would suggest.

Clone the built in View
In the Entityform Type edit form select your new View under Submission Views -> View for submissions reports
In your new View add relationship to Profile2 entity via the Entity Reference field on the Entityform
Now you can add any field from the Profile2 to the View.


Displaying node reference select list as ordered menu list

You can use view to display all node you want and use expose filter to search for a specific node
or to display as tree
I guess there is a module to display taxonomy as a tree reference to make it like parent and child
so you can convert your node to be taxonomy to easy make it as a tree or change the module structure to display nodes


How can I allow users to duplicate a select field while creating a page from a custom content type?

If you use CCk, you can just edit your field setting in it's global settings and select illimited value number :

And you get a button "Add another" :

here I just used a text field for the example but it can be a select or anything else


Add custom validation on views exposed filter block form

There are many issues reported for this behavior on Drupal.org and Drupal Answers.

As a work around, you can try HTML5 pattern attribute to add minimum length validation, check example here.

Or add a small JS snippet to validate input field on blur event.


Looking for a special views exposed filter with pager and select list

I've updated Ctools, Views and date to the latest version as well.
Here the view i recreated from scratch after having updated the modules:

$view = new view;
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test';
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_label'] = 'Éléments par page';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['pager']['options']['expose']['offset_label'] = 'Décalage';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Champ: Contenu : Titre */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Critère de tri: Contenu : Date de publication */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Contenu : Publié */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Contenu : Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'publi' => 'publi',
);
/* Filter criterion: Recherche : Termes de recherche */
$handler->display->display_options['filters']['keys']['id'] = 'keys';
$handler->display->display_options['filters']['keys']['table'] = 'search_index';
$handler->display->display_options['filters']['keys']['field'] = 'keys';
$handler->display->display_options['filters']['keys']['exposed'] = TRUE;
$handler->display->display_options['filters']['keys']['expose']['operator_id'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['label'] = 'Termes de recherche';
$handler->display->display_options['filters']['keys']['expose']['operator'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['keys']['expose']['multiple'] = FALSE;
/* Filter criterion: Date : Date (node) */
$handler->display->display_options['filters']['date_filter']['id'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['table'] = 'node';
$handler->display->display_options['filters']['date_filter']['field'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['operator'] = '<=';
$handler->display->display_options['filters']['date_filter']['exposed'] = TRUE;
$handler->display->display_options['filters']['date_filter']['expose']['operator_id'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['label'] = 'Par date :';
$handler->display->display_options['filters']['date_filter']['expose']['operator'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['identifier'] = 'datepicker';
$handler->display->display_options['filters']['date_filter']['expose']['multiple'] = FALSE;
$handler->display->display_options['filters']['date_filter']['form_type'] = 'date_text';
$handler->display->display_options['filters']['date_filter']['date_fields'] = array(
  'node.created' => 'node.created',
);
$handler->display->display_options['filters']['date_filter']['date_method'] = 'AND';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test';
$translatables['test'] = array(
  t('Master'),
  t('test'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('Éléments par page'),
  t('- All -'),
  t('Décalage'),
  t('Termes de recherche'),
  t('Par date :'),
  t('Page'),
);


not show any picture in full html ,filtered html mode

Based on the comments - try a module that inserts images into the body of a content type.


I applied a Drupal 8 core patch from this page. It seems to work fine. It adds a new option to /admin/config/media/file-system:

This option enables transliteration for all future uploads to all file fields. It also works for inline images when Enable image uploads is enabled (for the text-format). I don't know if the patch affects IMCE, since IMCE was not installed on my test installation.


How do I create a view with mixed languages, showing the node's original language by default?

To show only the "original" nodes in any language don't include any language filters so all languages are shown. This will show all your content, translated or not in both languages.
It's not clear from your question what you mean by "that shows all of this content".
If you want to show only the nodes that were originals, and not a translation of another, add the Source translation Filter from the Content translation Category. Set it to Include untranslated content: Yes if you want only the nodes that haven't been translated yet.
Set it to No if you only want to show nodes that already have a translation node.
I'm guessing you'll want the No selected, or you won't need the Content translation Filter filter at all.
Then add the Content: Language Filter and Expose it to allow visitors to filter the language. Select only the two specific language options and the Limit list to selected items if you only want those to be the options your visitors see and are able to choose (so they don't see options like "Site default", "Current", etc).


Can't sync site config from git, entities exist of type x

Two things are happening:

In your active configuration in the database, some module(s) is/are installed, that isn't/aren't installed in the configuration you are trying to import. The problem is that you have content for the thing(s) being uninstalled, so if you were to import the configuration, you'd have ghosts in your database. These ghosts are listed in the errors that begin with 'Entities exist of of type X'.

To resolve this you'll need to either enable the missing item(s) in the configuration you're trying to import, or you'll need to delete the items from the database before you import your configuration.
The configuration you are trying to import has enabled modules, but the codebase for those modules does not exist in the Drupal installation you are trying to import the configuration into. These modules are listed at the end of the errors that begin with 'Unable to install the X module' (ex - you are missing the Path Alias code base).

To resolve this, you'll either need to add the code for the required modules to your codebase.


How to get update to check Feature Server

You're looking for project status url, which is a property that can be used in your module's .info file:

  Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.


How to have a view field that searches node title, body and everything about node

You could try using Apache Solr backend. You can use the following modules:

http://drupal.org/project/search_api
http://drupal.org/project/apachesolr

Another solution is to use a module like "views_or" or "views_filters_populate".

Otherwise you could give a try to "search_autocomplete".

Good work!


Viewing an image file breaks if view mode has responsive image style

This is not a proper answer, but a workaround in case someone else has this issue: detect if a responsive style is used, load it, and apply via theme layer (the style name is hard-coded to be "embed"):

if ($file) {
  $view_mode = \Drupal::entityTypeManager()
     ->getStorage('entity_view_display')
     ->load('file.' . $file->bundle() . '.embed');
  $content = $view_mode->get('content');

  // Responsive.
  if (!empty($content['uri']['settings']['responsive_image_style'])) {
    $build = [
      '#theme' => 'responsive_image',
      '#responsive_image_style_id' => $content['uri']['settings']['responsive_image_style'],
      '#uri' => $file->getFileUri(),
    ];
  }

  // Non responsive.
  else {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($file->getEntityTypeId());
    $build = $view_builder->view($file, 'embed');
  }
}


You could use the tel: or callto: href identifiers depending on the method of your phone call (Skype uses callto:, mobiles that support this feature will use tel:.

For example, if the number is 123-456-789, your link would look like one of the following:

Call this user

or

Call this user

Check this (old) blog post for some examples/ideas on implementation.


It looks like you have researched a few ideas and mixed them all.  The page--foo.tpl is a theme template file, and the names there are often used with theme suggestions so you can change the regions and wrapping html for different pages in different ways.  This is theme layer, and should be used for changing the appearance but not the processing.

The Hook_form_id_alter() is used to alter that specified form before it is passed to the theme layer, so that function will run before the print $foo; in the template.

So with what is in your question, the process would go like this:

  Check value of yet-to-be-set global $foo If foo is a specific page,
  remove field from form send form to theming get current page save
  current page to local $foo and ignore the global $foo that has already
  been checked. print out the value of local $foo into the html of the
  page

Also, I do not see roles touched anywhere in your question.  If I have read it right, you dont need the tpl at all and you can do this all in the form_alter.

function MYMODULE_form_user_register_form_alter(&$form, &$form_state) {
  global $user;
  if( current_path() == 'user/register/foo' ){
    // do what you want here
  }
}

Considerations.  Since you are using hook_form_ID_alter instead of hook_form_alter it is pretty safe to assume that this will only fire on the registration form so checking the registration url is a little redundant.  Since you are trying to define a function inside a function, you are used to javascript and the php scope handling is causing you some trouble; you should google for available drupal functions (like current_path() ) to help you before trying to write your own helper functions.


Field type Entity Reference as select list but based on value

You can use Dynamic dependent fields module.

Project page says:

  Makes field value or options depend on other field values when editing
  entity.


You can force clean urls to be Off with the following line in your settings.php file. Add the following to the end -- this settings overrides even whatever is in your database; be sure to remove it later.

/* Turn off clean urls */
$conf['clean_url'] = 0;

Whether or not your webserver supports Clean Urls depends on its' configuration. I recommend reviewing the Getting Started with Clean URLs Guide.


Normally, I just roll my own.

I use a combo of drupal_http_build_query and drupal_http_request to make the request.  I then use drupal_json_decode to parse JSON results, or
simplexml_load_string to parse XML results.

When possible, I try to abstract out all of this into a PHP class as a singleton, which also includes static caching and/or caching via cache_set/cache_get for the actual requests.  I will then wrap up everything as a normal Drupal module.

Invariably, the service I am consuming will have something odd about it that precludes using a generic solution.  Also, I don't find the generic solutions any simpler than a custom one.


Disabling node editing after first node flagging

D7, no need of rules, place this code in your MODULE

function MODULE_node_access($node, $op, $account) {
 if ($op == 'update') {
  $flag='';
  $flag = flag_get_flag('YOUR_FLAG_MACHINE_NAME');
            if ($flag && $flag->is_flagged($node->nid, $GLOBALS['user']->uid)) {
  return NODE_ACCESS_DENY;
    }
  }
}

done, enyoy.


It's possible to pass a variable on attach_library in a template on Drupal 8?

.module

/**
 * Implements hook_ENTITY_TYPE_load()
 */

function my_module_node_load($nodes) {
    foreach ($nodes as $node) {
      if ($node->getType() == 'article') { // is of article content type
        $data_passer = &drupal_static('my_module_node_field_name');
        // use &drupal_static to pass value between hooks.
        $data_passer = $node->field_name->value;
      }
    }
}

/**
 * Implements hook_page_attachments()
 */
function my_module_page_attachments(array &$attachments) {
    if (!empty(&drupal_static('my_module_node_field_name'))) {
      $data_passer = &drupal_static('my_module_node_field_name');
      $node_field_name = $data_passer;
      $attachments['#attached']['drupalSettings']['my_variable'] = $node_field_name;
    }
  }
}

.js

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_behaviour = {
    attach: function (context, settings) {

      alert(drupalSettings.my_variable); //alerts passed in node field_name

    }
  };
})(jQuery, Drupal, drupalSettings);