How do I remove "active" css class from breadcrumbs?

Why not use jQuery .removeclass() on document load so that it removes 'active' from breadcrumb for each page.

More information here.

jQuery remove class


How do I pass variables into Twig template?

The '$' isn't used in twig to designate a variable. This code should work:

<a href="{{ path(route_name, {'node': route_parameters}) }}">
   Link to the object with {{ route_name }} and {{ route_parameters }}
</a>


Display the URL of where the content is located in my search results

Search API provides several general fields (e.g. Aggregated field, Rendered HTML output, URI, etc.) which are available to all Datasources.

Edit your index, when on the Fields tab, click Add fields and under the General heading add URI. You will need to re-index your content and the new fields should be available.


How can I check if a select field has been used with states?

I haven't tried it but a simple negate on an empty string might work:

'#states' => array(
  'visible' => array(
    'select[name="location"]' => array('!value' => '')
  )
)


Drush update for the first time hosed my website

Probably one of the updates of your modules is messing up. Most recently I had this problem with updating Rules which broke my site the same way it did yours (WSOD).

Reverting and updating one by one can show you what went wrong.

If you use drush you can do: drush up modulename (e.g. drush up rules) to update one by one, instead of drush up which updates everything. drush up drupal only updates core.


Okay, I fixed this. It was a legacy script in html.tpl.php. What I should have tried in my debugging was to switch theme. That would have at least narrowed it down to the theme layer.


How to get all nodes referencing a particular node?

The Relationships and Aggregation features are fairly limited as they directly work on the database query, so you can only aggregate using very simple functions like COUNT, AVG, MAX etc.

What you are trying to do (load multiple related values for each row, and render them together) can be done with a sub-view, for example with this module: https://www.drupal.org/project/views_field_view

That would allow you to create a separate view ("Nodes referencing a particular node") with a contextual filter, then add this view as a field to the main view. It slightly impacts performance, as each row in the parent view executes a new sub-view, but should be okay with caching.


There's no inheritance for modules, but much of the functionality they provide can be altered using hooks (search this page for _alter and you'll see the ones core provides).

Specifically for items defined in hook_menu(), you can use hook_menu_alter(), e.g.

function MYMODULE_menu_alter(&$items) {
  // Replace the page callback for the foo/bar path
  $items['foo/bar']['page callback'] = 'MYMODULE_some_function;
}

If I've misunderstood and you mean you literally want to inherit from a module, like subclassing a class, and just change a couple of things, then unfortunately not. Copying the module is the way to go; you'll need to change the names of all the functions so they don't collide with those in the core module, and change paths/cache keys/variables for the same reason.


Try to use Background Images Formatter module, hopefully it will fulfill your requirement.

  Background Images Formatter module provides an image formatter who allows you to set an image
  in background of a div. The images are from a field of an entity and
  not from a configuration page or sth else, so it's very easy to setup
  and manage.

Change selector value to whatever you want in manage display section (explained in attached screen shot)


How to display data in tables using Forms API?

The simplest way to do this (on small forms) that I have found is by taking advantage of the #prefix and #suffix elements in the render array. Here's an example:

$form['foo_fieldset'] = array(
  '#type' => 'fieldset',
  '#prefix' => '
',
  '#suffix' => '
',
  '#tree' => TRUE,
);
$form['foo_fieldset']['header'] = array(
  '#markup' => '

      A checkbox
      A text input
      A text input

',
);

for ($i=0;$i<10;$i++) {
  $form['foo_fieldset']['row_' . $i] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['foo_fieldset']['row_' . $i]['checkbox'] = array(
    '#type' => 'checkbox',
    '#prefix' => '',
    '#suffix' => '	',
  );
  $form['foo_fieldset']['row_' . $i]['text_1'] = array(
    '#type' => 'textfield',
    '#prefix' => '',
    '#suffix' => '	',
  );
  $form['foo_fieldset']['row_' . $i]['text_2'] = array(
    '#type' => 'textfield',
    '#prefix' => '',
    '#suffix' => '	',
  );
}

The other way to do it (maybe known as the "right" way) involves building a theming function to render your form in a table. Take a look at this page (ignoring the tablesort options as you don't care about that) to see how it's done: http://coffeeshopped.com/2010/09/drupal-drag-and-drop-tables-in-custom-modules


Customizing views exposed filter drop down list with css

Unfortunatelly, every browser has its own rendering of drop downs (as well as fileupload boxes). So direct CSS styling of a dropdown element won't work in all browsers.

What you need to do is to use module called Uniform (http://drupal.org/project/uniform). It provides intergration with uniform library which automatically replaces drop downs, fileuploads, checkboxes and radios with custom styled elements.

This will give you ability to style these custom elements and make dropdown lists look the way you want in almost any browser. Just check if this works for you.


How can I auto-populate fields with Ajax?

I was able to get a basic autopopulation callback working based on this question:

How do I modify a core field to use Ajax and add markup?

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Implements hook_form_alter() on behalf of mymodule.module.
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_publication_form') {

    $form['title']['widget'][0]['value']['#value'] = 'enter title here';

    $form['import_from_third_party_service_id'] = [
      '#type' => 'textfield',
      '#title' => t('Import from third_party_service Id'),
      '#description' => t('To autopopulate fields from third_party_service, enter the third_party_service ID above in the textfield above and hit the import key below'),
      '#maxlength' => 64,
      '#size' => 8,
      '#weight' => '-10',
    ];

    $form['import_from_third_party_service_submit'] = array(
      '#name' => 'custom',
      '#type' => 'submit',
      '#value' => t('Import'),
      '#weight' => -9,
      '#ajax' => [
        'callback' => 'mymodule_import_ajax_callback',
        'wrapper' => 'import-wrapper',
      ],
    );

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

  }
}

function mymodule_import_ajax_callback($form, &$form_state) {

  // replace with code to get value from third party service
  $new_title = 'hello world';

  $form['title']['widget'][0]['value']['#value'] = $new_title;

  return $form;
}


Edit a config variable of a custom module in controller

With the ConfigFormBase, you need to implement the editableConfigNames() method.  E.g.

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'example.settings',
    ];
  }

In general, you need to get the editable version of the config file to change it.  ConfigFormBase (well actually, ConfigFormBaseTraits) will only return the editable config is you implement the above method.

For reference, here's how you could do this without the ConfForm logic.

$config = \Drupal::service('config.factory')->getEditable('example.settings');
$config->set('message', 'Hi')->save();

See the documents for details.

Since you are expanding ConfigFormBase, you should be able to use:

$config = $this->configFactory()->getEditable('example.settings');

To get the editable version.


Automatic Nodetitles: How to hide "Pattern for the Title" when empty

Try the -dev version of the module. The release date for 1.0 of autmoatic nodetitles is 2011-Jun-07. You really think something released in 2011 is bug-free in against Drupal 7.31 (current stable release) ...

If you really care you could request a new supported release of the module in the issue queue.


Is there a common nginx conf for Drupal 7 sites?

The main problem that Drupal 7 has with nginx is that Drupal is designed for Apache, and so many modules assume that Apache is installed (and you will always have a little blue entry on your "Status Report" that tells you that you can't use Upload Progress because mod_php isn't installed — annoying).

That being said, thanks to perusio and others, many modules have been created that deal more with nginx and tap into its functionality well. So far, I haven't run into any problem with nginx that would have been fixed by Apache, and nginx is far faster and has a much lighter footprint. This is shown by many benchmarks, but it's also my experience. It also has better integration with php5-fpm, which also outperforms mod_php.

As Drupal develops, it is becoming more backend agnostic. You can see this with 7's database abstraction layer that allows for more database backends, and so I assume that future releases will be designed with other web servers in mind.

So, there are no pitfalls that I've seen at all. You just have to pay a bit more attention to what some of the modules do, or at least what they say they do. If they mention .htaccess files, then make sure that you have corresponding entries in your nginx files that do the same thing. I haven't actually seen a case where nginx fails with a proper configuration.

Perusio's nginx configuration is absolutely amazing, but it takes quite a while to get through it all and understand it. You WILL need to customize it for yourself, and you might run into some problems that you'll need to fix if you use non-standard setups for things like imagecaching or advagg or some others. It also assumes that you're using more than one php-fpm pool. So you'll need to go through and pull out what isn't needed. But it is worth it to take the time to go through it all because you'll learn so much about how nginx works.

I've also ran into several errors with my nginx/drupal sites because I have a tendency to use php-fpm 5.4 or 5.5. The errors have nothing to do with nginx but with Drupal functions themselves as Drupal is just really finishing a transition to requiring php 5.3. If you look around the issue queues, however, you'll find several patches and other solutions to fix modules to work with newer versions of php.

At the end of the day, I would recommend that anyone who is starting with a fresh server use nginx instead of Apache. It's just better.


Assign specific template to specific pages

See here Drupal 7 Theme Hook Suggestions

For nodes You can use

  node--[type|nodeid].tpl.php

  base template: node.tpl.php

  Theme hook suggestions are made based on these factors,  listed from
  the most specific template to the least.  Drupal will use the most
  specific template it finds:

  node--nodeid.tpl.php

  node--type.tpl.php

  node.tpl.php

Also Drupal 6 Template Suggestions

To use same tpl for multiple pages you need to use theme_preprocess_node Like

function theme_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  if(in_array($node->nid), $myuids)
   $vars['template_file'] = 'your_template_file';
}


Create a new View, Give it a Name

Select "comments" for the show option
Display Formats should be Unformatted of Fields -- Not Comments
Hit Continue & Edit
In d7 the content relationship is going to be added for you automatically (just be aware)
Add a new field (Content: Title) -- You might want to exclude it from display
Under the Format settings there's going to be a Grouping field option, select Content: Title.
Save Your View.

That should do it. Sorry is so plain, the views UI is not the easiest to explain, if I tried this post will be insanely long. I try capturing the key details.

Hope this helps.


Another approach would be template files.

The template name depends on the entity you are theming.

For example, with views-view-list.html.twig:

change

<{{ list.type }}{{ list.attributes }}>

  {% for row in rows %}

      {{- row.content -}}

  {% endfor %}

</{{ list.type }}>

to

  <{{ list.type }}{{ list.attributes }}>

    {% for row in rows %}

        {{- row.content -}}

    {% endfor %}

  </{{ list.type }}>

If you go the template route, it can be general so that any view of that type will inherit your custom markup. Or, it can be specific to that view name or ID.

If you want to utilize jQuery, I would recommend being more specific with your class selectors and allow for multiple view instances. For example:

$('.views-class ul').each(function() {
  if ($(this).hasClass('item-list')) {
    $(this).wrap("

");
  }
});

Here is an example views-view.html.twig, which is one level up really from the above template... which prints the views name as a class... which allows view by view customization to structure and layout by CSS alone:

views-view.html.twig

{%
  set classes = [
    dom_id ? 'js-view-dom-id-' ~ dom_id,
    'views-wrapper',
    'view-' ~ css_name,
  ]
%}

  {{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}

      {{ header }}

  {% endif %}

  {{ exposed }}

  {% if attachment_before %}

      {{ attachment_before }}

  {% endif %}

  {% if rows.header %}

      {{ rows.header }}

  {% endif %}

  {# add custom wrapper here around rows, or in deeper template files. #}
  {{ rows | without('header') }}

  {{ empty }}

  {% if pager %}

      {{ pager }}

  {% endif %}

  {% if attachment_after %}

      {{ attachment_after }}

  {% endif %}

  {% if more %}

      {{ more }}

  {% endif %}

  {% if footer %}

      {{ footer }}

  {% endif %}

  {{ feed_icons }}

Plus, this template separates the header and exposed filters making custom templating and individual CSS easier to implement and maintain.

I add this answer because I believe Drupal theming layer should be utilized when possible before jQuery and other front-end technologies.


Adding Boolean or Tag to Image File Field

The module File Entity has it's own field widget "Editable file".

You have to change the image field to use this widget in manage form display of the content type.

Then add a new image in the node creation page and a button will appear to edit the custom fields inline.

The widget has no preview image. So you have to choose, if you want inline fields or preview images.

The File Entity module is a basic solution with a very simple user interface.

A complete media solution for D8 will be provided by the Drupal Media Initiative, here are the latest news:

http://janezurevc.name/releases-of-various-drupal-8-media-modules


Don't delete it, copy it into your theme with the other templates and adjust it there, your theme will override the one in core once you clear cache.


How do I get the router name from the internal path?

Have a look at PathValidatorInterface::getUrlIfValid() or the version that does not check access. That is provided by the path.validator service:

\Drupal::service('path.validator')->getUrlIfValid('node/1')


Have you looked at the PHP filter module? I believe you could make two views, one which displays the burglary safe items and one which displays the non-burglary safes. Add both blocks to all pages, then use the filter module with a PHP expression to decide which to make visible and which invisible.


Notices: Undefined index and trying to get property of non-object include()

You need to check if $page['content']['system_main']['nodes'] is set or not:

Please check updated code:

<?php if ($site_name): ?>
    <?php if ($title): ?>
      <div id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>

          <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">

<?php if(isset($page['content']['system_main']['nodes'])):?>
<?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?>
<?php endif;?>

    <?php else: /* Use h1 when the content title is empty */ ?>
      <h1 id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>
        <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">

<?php if(isset($page['content']['system_main']['nodes'])):?>
<?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?>
<?php endif;?>

    <?php endif; ?>
  <?php endif; ?>


Why isn't my custom Form API #states applied in my webform yaml editor working?

For the simple case where Question 2 is shown only if Question 1 is left unchecked, your YAML doesn't look right to me. If you're editing YAML in the conditions tab for the Question 2 checkbox, then just the last 3 lines should suffice:

invisible:
  ':input[name="some_question[q1]"]':
    checked: true

I don't think you want the "#states" key to be in there anywhere, nor do you want to include any selector information for Question 2.

That's if the YAML is part of Question 2's Condition source. If on the other hand the YAML you're showing is part of the form's source, then it should probably look something like this:

q2:
  '#type': checkbox
  '#title': 'Question 2'
  '#states':
    invisible:
      ':input[name="some_question[q1]"]':
        checked: true

Note that the #states key is shown here, but only once - we're omitting 2 out of 3 of the same lines as above.


change save button text of a node to submit

This is the complete $form['actions']['submit'] array the Node module uses for the form.

  $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#access' => variable_get('node_preview_' . $type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
      '#value' => t('SaveTest'),
      '#weight' => 5,
      '#submit' => array('node_form_submit'),
   );

You need to hook into the node form.

/**
 * Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['#node']) && $form_id == YOUR_NODE_TYPE . '_node_form') {
    $form['actions']['submit']['#value'] = t('YOUR_NEW_VALUE'),
  }
}


Solved that.
I added a line on my code i.e $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;'

class invite_an_userMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

This is now working for me.. Yeppi :)


Creating new content type (programmatically) with CCK fields as default

there are several suggestions about create CCK programatically (also can be seeking for CCK import content):

Programmatically Create, Insert, and Update CCK Nodes: http://civicactions.com/blog/cck_import_and_update
Creating Drupal CCK content programatically/ via API: https://stackoverflow.com/questions/772880/creating-drupal-cck-content-programatically-via-api
Programmatically add CCK field to content type: http://drupal.org/node/702156
Creating nodes with CCK-fields programmatically using drupal_execute() in D6: http://drupal.org/node/439090

I extract interesting comments from StackExchange:

  ...The Node Export module can generate sample code for creating a node
  (complete with CCK fields) programatically.
  There are a ton of modules that try to do the import thing right. Take
  a look at a comparison of them http://groups.drupal.org/node/21338 ...

I hope this information be useful


How to make specific custom table data searchable in Drupal 7?

The Drupal search interface manages a global search mechanism.

Modules may plug into this system to provide searches of different types of
data. Most of the system is handled by search.module, so this must be enabled
for all of the search features to work.

There are three ways to interact with the search system:

Specifically for searching nodes, you can implement
hook_node_update_index() and hook_node_search_result(). However, note that
the search system already indexes all visible output of a node; i.e.,
everything displayed normally by hook_view() and hook_node_view(). This is
usually sufficient. You should only use this mechanism if you want
additional, non-visible data to be indexed.
Implement hook_search_info(). This will create a search tab for your module
on the /search page with a simple keyword search form. You will also need
to implement hook_search_execute() to perform the search.
Implement hook_update_index(). This allows your module to use Drupal's
HTML indexing mechanism for searching full text efficiently.

If your module needs to provide a more complicated search form, then you need
to implement it yourself without hook_search_info(). In that case, you should
define it as a local task (tab) under the /search page (e.g. /search/mymodule)
so that users can easily find it.

The full documentation can be found  at https://api.drupal.org/api/drupal/modules%21search%21search.module/group/search/7


Encode a line break in an HTML email sent by Rules?

Have a look at my answer to "How to use Rules to send an eMail with a body containing all items of a field collection?". It includes a rule (in export format) which looks like so:

{ "rules_field_collection_msg_and_email_body" : {
    "LABEL" : "Field Collection msg and eMail body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The  list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E"
          },
          "PROVIDE" : { "variable_added" : { "variable_for_email_body" : "Variable to use in eMail body" } }
        }
      },
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "article details item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "variable-for-email-body" ],
                "value" : "[variable-for-email-body:value]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E"
              }
            },
            { "drupal_message" : { "message" : "The host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      },
      { "mail" : {
          "to" : [ "site:current-user:mail" ],
          "subject" : "Demo of an eMail with a body containing all items of a field collection",
          "message" : [ "variable-for-email-body" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

Even though your question is not a duplicate of that question, this rule includes a solution which you could also apply in your case:

A Rules Action Add a variable, with machine name variable_for_email_body.
A Rules Action to actually populate the content of this variable_for_email_body (just replace that content to fit your needs, and include whatever HTML tags you want to use in our eMail body).
A Rules Action Send mail, with Message body equal to ... [variable-for-email-body].

Done ...

PS: obviously, this is for D7 ...


Append query parameter to module's javascript based on custom field on page

You probably want to approach this through hook_ENTITY_TYPE_view(). It's easy enough to get the current node in the page attachments hook, but as you only need to take action when a node is being viewed, using the more specific hook seems appropriate.

A basic example:

function my_module_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if ($view_mode == 'full' && $entity->getType() == 'foo' && $entity->hasField('field_bar')) {
    if ( ($val = $entity->field_bar->value) ) {
      $build['#attached']['library'][] = 'my_module/script';
      $build['#attached']['drupalSettings']['my_module']['script']['bar'] = $val;
    }
  }
}

The settings you add to the #attached array will be available in JS after a change to your libraries yml file to add a dependency:

script:
  js:
    ...
  dependencies:
    ...
    - core/drupalSettings

The value will be available in the JS var drupalSettings.my_module.script.bar.


Problem changing the parent group for a node

Ok, I figured this out. Here is what I had to do.

I had to address this slightly differently. I just had to change $node->og_parent = 23; to $node->og_parent->nid = 23;.

I just had to address the specific node id and that fixed it.


How to show block based on browser language?

I don't think this is possible without custom code if you want to do this differently from the current language.

However, you don't need to do all the heavy lifting yourself. See LanguageNegotiationBrowser and the code there, you should be able to more or less copy that 1:1.

Then it will only do it if the language actually exists, respects language mappings and so on. You just have to call that, check if it's different from the current language and if so, display something.

However, properly caching that is going to be fun:

You need a cache context for an arbitrary http header, similar to CookiesCacheContext. so something like http_header:HTTP_ACCEPT_LANGUAGE as a cache context.

That will however not work for anonymous page cache, since that doesn't check cache contexts at all. To work around that, you need your own page cache implementation, that caches by that header, which will obviously result in lots and lots of variations.

So.. maybe you should just do this completely in JS?


How to set target="_blank" for links in CKEditor

D8 Editor Advanced link module

  Enhances the link Dialog in D8 CKEditor. Allows to define the
  following attributes:

  title
  class
  id target
  rel


How to use hook_webform_submission_presave

Notice the value on which you check in the if.

the correct code is:

function webform_presave_webform_submission_presave($node, &$submission) {
  if ($submission->nid == 28) {
    $component_id = 1;
    $submission->data[$component_id][0] = 'Yes';
  }
}


One easy way of doing this, is to use hook_preprocess_node(), and in that function, check for that specific term. And depending on that term, you can actually unset() that file download field in the node, and insert "Please sign up", or something, message in it's place.


User module functions undefined in custom module

So you are just calling a function without telling drupal how to access that function , you can tell drupal about where to find this function using this code :

 module_load_include('module', 'user', 'user.module');


What path to images to use with CKEditor to insert images in content?

You are missing the forward slash: /sites/default/files/mypictures/apache_pb.png

Incidentally, IMCE will make this easier for you.


Can't set default value with hook_field_widget_form_alter()

solved - I noticed my default values worked on node-edit forms, so I tried raising my custom module's weight, which seemed to do the trick :-)


Service event_subscribe before path_processor_inbound

Both priorities are for different queues. If you set a priority for an event subscriber this is only for the specific event you subscribe to. In this example you subscribe to KernelEvents::REQUEST. Then you can only move up and down in the list of all other subscribers to this event.

You can find more information and a list of the D8 events here:

https://api.drupal.org/api/drupal/core!core.api.php/group/events/8.2.x

Path inbound/outbound processors are not even events. These are handled by the PathProcessor Manager and the priority set here is again only for the list of all other path processors.


Search Results page. Move the search form after the results?

Short answer. If you're looking for a twig template to move around the search form, no you can't.

Long answer. Drupal core search dynamically builds its search routes for all searchable entities then handles the page render via SearchController::view(). The controller view method only defines the theme functions/templates for the search results, not the search page as a whole.

If you wanted to move these around the render form & results elements,
It's possible to override the search routes via a custom module so the  _controller property points to a custom controller that extends SearchController and defines a view() method that does something like:

// in my custom search controller:
public function view(Request $request, SearchPageInterface $entity) {
  $build = parent::view($request, $entity);
  // @TODO: alter $build render array so form / results are re-ordered
  return $build;
}


Found the issue: the #type' => 'tableselect has to be built inside a class that extends FormBase.

This Works:

  class DisplayTable_1 extends FormBase {
    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $options = [
            1 => ['first_name' => 'Indy', 'last_name' => 'Jones'],
            2 => ['first_name' => 'Darth', 'last_name' => 'Vader'],
            3 => ['first_name' => 'Super', 'last_name' => 'Man'],
        ];

        $header = [
            'first_name' => t('First Name'),
            'last_name' => t('Last Name'),
        ];

        $form['table'] = [
            '#type' => 'tableselect',
            '#title' => $this->t('Users'),
            '#header' => $header,
            '#options' => $options,
            '#empty' => t('No users found'),
        ];

        // Add a submit button that handles the submission of the form.
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
            '#description' => $this->t('Submit, #type = submit'),
        ];
        return $form;
    }

    public function getFormId() {
        return 'fapi_example_input_demo_form';
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Find out what was submitted.
        $values = $form_state->getValues();
        foreach ($values as $key => $value) {
            $label = isset($form[$key]['#title']) ? $form[$key]['#title'] : $key;

            // Many arrays return 0 for unselected values so lets filter that out.
            if (is_array($value)) {
                $value = array_filter($value);
            }

            // Only display for controls that have titles and values.
            if ($value && $label) {
                $display_value = is_array($value) ? preg_replace('/[\n\r\s]+/', ' ', print_r($value, 1)) : $value;
                $message = $this->t('Value for %title: %value', array('%title' => $label, '%value' => $display_value));
                drupal_set_message($message);
            }
        }
    }
}


How to use the Rules module to unset all flags (set x days ago) without using Rules Scheduler

Create a page and use whatever content type you want for it, eg. "Article". And assign a path to that page also, e.g. on \admin\dummypage. It doesn't matter what the content of that page is.

Then create a rule (using Rules) and enable the Path Rules module also. With this combination you can trigger a rule when the page \admin\dummypage is visited.

The rule can do (= perform a Rules Action) what you want to do. Built a view and with the help of VBO you can apply the changes you want. See therefore the video mention in the next answer.

Then you have to make sure that the page is visited. You can do this by either of following ways:

Put a reminder in your calender that includes the URL of your special page, and click on the page.
Use a websites like http://www.montastic.com/ (they will retrieve this page regularly).
Schedule a cron job. In this cron job you do a wget statement to retrieve the page and send it to null.


How to replace url of taxonomy label link?

I found solution :

function MYTHEME_preprocess_field__field_technologie(&$variables, $hook){
  $element = $variables['element'];

  foreach ($variables['items'] as $index => $item) {

    $route_name = 'entity.node.canonical';
    $params     = 39;
    $tid = $item['content']['#options']['entity']->id();

    $options = [
      'query' => ['technologie' => $tid],
    ];

    $url = Url::fromRoute($route_name, array('node' => $params), $options);
    $variables['items'][$index]['content']['#url'] = $url;
  }
}


The "Rendered entity" row type comes from the Entity API module.
When using the node view row type the views module adds the view object to the node in views_plugin_row_node_view::render(), however the entity module doesn't do anything similar for its row type, so there is no easy way to get the view object when themeing the entity.
If your view is using a page display you can use views_get_page_view() but this doesn't work with other display types, like block views for example.
Note that there is a feature request for the entity module to add the view object to the entity but it is still in development and the module maintainer wants to use a different approach.
So you could use that patch and then when a newer patch comes along you will likely need to make some minor tweaks to your custom themeing code, or you could make a new version of that patch as per the maintainers comments and then use that and possibly avoid having to change your custom code in future.
If you are comfortable updating the patch I would recommend that approach, otherwise I would recommend using the current patch and updating your custom code in future.


Organic groups, group content types and pathauto

I tried:

[node:og-group-ref:url:relative]/[node:menu-link:parent]/[node:title]

Worked like a charm.

So, I guess that you should go with:

[node:og-group-ref:url:relative]/[node:content-type]/[node:title]

Note:
Posted the answer since this was the first result on Google (for me), and no answer was given... Perhaps it will put someone else in the right direction faster.


Accessing hreflang in a preprocessor or twig layer

function MODULE_page_attachments_alter(array &$attachments) {
 foreach ($attachments['#attached']['html_head'] as $can_key => $can_value) {
       foreach ($can_value as $low_value) {
          if (isset($low_value['#attributes']['rel']) && $low_value['#attributes']['rel'] == 'alternate') {
             // Unset canonical tags if present there.
             $attachments['#attached']['html_head'][$can_key]['#attributes']['hreflang'] = 'your value';
           }
        }
     }
}


Customized User Registration form with Profile fields

I believe you're looking for hook_user_presave().

This hook is called directly before the user is saved and the $edit arg will contain all of your form values.

As an alernative, you may look at the Profile2 module


How to use set() on a field within a field collection?

It's not really clear to me why you don't change the values on the entity, but save() is too late.

The entity is built in buildEntity()/copyFormValuesToEntity(), if you want to change how it is build based on form_state values, you have to change them by overriding those methods and doing your changes first.


why am i getting a Drupal\Component\Plugin\Exception\PluginNotFoundException: when the plugin does exist?

after flushing the cache and reinstalling the module

Check that the module is indeed installed at /admin/modules, if it's not, it's due to a migrate tools bug. Perhaps you deleted the part
dependencies:
  enforced:
    module:
      - migd8_node_blog

that you have in your other question, which fixes the reinstall bug if you have it before you install the module.
But if you installed it without the above code, you'll have to run this code once/one time only, and it will allow you to install again as this code removes the stuck configuration.
  $module_path = DRUPAL_ROOT . base_path() . drupal_get_path('module', 'migd8_node_blog') . '/config/install';

  $configs = array();
  $files = file_scan_directory($module_path, '/migrate_plus/');
  if ($files) {
    foreach ($files as $file) {
      $configs[] = $file->name;
    }
    // Delete each config using configFactory.
    foreach ($configs as $config_name) {
     \Drupal::configFactory()->getEditable($config_name)->delete();
    }

    return TRUE;
  }

If the modue is indeed installed, then the issue is due to you trying to assign migd8_node_blog_node as a plugin under the wrong key.
Since this is a source plugin and should be used only be used under source: and not/never under process: or any other key. See my answer.


How do I set the absolute path for an image?

IMCE has a checkbox setting to enable absolute paths in configuration page


Drupal Pager Error Causing WSOD When Viewing Term or Edit Term

If you ever run into a WSOD error, follow the directions here and it will generally tell you the file name and the line number that is causing the WSOD. Or, it will tell you that your server resources are too limited (out of memory).

Here are the instructions:

http://drupal.org/node/158043

Or just Google 'Drupal WSOD' and it's the first link on the SERP.


Adding a module dependency to a public project

I would use hook_requirements() for this, at least in your next version.

It takes severity parameter:

  The requirement's result/severity level, one of:

  REQUIREMENT_INFO: For info only.
  REQUIREMENT_OK: The requirement is satisfied.
  REQUIREMENT_WARNING: The requirement failed with a warning.
  REQUIREMENT_ERROR: The requirement failed with an error.

What you want seems to be REQUIREMENT_WARNING

  Requirement severity -- Warning condition; proceed but flag warning.

That way admin will see that requirement is not satisfied, but will be able to proceed anyway. I currently have this in one of my projects:

If I click "try again", I can proceed, but I will not be surprised if next version will not allow me to proceed, and I am aware that some important functionality will not work if I will proceed now, without addressing this warning.

It's also a good idea to provide a link to installation instructions or drush installation helper syntax in your warning message, as seen on the screenshot.

It should be a temporary solution only, of course. After a week or two you could move your dependency to .info file. Module users will expect it, informed by your warning, and no further logic or warnings will be needed anymore.

Of course changelog and project's page should be a main source of information about serious changes, but many people update using Drupal's built-in functionality and will not even see module's page before update, so it is unsafe to assume they will know basing only on the assumption you posted it there.


Flag module: Do not allow users to flag own content

This is a specific use-case so it may be better to approach this using the Flag API. Specifically, try hook_flag_access and add this to your custom module (or create one). This function takes the following parameters:

hook_flag_access($flag, $entity_id, $action, $account)

and what you are specifically interested in is the following:

$entity_id: The id of the entity in question.

$account: The user on whose behalf to test the flagging action.

The $entity_id will allow you to determine what user id created the entity and the account object will already contain the account of the current user so this function will block flag display if they are the same:

function YOUR_MODULE_flag_access($flag, $entity_id, $action, $account) {

  //load data for the entity
  $entity = entity_load($entity_type, array($entity_id));

  // if the account that created the entity is the same as the user attempting to flag it then block access
  if ($entity[$entity_id]->uid == $account->uid) {
    return false;
  }

}


how to know if the page i am on is a node or not

You can do:

if(\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical'){
 //Do what you want.
}


With thanks to the comments made by various people above, I have now optimised this code so that it doesn't run out of memory.

$chunks = array_chunk($this->nids, 100);

foreach ($chunks as $chunk) {
    $nodes = Node::loadMultiple($chunk);

    foreach ($nodes as $node) {
        //do stuff with the node here...
    }
    Drupal::entityTypeManager()->getStorage('node')->resetCache([$chunk]);
    print "Mem usage: ".memory_get_usage(true)."\n<br>";
}

I couldn't simply do loadMultiple for all the nodes at once as it was still using unholy amounts of memory, but chunking it and resetting the cache after each chunk seems to work nicely.

I experimented with different sized chunks, and I found I got the best mix of performance vs memory usage with the chunk size at 100. YMMV.


Display all nodes with actually viewed taxonomy term

There is a default view related to taxonomy term u can make use of it and change accordingly it will solve ur problem.


PHP filter field behavior with Rules - can't use curl_exec

I solved the issue by moving the code to a custom module, then everything worked. My best guess is that the PHP filter is somehow interpreting the code and filteirng out stuff it considers innapropriate.


Try this:

print date("Y/m/d h:i:s", strtotime($node->event_info_date['und'][0]['value']));

Hope this will help you.


node--TYPE.tpl.php doesn't include the global $language variable as you can see in this document but you can still use it by bringing the variable into scope, using global.

I've updated your code below to show you how to get this working.

<?php global $language; ?>
<?php if ($language->language == 'es'): ?>

<a href="<?php print $base_url . $node_url ?>">Leer más

<?php elseif ($language->language == 'en'): ?>

<a href="<?php print $base_url . $node_url ?>">Read more

<?php else: ?>

<a href="<?php print $base_url . $node_url ?>">Leere más

<?php endif; ?>


It sounds like you want a slideshow for each content, based on that image field. There are many modules that offer that functionality, some themes, and you can always write or otherwise incorporate Javascript to handle it for you.


Security wise it would make sense to import them in Drupal and then use the Mass Password Reset module to reset all passwords.


Placing a block next to the comments section

The regions are usually printed in the page.tpl.php

And the comments are printed with in the node.tpl.php

You could follow the below steps to get a region with in node.tpl.php

Add a region in the .info file by adding regions[custom] = Custom
If you already have a preprocess_node in you theme template.php then add the below code or else create a function in the template.php with the name mythemename_preprocess_node(&$variables)

$variables['custom'] = block_get_blocks_by_region('custom');

This would give you a variable with in the node.tpl.php named custom. This is a renderable array of the blocks with in the region.

Now in your node.tpl.php you would be having something like <?php print render($content['comments']); ?> above or below that you can add

Or you could wrap them in a DIV to suit your requirement.

What ever you add to The region custom would now be displayed near the comments


Super late but support for this request has been added in the latest commit of the Packery module: Commit 24856cf on 7.x-1.x by swim: Added imagesLoaded support on per settings basis.

Just toggle on/off on the settings page, and read the README.txt for the plugin placement. Here is a quote from the updated README.txt:

  ImagesLoaded support

  For imagesLoaded support please download the plugin from https://github.com/desandro/imagesloaded.
  Place the plugin in the libraries directory at sites/all/libraries/imagesloaded so that the file is at sites/all/libraries/imagesloaded/imagesloaded.pkgd.min.js.


How to add value on custom field using rule action

You were close. It's actually @user.current_user_context:current_user.field_user_custom, per "Set a data value"?.


Form text field is too wide for the side bar

You can change field size .Default size is 60.You can text field width by css.


Programatically is it possible to list up all the path aliases that my site has?

I got a fresh installed d8.1 and a fresh pathauto 8.1.x-dev.
I got the url_alias table in my database by installing the module.

the table schema is [pid | source | alias | langcode]

I guess what you want to do is something like this:

$query = db_select('url_alias', 'ua')
  ->fields('ua', array('alias'))
  ->execute();

that should give you the result you want.


I thought this would be quite tough to do, but as it turns out it's fairly easy.

You just need to create a custom module that adds a column to the node table on install, implement hook_schema_alter() so Drupal knows about the new column, and add some logic to provide a value before the node is saved.

Here's a small module that will do the trick:

File: node_table_alter.info

name = Node Table Alter
core = 7.x

File: node_table_alter.install

function node_table_alter_install() {
  // Add the new field to the node table
  $field = array(
    'description' => 'Stores the user id of the last user to alter the node',
    'type' => 'int',
    'unsigned' => TRUE
  );

  db_add_field('node', 'changed_by', $field);
}

File: node_table_alter.module

function node_table_alter_schema_alter(&$schema) {
  // Add the new field to the schema cache
  $schema['node']['fields']['changed_by'] = array(
    'description' => 'Stores the user id of the last user to alter the node',
    'type' => 'int',
    'unsigned' => TRUE
  );
}

function node_table_alter_node_presave($node) {
  // Populate the changed_by column with current user's id
  $node->changed_by = $GLOBALS['user']->uid;
}

You may want to add logic to remove the field again on uninstall, and add an index to the table for the changed_by column (see db_add_index()), but this should give you a good place to start.

The beauty of this method is that you have effectively added a new property to the node. You'll be able to use node_load(), EntityFieldQuerys, etc. with it as if it were any of the other standard properties for a node.

God bless Drupal for being so extendable!


Error guzzlehttp/guzzle ^6.3 -> no matching package found when update from 8.7.9 to 8.8.1

I have just to remove the vendor Folder it works now:
For the complete steps see 8.5.6 Update not being recognized .


I'm not sure why you need an AND condition in the first place for this?

Should be enough to have a contextual filter for the taxonomy terms and a normal filter for the node language?

Note that translations are stored in a single node. I'm not sure what your expectations are about what exactly should be displayed. There are settings about which language should be used for display. You might have a problem with duplicates, though.


What may cause Column not found (nid) in on clause?

The body field should definitively NOT have a nid column in the table. The field_data_body table provided by core will contain an entity_id column which is the reference to the node entity.

2 things I can think of that might be causing this:

You have custom code that's making an erroneous database query in a hook_node_load() function or similar (either directly or using an EntityFieldQuery)
(more likely I think) Core/contributed modules or files have been edited and the changes are only now causing problems.

The best advice I can give is to install the Hacked! module and determine whether or not core/contributed modules have indeed been hacked. If that comes back all clear then you're just looking at an error in some custom code somewhere which will be easy to track down.

If it doesn't come back clear, at least you know what the problem is and you can then decide how best to proceed with getting Drupal back into a proper un-hacked state.

Incidentally, don't worry about the table being referred to as field_data_body0...if you look further down in the query that's just an alias that's being used for field_data_body:

FROM {field_data_body} field_data_body0


Can I add my own if statement to node.tpl to test if field groups are null?

For example:

I created content type
In display settings for Full content display created group group_mygroup

If group elements are empty then group wil not be displaying. In this case you should check it:

//if node's group_mygroup does not exist
//in our case it means that all elements in group are empty
if(!isset($node->group_mygroup))
        print 'Group elements are empty';
print render($content);

As you can read in node template help part - block of comments:

 * Other variables:
 * - $node: Full node object. Contains data that may not be safe.

Now, what you can do to understand solution more clearly:

Install Devel module

  Helper functions for Drupal developers and inquisitive admins. This
  module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries).

Somwhere in your template's code use
dpm($node);
Create content of your type and see how it is displaying. You should see same picture

Click on header of appeared block and you can see structure of node object

If you want to check if some field doesnt exist - use same construction:

if(!isset($node->field_name))
print 'Field is empty';


I believe that the user profile is not a type of "node" so it is invisible to Panels.  Therefore, you will most likely need to write a custom module that will inject the comment form into the user's profile page.


Not sure what a "drupal commerce" form is. There are two major kinds of forms in Drupal Commerce, including the add-to-cart form and the checkout form. Both forms include actions in the Rules module that would let you send an email should one of them get submitted.

Here's a rule that proves the point for add-to-cart (though I would not recommend spamming yourself this way):

{ "rules_spam_yourself" : {
"LABEL" : "Spam Yourself",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"DO" : [
  { "mail" : {
      "to" : [ "site:mail" ],
      "subject" : "Product added!",
      "message" : "\/\/ Product\r\nProduct Added: [commerce-product:title] ([commerce-product:sku])\r\nQuantity: [quantity:value]\r\n\r\n\/\/ Order\r\nOrder ID: [commerce-order:order-id]\r\nOrder Number: [commerce-order:order-number]\r\n\r\nOrder Status: [commerce-order:status-title]\t\r\nOrder State: [commerce-order:state-title]\r\n\r\nCreated: [commerce-order:created]\r\nUpdated: [commerce-order:changed]\r\n\r\n\/\/ Customer\r\nCustomer Email Address: [commerce-order:mail]\r\n\r\n\/\/ Actions\r\nCustomer View: [commerce-order:customer-url]\r\nAdministrative View: [commerce-order:admin-url]\r\n",
      "language" : [ "" ]
        }
      }
    ]
  }
}


It could be because you have enabled clean url but its not working may be because of .htaccess file missing. Just check if there a .htaccess file in your sites first folder. if not copy one from other drupal site. or what you could do is go to yoursite/?q=admin/config/search/clean-urls this page and uncheck enable clean url and save


How to build an url to access filtered view?

Have you tried using Contextual Filters in your view? It sounds like they do what you want.


How can I hide certain values of CCK on node view page?

You can use the Field Permission module. It allows to give different access rights to different roles per field.


Add checkbox setting to a multiple value field

You need to use field collections to group fields together.. Field settings is used for field configuration...

According to your requirement you would like to choose for each field value associated value to track whether image should be displayed or not in home page.. Field collections does this and have integration with views..


How to update users table including relation tables with entity?

Long answer short: You can't save them at once and have to synchronize the user fields manually.

Users are fieldable entities and field data is stored in different tables. So in your case you'd have to create all fields you like to synchronize in all your sites and you need to read them from your base site's user entity field by field and write them to the according tables of your target sites.

A very error prone approach on database level (not mentioning the complexity with a growing number of attributes/client sites).

I strongly suggest a less low-level solution. E.g. by utilizing Drupal's REST services, considering OAuth2/OpenID server/client, LDAP or SAML for user authentication. (Just some keywords to use Google with; there are some contrib D8 modules in heavy development for all of these approaches.)


Modify values that are received via Feeds_ex

Try hook_feeds_presave().

Just explore $entity object. You will get some idea.

Below is a example code.

$entity->lang_country[LANGUAGE_NONE][0]['value'] = 'en';
// After split [language-country] store your lang here.

Update:
Also check feeds_tamper


Extract final value from nested field collection

Try this :

$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_rich_text_group->value() as $value) {
  $field_collection_wrapper = entity_metadata_wrapper('field_collection_item', $value);
  $field_collection_myfield = $field_collection_wrapper->field_myfield->value();
  print_r($field_collection_myfield);
}

Field Collection is an entity, so if you want to access its field you have to pass the field collection in entity_metadata_wrapper. Then you can access the value of your fields in field collection like you do with your $node_wrapper


Yes, just use Date-Filter (node) and expose as Popup. I assume you have the Date module (6.x-2.9 in my case) and Date Popup module installed and set your Datepicker on admin/settings/date_popup...

In Views it probably won't work in the preview, but on the view itself it will.


How to increase the width to the Omega sub-theme more than 950 usable pixels

My guess would be not to touch to the original theme and create a new one where you can override without touching anything to the original.

Now, I can't help any more, I never used that theme and Drupal 7 yet.


Enabling AJAX in Views breaks Form API AJAX button (Drupal 8)

The issue is in this line of RenderElement::preRenderAjaxForm:

$settings['url'] = Url::fromRoute('<current>');

When the form with the button "add to cart" is rendered inside of an ajax request of a view, then the url is set to the wrong endpoint /views/ajax.

A workaround would be to add a static url in the ajax setting of the form element, so that it won't be set dynamically:

use Drupal\Core\Form\FormBuilderInterface;

  '#ajax' => [
    'callback' => '::add',
    'wrapper' => $wrapper,
    'url' => Url::fromRoute('<front>'),   // set this to the route of the view page
    'options' => ['query' => \Drupal::request()->query->all() + [FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]],
  ]

If you use the form in multiple pages you would need to adjust the code to only set the url when the form is rendered in this view.


How to publish in an organization with hierarchy?

Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site.
What are the features of the Group module versus Organic Group module?

Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 2            ! Customers  ! 5             ! Lead
 2            ! Customers  ! 6             ! Prospect
 2            ! Customers  ! 7             ! Licensed Customer
 2            ! Customers  ! 8             ! Sales
 2            ! Customers  ! 9             ! Support
 2            ! Customers  ! 10            ! Accounting
 2            ! Customers  ! 11            ! R&D
 3            ! Project    ! 12            ! Project Manager
 3            ! Project    ! 13            ! Developer
 3            ! Project    ! 14            ! Customer

Group Types

The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles

For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 2 roles that are configured:

Instructor.
Student.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These are the Group Specific Roles: these roles can be configured per group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor and Student (which are not available for the other group types.

On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.

Groups

Each of the configured group types can have any number of Groups.

Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions

For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

Your usecase

In your case, your challenge seems to be about this:

  ... content going through different levels like this?

Translated to an implementation using the Group module, it seems to me that all that's needed is to assign, and later on re-assign, each node (content) to an appropriate group. Whereas you use appropriate group permissions/roles to accutally perform these assignments.

And for the required group types to be configured, I'd start with these specific group types:

Teams (with groups Team T1, Team T2, ..., Team Tn).
Sections (with groups Section Sa, Section Sb, ..., Section Sx).
Devisions (with groups DevX, DevY, DevZ).

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Using hook_theme_registry_alter to only modify specific pages instead of all pages

For simple alterations, instead of implementing hook_elements(), you could simply implement hook_form_alter() or it's cousin hook_form_FORM_ID_alter(). Both of these functions will effectively allow you to (as their name suggests) alter a form's input elements, and they are much easier to implement than hook_elements(). The former gets called for every function in the website, while the later only gets called for the FORM_ID that you specified in your hook implementation.

If the ID of the form you wish to modify is my_form, then hook_form_FORM_ID_alter() would be written as hook_form_my_form_alter(). If you want a more thorough explanation of these two hooks, I highly recommend reading Lullabot's writeup on modifying Drupal 6 Forms.


If you use devel module a simple approach for debugging entity query could be use the debug tag (simply add $query->addTag('debug') to your query).
Here an example

$query = $this->entity_query->get('node');
$query->condition('status', NODE_PUBLISHED);
$query->addTag('debug');
$query->execute();

And the result


Redirect user based on role and node content

Use Rules module to redirect based on user roles.

After Installing Rules module, Go to Admin -> Configuration -> Rules (admin/config/workflow/rules/)
Add new rule
Enter rule name & select User has logged in from React on Event
Add new condition and set User has Role Select the required role and Save
In Action add new action Set it Page Redirect & enter the redirection URL


How do I enable the WYSIWYG editor on fields?

Click Configure of your CCK field and choose Filtered text (user selects input format) under Text processing. This configuration will show input format selection you need to choose. As long as you configure properly your WYSIWYG module the editor will show.


Where should I be storing custom node-related data?

I would suggest making your own table in the database, it's a perfectly acceptable practice if you name the table something unique that isn't likely to collide with other modules.

The database API is an extremely useful resource for this.

[edit:] Thanks to J. Reynolds - in this instance you will definitely need to tell Views about your table.


Problems moving whole project from one directory to another

Had to change the path name in civicrm.settings.php from:

G:\XAMPP_2018\htdocs\crm4

To

C:\Core\XAMPP_2018\htdocs\crm4\

This is around LINE 180:

Code looks like this:

$civicrm_root = 'G:/August25/XAMPP_2018/htdocs/crm4/sites/all/modules/civicrm';
if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
  define( 'CIVICRM_TEMPLATE_COMPILEDIR', 'G:/August25/XAMPP_2018/htdocs/crm4\sites\default\files\civicrm\templates_c\');
}

But the slashes also have to be forward like this "/", I searched from Windows path, that's why I couldn't find the code using find and replace!


How to use Views & Entity Reference to create dynamic URLs that are based title from the referenced node

This is how I solved a similar problem:  Create a filter on the title and use the relationship: entity.  Then, in a custom module put something similar to:

    function MYMODULE_views_pre_view(&$view, &$display_id, &$args){
      switch($view->name) {
        case 'view_name':
          $value = arg(x);
          $view->display['default']->handler->options['filters'['field_name']['value'] = $value;
        break;
      }
    }

I'll probably go ahead and build a more universal module out of this because of how often I use it.  The benefit is you can inject an argument as a filter.  I use dashes for spaces and include a str_replace(); to replace dashes with spaces for the filter.  You loose some validation, etc. but there's a bunch of modules that provide filters but no contextual relationship.  This binds the two in a hacky way.


How to use Dompdf with Entity Print without composer?

I have been using the same module and was able to get it setup with Dompdf. Here are the steps in detail I used.

Summarized steps:

composer require drupal/entity_print (this automatically downloads the dompdf dependency for me)
On the content type, I enabled the custom display setting of PDF
Followed steps in "From your theme" to create the print.css and twig templates
composer require dompdf/dompdf (in case #1 doesn't download it)

Alternative: Ludwig module


This is probably the solution, "Making region content available to node templates in Drupal 8": http://atendesigngroup.com/blog/making-region-content-available-node-templates-drupal-8

Replace “THEME” with your theme name below:

/**
* Implements hook_preprocess_node() for NODE document templates.
*/
function THEME_preprocess_node(&$variables) {
  // Allowed view modes
  $view_mode = $variables['view_mode']; // Retrieve view mode
  $allowed_view_modes = ['full']; // Array of allowed view modes (for performance so as to not execute on unneeded nodes)

  // If view mode is in allowed view modes list, pass to THEME_add_regions_to_node()
  if(in_array($view_mode, $allowed_view_modes)) {
    // Allowed regions (for performance so as to not execute for unneeded region)
    $allowed_regions = ['primary_content'];
    THEME_add_regions_to_node($allowed_regions, $variables);
  }
}

/**
* THEME_add_regions_to_node
*/

function THEME_add_regions_to_node($allowed_regions, &$variables) {
  // Retrieve active theme
  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Retrieve theme regions
  $available_regions = system_region_list($theme, 'REGIONS_ALL');

  // Validate allowed regions with available regions
  $regions = array_intersect(array_keys($available_regions), $allowed_regions);

  // For each region
  foreach ($regions as $key => $region) {

    // Load region blocks
    $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme, 'region' => $region));

    // Sort ‘em
    uasort($blocks, 'Drupal\block\Entity\Block::sort');

    // Capture viewable blocks and their settings to $build
    $build = array();
    foreach ($blocks as $key => $block) {
      if ($block->access('view')) {
        $build[$key] = entity_view($block, 'block');
      }
    }

    // Add build to region
    $variables[$region] = $build;
  }
}

After clearing caches, I can now print content specified in Drupal’s block layout using my node template files. For example, if I’ve specified primary_content in $allowed_regions, then I can access it via node--node_type.html.twig with:

{{ primary_content }}


Modifying behavior of "You Saved..." info in cart when attributes are chosen

Doing this in jquery is probably going to be the quickest way to achieve this, especially since you're dealing with custom code. The jquery code you posted is close, but you need a different approach to test if the list-item contains text:

$(document).ready(function(){
    if ($('.item-list' + ':contains("someothertext")').length != 0 ) {
        $(".cart-savings").toggle();
    }
});

Also, note I used the toggle() function here which is a quicker way to determine visibility than adding / unadding a visibility class.

You can verify the above code here: http://jsfiddle.net/JZnPq/


How to redirect to www without editing .htaccess file?

It's always going to be better to do this with .htaccess, or in other web server config, but if you need to do it in php, put this at the top of settings.php:

if ($_SERVER['HTTP_HOST'] == 'example.com') {
  header('Location:http://www.example.com' . $_SERVER['REQUEST_URI']);
  exit();
}


How to configure Node Export to mass node export?

You can do it with drush:

$ drush help ne-export
Export nodes using Node export.

Arguments:
  nids : A list of space-separated node IDs to export.

Options:
  --file : The filename of the output file.  If supplied, the node code will be
exported to that file, otherwise it will export to stdout.
  --format : If supplied, node code will be output using a particular export
format, if available. (e.g. serialize)
  --status : Filter for 'status'; A boolean value (0 or 1) indicating whether
the node is published (visible to non-administrators).
  --promote : Filter for 'promote'; A boolean value (0 or 1) indicating whether
the node should be displayed on the front page.
  --sticky : Filter for 'sticky'; A boolean value (0 or 1) indicating whether
the node should be displayed at the top of lists in which it appears.
  --translate : Filter for 'translate'; A boolean value (0 or 1) indicating
whether the node translation needs to be updated.
  --language : Filter for 'language'; The language code (e.g. de or en-US) of
this node.
  --type : Filter for 'type'; The machine-readable name (e.g. story or page) of
the type of this node.
  --sql : Filter by SQL (EXPERIMENTAL); An SQL query string that returns nids
(e.g. "SELECT nid FROM nodes WHERE nid < 10").
  --code : Filter by PHP code (EXPERIMENTAL); PHP code that prints or returns,
an array or CSV string of nids (e.g. "custom_get_my_nids();"). Don't include PHP
tags.

For example,

drush ne-export --type=article --file=article.txt

will output all of the article nodes to article.txt in serialized format.  You can then use drush to import them:

$ drush help ne-import
Import nodes previously exported with Node export.

Arguments:

Options:
  --uid : User ID of user to save nodes as. If not given will use the user with
an ID of 1. You may specify 0 for the Anonymous user.
  --file : The filename of the input file.  If supplied, the node code will be
imported from that file, otherwise it will import to stdin.

For example:

drush ne-import --uid=1 --file=article.txt

*updated


How to create a link in my view of users to perform an operation like Active or Block?

Have a look at the Rules Link module. Some details from its project page:

  This module lets you create links which trigger arbitrary functionality with the help of Rules.

  Features:

  Attach the link to any entities.
  Show the link only for certain bundles.
  Narrow the entities on which the link will be shown using the visibility conditions.
  The links are usually displayed using Views.
  For entities that can be displayed, the links can be shown on node view.
  Supports an arbitrary number of additional Rules parameters for passing context via Views.
  3 types of links: Javascript, Normal and Confirmation form links.
  Use individual permissions for each link.

Some more details (from its README.txt):

  To create a new link go to admin/config/workflow/rules_links and click on "Add rules link". Enter the title of your link and set all the settings. After clicking on the "Save Rules Link" button, the module will generate a new And- and Rules-Set and their forms will be embedded into the rules link editing form.

  The And-Sets are called Visibility Conditions and will define when to render the links. The Rules set is the rule, that will be triggered on clicking the rule. Additionally Rules Links also generates access permission for each link, which you'll have to set in admin/people/permissions.

  The best way to display the links is currently using views. Rules Links link will create a Views field for each link, using the title of the link as title for the field. So if you have link for nodes with the delete 'Delete node', you'll find the Views field under name 'Content: Delete node'.

  Alternatively you can use render the links directly in the entities that can be displayed, using the option 'Show link in entity' in the Rules Links settings.

  Note that this will not work for links were the parameters have multiple
  paramaters.

  If you would like to render a link yourself in a theme or in a module, than use the function rules_link_render_link().

Note the "The best way to display the links is currently using views" in the above quoted text, which is pretty close to what you're asking for.

PS: I'm assuming this question is about D7.


How do I go to Checkout Page without product in cart?

You can add the following code to a custom module:

/**
 * Implements hook_menu_alter().
 */
function YOURMODULE_menu_alter(&$items) {
  // Alter the default checkout callback to allow checkout without products.
  $items['checkout']['page callback'] = 'YOURMODULE_checkout_router';
}

/**
 * Implements hook_commerce_checkout_order_can_checkout().
 */
function YOURMODULE_commerce_checkout_order_can_checkout($order) {
  return TRUE;
}

/**
 * Displays the checkout form and create the user a cart if none exist.
 */
function YOURMODULE_checkout_router() {
  global $user;
  // Load the shopping cart order.
  if (!($order = commerce_cart_order_load($user->uid))) {
    $order = commerce_cart_order_new();
  }
  drupal_goto('checkout/' . $order->order_id);
}


How can we apply group_concat using views?

After some R & D on the above issue. I found that Views Aggregator Plus has that feature which I require. However, there are some minor configuration to be made but this module is quite helpful the result which I was expecting.


Filtering a View that is output as a Block

Ok finally dug up my answer.

http://drupal.org/node/386388

In summary, the scripts for ajax views cannot be added if you embed your view in a page template. You either have to create the view in preprocess_page or in a node template file.


Display an Array as a List inside a Table

There's theme_item_list() which

  Returns HTML for a list or nested list of items.

e.g.

$rows[] = array(
  ...
  array('data' => theme('item_list', array('items' => $models))),
  ...


How can I add Support module's tickets to the homepage?

You could change the default front page for your site in the admin section at example.com/admin/config/system/site-information.  Enter support and it will now be your front page.


How do I Bulk Edit Fields or Taxonomy of Nodes?

Drupal core doesn't provide this functionality, so yes, you need to implement it yourself.

Yes, you can implement your own action plugin to do this. You can also have a form to select which tag you want to apply. Have a look at the node delete action plugin, which uses a confirmation form, but you can implement whatever functionality you want in that form.

Keep in mind that Drupal core is missing another important feature for your use case. The ability to apply a bulk action to more than one page. The best you can do until there is a port of the contrib module to provide this to increase the amount of rows per page, so that you need to repeat it fewer times.


Get fields from a collection field in .theme

Use the following code:

$fieldCollectionItems = $node->get('field_collection_gallery');

    foreach ($fieldCollectionItems as $key => $item) {
      $fcItem = FieldCollectionItem::load($item->value);

      if ($fcItem instanceof FieldCollectionItem) {
        $fcValue = $fcItem->get('field_name')->getValue();
      }
    }

The $fcValue variable should contain the value from the field in the field collection item.

You have to replace the field_name with your own field name in the last line in the foreach() loop.


Create a view to show a user his or her recent activity

Why not just use the  heartbeat or the message module and let them do the heavy lifting for you


Commerce : adding optional insurance block to shopping cart form : ajax callback

To implement an optional insurance field in the shopping cart : first, follow question steps 1 to 6.

For a nice ajax replacement, create a very simple Order total view with a Global: Custom text field (which we'll hide with a css class, just to have the minimum :one field) and put Commerce Order: Order total field in footer.

Then alter the form and setup the ajax callback :

function vts_insurance_form_views_form_cart_field_assurances_block_alter(&$form, &$form_state, $form_id) {
  //add ajax to our field
  $form['field_order_assurances'][0]['field_order_assurances']['und']['#ajax'] = array(
    'callback' => 'vts_insurance_cart_refresh',
    'progress' => array('type' => 'throbber', 'message' => ''),
  );
  //unset unused buttons
  unset($form['field_order_assurances'][0]['actions']['submit']);
  unset($form['actions']);
}

function vts_insurance_cart_refresh(&$form, &$form_state) {
  $order = commerce_cart_order_load($GLOBALS['user']->uid);

  //set the order insurance field value & save it
  $order->field_order_assurances['und'][0]['tid'] = $form_state['values']['field_order_assurances'][0]['field_order_assurances']['und'][0]['tid'];
  commerce_order_save($order);
  commerce_cart_order_refresh($order);

  //Display a message to customer
  $term = taxonomy_term_load($order->field_order_assurances['und'][0]['tid']);
  dsm(t('Insurance : you selected ').$term->name);
  $commands[] = ajax_command_replace('.messages.status', theme('status_messages'));

  //Refresh the cart total display
  $cart_total = commerce_embed_view('shopping_cart_total', 'block', array($order->order_id));
  $commands[] = ajax_command_replace('.view-shopping-cart-total', $cart_total);

  return array('#type' => 'ajax', '#commands' => $commands);
}

In the module js file, play with your DOM elements to display them as wished

(function ($) {

  $(document).ready(function(){
    //A wrapper for the first shopping cart total refresh
    $('.commerce-order-handler-area-order-total').wrap('

');
    //Move the editable field above buttons
    var assurances = $('.view-id-cart_field_assurances').detach();
    $('.view-shopping-cart-total').before(assurances);
    //A wrapper for ajax messages
    var insurance_message = $("

");
    insurance_message.appendTo(assurances).hide();
  });

})(jQuery);

A rule setting up a Fee price component, depending on the insurance field percentage value.

{ "rules_calcul_des_assurances" : {
    "LABEL" : "Calcul des assurances",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Cart" ],
    "REQUIRES" : [ "commerce", "rules", "commerce_fees" ],
    "ON" : { "commerce_fees_order" : [] },
    "IF" : [
      { "entity_exists" : {
          "type" : "commerce_order",
          "property" : "order_id",
          "value" : [ "commerce-order:order-id" ]
        }
      },
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "field_order_assurances" } }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "commerce-order:commerce-order-total:amount-decimal" ],
            "op" : "*",
            "input_2" : [ "commerce-order:field-order-assurances:field-pourcentage" ]
          },
          "PROVIDE" : { "result" : { "assurance_cout" : "Co\u00fbt de l\u0027assurance" } }
        }
      },
      { "commerce_fees_apply" : {
          "entity" : [ "commerce-order" ],
          "fee" : "assurances",
          "amount" : [ "assurance-cout" ],
          "currency_code" : "EUR"
        }
      }
    ]
  }
}

With such implementation, it is possible to add any kind of field in the shopping cart footer, allowing customers to choose options that will change the order total adding a price component, with Ajax feature. Nice.


change action link on views exposed form

You can alter the value of the submit button inside the view:
Advanced -> Exposed From -> Exposed form style -> Settings -> Submit button text.
From http://drupal.org/node/109604:
The documentation for Views 2 and Views 3 for Drupal 6 and Drupal 7 is contained within Views module!
Install the Advanced Help module to access it.


Drupal Commerce Paypal WPS - Connection refused

This was an environmental problem. The Drupal server did not have a direct connection to the internet. Setting the proxy settings in settings.php got this to work.

http://devincarlson.ca/blog/configuring-drupal-use-proxy-server-when-making-external-http-requests

In my case the settings I had to set were:

$conf['proxy_server'] = 'my server';
$conf['proxy_port'] = 1234; // port number


Import image using feeds and image path?

I believe it should work automatically, but you need to use a valid path schema, for example: public://images/myimage.jpg. Otherwise Feeds needs to know the absolute path to these images. If needed, use Feeds Tamper to correct image paths.


How to make role field on approval in the Edit Profile page by Admin

You can't allow the users to change the role/profile directly, if this is what you want. What you'll need instead is another field to act as a proxy for the roles, so you would have a checkbox for each one.

Then you can use a rule to detect a change to the user and if there is a difference in the old and new values of this field, send an email to the admin.

I think this can probably all be done with contrib modules though it will not be a trivial matter, and would be easier to build and maintain with a little custom code acting as glue.


The reason was a failed loaded javascript file.
I use the following code to add a JavaScript file:

drupal_add_js($p . '/slider.js','module','footer');

So the following HTML was added in the footer of the page:

<script type="text/javascript" src="/sites/default/modules/custom/slider/slider.js?G"></script>

At some point I renamed the file slider.js, so it stopped being loaded, and this is the reason behind the Firebug error.

In the "Net" tab, Firebug was not showing any error; it was showing just a "301 Moved Permanently" next to the slider.js file.


How can i change registration email send to admin

Unlike normal users there's is no UI to change the text of the message sent to administrator on account creation.

You could implement hook_mail_alter(), to achieve this via a custom module:

function MODULE_mail_alter(&$message) {
  if ($message['id'] == 'user_register_pending_approval_admin') {
    //$message['body'] is the array you want to change.
    $message['body'][] = 'Your custom message for admin goes here.....';
  }
}


I have a client who takes deliveries in the form of the sites/ folder and a database backup, and installs them in Pressflow.  As long as the Pressflow version isn't older than the Drupal version, we have never had problems.

There is no real migration.  Just replace the files, run update.php, and move on.  Two minor gotchas, though.

Pressflow error reporting is different, and a lot (and I mean a lot) of E_NOTICE will end up in the dblog.  You may want to adust error_reporting to exclude these.

Pressflow is API compatible with Drupal, but I have run into situations with anonymous sessions.  Occasionally, I need to manually call drupal_start_session, which is in Pressflow 6, from a custom module before I start doing stuff with $_SESSION.

Personally, I would give Zend Server CE a shot, too.  The Pressflow 6 site that I am wrapping up really flies in this environment.


Panels Node template with additional arguments

You need a few components to make this work properly.

You View must have a display of type "Content pane".
A contextual filter.
In the Pane settings you should set your argument input to be "From context", and then picking an argument source that matches what your contextual filter wants. Most likely that will be a node id. (The argument setting could be a specific argument, first, second or so, as well, but that's generally not a very good idea)
Add the View pane to your panel page, not the View itself. If the Pane doesn't show up in the listing, your Pane settings are wrong.
Done.


Node language in views contextual filters

Why isn't the current users language suitable, that's what you want

Have you looked in the filters section of views (Bottom left of the views editing screen) rather than contextual filters? There should be the current users language as a filtering option in there.


Open the View and you'll see if it is a page or block, if it is a page you can see the path to the page under Page Settings, if it is a block just look for that block in the list (/admin/structure/block).

The block is named like Views:[view_name] and if it is disabled I think you can safely remove that View, if not you can see the region and where you can see that block when you edit block and look at Visibility settings.

I think that there is no other automated way to find out where some View is used.


Can you export and import templates for multi-site use?

If it's Drupal8 you can:

save webform as a webform template
export/import the source file.
 You can copy it and the paste to the new webform on the other site. It will duplicate an identical webform for you.


Cannot create hook_menu subitems with proper position in administrative menu

I think the MENU_LOCAL_ACTION type for your sub-menus is not the good choice.

The Menu item types documentation tell us :

  MENU_LOCAL_ACTION : Menu type -- An action specific to the parent,
  usually rendered as a link.

If you want to have a menu with sub-menus, you need to also define a page call back for it. You can use the system_admin_menu_block_page, witch display a bloc with all the sub-menus links.

// Main menu link
$items['admin/store/products-fabrics'] = array(
    'title' => 'Látky produktov',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'type' => MENU_NORMAL_ITEM,
);

// Sub menu links
$items['admin/store/products-fabrics/'.$product['nid']] = array(
    'title' => $product['title'],
    'access arguments' => array('access administration menu'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('activit_eshop_fabrics_of_products_form'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'd_forms.inc',
);


1.If you want to just add a class to the content of view container you can add it from the view itself

if you have a template file for views you can add the class there. or you can set it as in views header and footer


How can I check I run the Drupal Commons profile?

The profile used to install the site is stored in the variable install_profile. There's a few different ways you can see the value:

Pop into the variable table in your database and search for install_profile:

select value from variable where name='install_profile';

Install the Devel module and visit mysite.com/devel/variable
Put this custom code in a template file somewhere:

<?php print variable_get('install_profile', 'No install profile found.'); ?>

Hope that helps


Node authors notified by email when a comment is added using trigger module - node token not getting

Maybe you can try these module
http://drupal.org/project/comment_notify

Video tutorial
http://drupalize.me/videos/notify-author-comments
http://drupalize.me/videos/notify-comment-reply


In Drupal 7, the default is to use an excerpt (i.e. a trimmed value) of the full text as the summary. The summary is the text that is placed on the front page.

If I understand your question correctly, you do not want to use the default excerpt, because this confuses the reader.

Instead of this default, you can type in whatever you want as the summary to appear on the front page, e.g.:

  Here is a long and quite interesting quote about lorem ipsum dolor sit amet.  To read the full text, just click on the  Read more link below.

To add a hand-written summary, click in the "(Edit summary)" link just above the main body text field in the input form.  Leave this field blank to use the trimmed value of full text as the summary.


Improving performance with Field Collections?

Update: In the end, I abandoned field collections and created a custom compound field that is attached to the 'course' content type.

This pretty much eliminated the performance problems. Opening a course node with 130 lessons in the field now takes 3-6 seconds, depending on the server.

And because the field is unlimited multivalue, the delta works a sorting mechanism for the lessons in views, etc.

I also added code to add more than one item at a time as seen here:

Slow "Add another item" with unlimited valued fields

When there are a lot of items in the field, adding a new item ends up taking a lot of time.

Good resources:

http://www.phase2technology.com/blog/compound-fields-in-drupal-7/
https://drupal.org/project/examples (field example)
https://api.drupal.org/api/drupal/modules!field!field.api.php/7


Theming own field: how do I control the outer markup?

The way to correctly theme what you are asking is shown here: theme_field()

In particular:

  This is the default theme implementation to display the value of a
  field. Theme developers who are comfortable with overriding theme
  functions may do so in order to customize this markup. This function
  can be overridden with varying levels of specificity. For example, for
  a field named 'body' displayed on the 'article' content type, any of
  the following functions will override this default implementation. The
  first of these functions that exists is used:

THEMENAME_field__body__article()
THEMENAME_field__article()
THEMENAME_field__body()
THEMENAME_field()

  Theme developers who prefer to customize templates instead of
  overriding functions may copy the "field.tpl.php" from the
  "modules/field/theme" folder of the Drupal installation to somewhere
  within the theme's folder and customize it, just like customizing
  other Drupal templates such as page.tpl.php or node.tpl.php. However,
  it takes longer for the server to process templates than to call a
  function, so for websites with many fields displayed on a page, this
  can result in a noticeable slowdown of the website. For these
  websites, developers are discouraged from placing a field.tpl.php file
  into the theme's folder, but may customize templates for specific
  fields. For example, for a field named 'body' displayed on the
  'article' content type, any of the following templates will override
  this default implementation. The first of these templates that exists
  is used:

field--body--article.tpl.php
field--article.tpl.php
field--body.tpl.php
field.tpl.php

  So, if the body field on the article content type needs customization,
  a field--body--article.tpl.php file can be added within the theme's
  folder. Because it's a template, it will result in slightly more time
  needed to display that field, but it will not impact other fields, and
  therefore, is unlikely to cause a noticeable change in website
  performance. A very rough guideline is that if a page is being
  displayed with more than 100 fields and they are all themed with a
  template instead of a function, it can add up to 5% to the time it
  takes to display that page. This is a guideline only and the exact
  performance impact depends on the server configuration and the details
  of the website.

Finding the right naming convention is somewhat a mess, so I suggest you to try the Theme developer module in order to find out all the possible names for your template file.

Here is the naming convention guide. Given your comment my best guess would then be: field--field-chemical-hazards.tpl.php


You may have to save the changes after you make them.  After your decrement action, add another action to save the entity.


In your htaccess file you can set the rewrite rule:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /site


How do I hide the title when creating/editing a specific type of content?

A great module you can use is Auto NodeTitle :

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).

  Advanced users can also provide some PHP code, that is used for
  automatically generating an appropriate title.


Give File (Field) Paths a try:

The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.
In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.


How to pass Webform elements from controller to custom twig template

my_module.module:

/**
 * Implementation of hook_theme
 *
 * Since we have a lot to explain, we're going to use Twig to do it.
 */
function my_module_forms_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'template' => 'my-template',
      'variables' => ['form' => NULL],
    ],
  ];
}


Location subfields problem to render in teaser template node

The location field module wrap fields inside #location so try with :

<?php print render($content['field_mapa'][0]['#location']['street']); ?>

and

<?php print render($content['field_mapa'][0]['#location']['city']); ?>


You can theme (you dont want to change the value stored in the DB, just change its displayed value) the view row value by using a template suggestion:

I prefer using a preprocessor function to do this on the field. This blog post covers how to do this for a specific view_name and field.

From the blogpost:

  There is an issue to let Drupal 7 and 8 themes implement a
  preprocess/process function per view as it is possible in Drupal 6,
  but it is in development (see issue).

  Until it is fixed there is a way to achieve that behaviour:

<?php
/**
  * Generic preprocess that is still working on D7
  */
function MYTHEME_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name)) {
    $function = __FUNCTION__ . '__' . $vars['view']->name . '__' . $vars['view']->current_display;

    if (function_exists($function)) {
     $function($vars);
    }
  }
}

/**
  * Then the specific preprocess that worked without the above code for D6
  */
function MYTHEME_preprocess_views_view_fields__VIEWNAME__DISPLAY(&$vars) {
  // my specific preprocess code
}
?>

There's also like views_custom_styles (sandbox project) and views_php which will let you do the same thing -- but for what you're asking (to my knowledge) you're gonna have to write code.

The preprocessor example I give is a clean solution re-using the Theme API (suggestions) and hooks.