I just did a lot of this with Menu Block. I prefer Menu Block as it is a little more flexible and offers more template suggestions and hooks than the core menu module. It kind of looks like you are building your own block above, I can't tell, but you can save time by using Menu Block in that case.

In one of my menus, this is the twig file that handles the output. I did not do any preprocess or extra stuff, just built around the macro concept used in menu.html.twig. Every parent item has children, and if those children items exceed 7, it will start a new list. For example, if the menu link has 14 children, then my code will have a drop down consisting of 2 unordered lists with 7 links each. Our style then makes them into columns. This is a little different from your use case, but should get you on the right track.

{#
/**
 * @file
 * Theme override to display a menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

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

      {% for item in items %}
        {%
          set classes = [
            'global-top__utility-item',
            'js-utility-item',
            item.in_active_trail ? 'active-trail',
            item.below ? 'has-submenu'
          ]
        %}

          {{ link(item.title, item.url) }}
          {% if item.below %}
            {{ menus.submenu_links(item.below, attributes, menu_level + 1) }}
          {% endif %}

      {% endfor %}

  {% endif %}
{% endmacro %}

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

    {% for chunk in items|batch(7) %}

        {% for item in chunk %}

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

        {% endfor %}

    {% endfor %}

{% endmacro %}


Using the Features module let me export the menu, at which point it was easy to set 'hidden' => '1' on the 'main-menu:' link.


views with multiple contextual filters - should return data only when both or any one filter is present

Perhaps this is what you're looking for:
https://www.drupal.org/node/1871388

Otherwise, it looks like you might want to set up what your contextual filters do when the arguments  are not available:

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


How can check if a field is empty in a node template?

Check on node.field_notes something like

 {% set count_paragraph_element = node.field_notes | length %}
  {% if count_paragraph_element == 0 %}
      Empty
  {% else %}
      Not empty
  {% endif %}

Update
if you want to check if text plain long field has empty value try this.
I assume that your field machine name is field_text:

{% for item in node.field_notes %}
      {% if item.entity.field_text.value is empty %}
        text value is empty
      {% else %}
        text value not empty
      {% endif %}
{% endfor %}


Out of the box, Drupal won't do this.  You can do something like this, though:

function MYTHEME_preprocess_page(&$variables) {
  $parts = explode('/', request_path());
  $subhook = __FUNCTION__;

  foreach ($parts as $part) {
    $subhook .= '__' . $part;

    if (function_exists($subhook)) {
      $subhook($variables);
    }
  }
}

This is untested (it may need some tweaking), but it will build up function names based on the request_path().  So, the idea is that if the URL is http://example.com/foo/bar/bar, it will check for

MYTHEHE_preprocess_page__foo()
MYTHEHE_preprocess_page__foo__bar()
MYTHEHE_preprocess_page__foo__bar__baz()

and call each, in sucession, passing in the $variables.

As this will call functions based on user input, you will want to think about some logic to prevent malicious activity, such as only doing it for certain paths, etc.

Just note, that if you are doing this to the admin pages, then you need to do this in the admin theme you have defined for your site, and not the main theme.

I don't normally do this with the preprocess page hooks, but I use something similar for the node ones based on content type and view mode.


How do I add a thumbnail to the teaser of a blog post containing an image?

Go to display settings for your content type ('blog post'), and then select teaser ex.:

/admin/structure/types/manage/article/display/teaser

From here you can control which fields will display in your teaser (or full, or other defined formats). Your image field is most likely hidden for your teaser, you'll want to have it displayed and style accordingly.


How to add a custom attribute to the script tag via drupal_add_js?

It's old but I have the same problem (adding "crossorigin" attribute) and this is my answer :

There is an issue about it here : https://www.drupal.org/project/drupal/issues/1664602
@kenorb solution can't work because "drupal_add_js" add "script" tag automatically.
But... you can try this workaround (a little dirty) :
close the script tag and open yours without closing

.

drupal_add_js('//--><!]]></script><script src="//static.queue-it.net/script/queueconfigloader.min.js" data-queueit-c="MyClientID"><!--//--><![CDATA[//><!--', 'inline');


Migrate two user fields (translation) to translation

Now it works.  There was a problem with the migration of the user admin (user/1). If you migrate admin user, then you can't edit translations of any user.
Now I put a custom source plugin with function query() overwritten:

/**
   * {@inheritdoc}
   */
  public function query() {

    $query = parent::query();

   // Only migrate users not admin (1)
    $query->condition('uid', '1', '<>');
    return $query;
  }


Drupal-7 Where can I change the text from Simplenews unsubscription confirm page?

Sounds as if you need the String Overrides module. From the project page:

  Provides a quick and easy way to replace any text on the site.

This includes messages as well. Here's what you would need to do:

Extract to your sites/all/modules directory.
Enable the module in admin/build/modules.
Configure the access permission in admin/user/permissions.
Visit admin/config/regional/stringoverrides and fill in the strings you'd like to replace. This is the string coming from Simplenews: %user was unsubscribed from the %newsletter mailing list.. Just change it to whatever you would like. You have the %user and %newsletter replacements available.


How to perform action from form opened in modal?

I recently had to do something similar, and I took a good amount of time to understand how Drupal 8 ajax works.
Here are the steps:

Step 1: Ajaxify the link to open the modal, this is easy and you've probably done it already.

$form['ajaxed_link'] = [
  '#type' => 'link',
  '#title' => $this->t('Click to open the modal'),
  '#url' => Url::fromRoute('route_name', ['route_parameters']),
  '#attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => Json::encode([
      'height' => 400,
      'width' => 700
    ]),
  ],

Step 2: Create the form that will open when the #url is called and create a route for it as well. Remember to make the submit button there ajax too, and specify an ajax submit handler using the callback key.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Ajaxed submit button'),
  '#ajax' => [
    'callback' => [$this, 'ajaxSubmit'],
  ]
);

Step 3: Define a function for the callback and make sure it returns an ajax response with the right commands. The first command closes the modal and the second command invokes the click on the desired button (use the correct jquery-selector).

public function ajaxSubmit(array &$form, FormStateInterface $form_state, Request $request) {
  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new InvokeCommand('#jquery-selector', 'click'));
  return $response;
}

Take note that it's a good idea to provide a non-ajax fallback return value from the ajaxSubmit callback for clients where JS is disabled. Do this by setting a form redirect in the regular form submit handler.

public function submitForm(array &$form, FormStateInterface $form_state) {
  ...
  $form_state->setRedirect('route_to_previous_form');
}


Print mailing address labels from a view

Our warehouse team needed the ability to print address labels on the Avery 5163 template for every Commerce Order that is set to the status as Pending

I consider this to be a jury rig more than a Drupalish answer, but it got us through just the same.

Here is how we did it.

We created a page with a table view that shows all orders that are pending.

We created a view of Commerce Profiles that showed only the customer addresses in a grid format.

We used the Printer, e-mail and PDF versions module to create printer friendly versions of the views Here is the module - http://drupal.org/project/print

We altered the print.css file in the modules folder so that the address labels lined up with the template. (Later we ended up adding print.css file in our theme to override the one in the module folder and protect it from updates – Here are the instructions on how to add a style sheet - http://drupal.org/node/171209)

We created an html button in the header of view of pending Commerce Orders. It linked to the print version of the address label view.  (you can add the word print before any relative url to get it’s print view)

We altered the browser settings of the guys at our warehouse to exclude all the extra information that comes when the browser prints – Here are some instructions – http://lifehacker.com/5603815/how-can-i-get-rid-of-the-url-and-other-text-when-i-print-from-web-pages

We also altered the margins in the browser.

We will be looking for a better solution as time and money for work permits , but I thought that someone else might find our experience helpful


You may need to trigger a page refresh from the ajax?  I'm not entirely sure if you would be able to load the individual pane.


How do I make my site "notice" things to index?

Here are a few things you should check:

On the Search settings page (located at admin/config/search/settings), make sure Node is checked (enabled) as an Active Search Module.
On admin/reports/status, verify when your cron job was last executed. And use the link 'run cron manually' on that page to manually trigger the cron job to be run.
Disable the "PHP Filter" module (used for nodes that use the "PHP Code" input format), to not get stuck because of some bad PHP code stored in a node. Because nodes containing PHP can cause problems with search indexing.
Clear the cache.
Check the Drupal log for possible errors related to it.

Some more excerpts from Search module: an internal site search system, related to Re-indexing:

Content-related actions on your site (creating, editing, or deleting content and comments) automatically cause affected content items to be marked for indexing or reindexing at the next cron run. When content is marked for reindexing, the previous content remains in the index until cron runs, at which time it is replaced by the new content.
Unlike content-related actions, actions related to the structure of your site do not cause affected content to be marked for reindexing. Examples of structure-related actions that affect content include deleting or editing taxonomy terms, enabling or disabling modules that add text to content (such as Taxonomy, Comment, and field-providing modules), and modifying the fields or display parameters of your content types. If you take one of these actions and you want to ensure that the search index is updated to reflect your changed site structure, you can mark all content for reindexing by clicking the "Re-index site" button on the Search settings page (administer >> site configuration >> search settings in Drupal 6, or administer >> configuration >> search and metadata >> search settings in Drupal 7).

If none of this helps, then you may also want to look at issue # 1715366 (which started in D7 ...) for other possible causes of your issue.

PS: what happens if you run the cron job, eg by triggering it from the admin screens?


How to handle blog tags in a contrib theme?

To print the the default taxonomy field separate from the other content:

<?php

    hide($content['field_tags']);
    print render($content);

    print render($content['field_tags']);

?>

This will only handle the default "tags" taxonomy. To follow discussion of an easier way to accomplish this, see this issue.


admin/commerce/products/add page says "You have not created any product types yet" when I have

Those admin pages are generally based on the menu, so I think it makes sense that the commerce module is using the menu to build it.

It doesn't have to be like that, though, you can change it up pretty easily:

function MYMODULE_menu_alter(&$items) {
  $items['admin/commerce/products/add']['page callback'] = 'MYMODULE_commerce_product_ui_add_page';
}

function MYMODULE_commerce_product_ui_add_page() {
  $types = commerce_product_types();

  if (count($types) == 1) {
    drupal_goto(_MYMODULE_commerce_product_admin_add_path(key($types)));
  }

  return theme('MYMODULE_product_add_list', array('types' => $types));
}

function _MYMODULE_commerce_product_admin_add_path($type) {
  // Method taken from commerce_product_ui_menu()
  return 'admin/commerce/products/add/' . strtr($type, array('_' => '-'));
}

function MYMODULE_theme() {
  return array(
    'MYMODULE_product_add_list' => array(
      'variables' => array('types' => array()),
    ),
  );
}

function theme_MYMODULE_product_add_list($variables) {
  // Build up an HTML list of links based on $variables['types'], similar to theme_product_add_list()
}


When paging through a block, another block on the page disappears

A couple of things come to mind.

On the block that disappears, does it have an argument that is defined by the URL?
or in your block settings, have you accounted for a wildcard for subsequent pages?


i'm not sure, but i would recommend asking in the DKAN issues found at Github where they actively develop their modules. The DKAN set of modules on github can be found at https://github.com/NuCivic/dkan


Add a Button within the content type overlay window for the url link

The page in your screen shot is a 'node add' page for a particular content type in your drupal site. Therefore the best way to add more elements there is to utilize hook_form_alter()

<?php
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mynodetype_node_form') {
    dsm($form); // This function is available via Devel module. Here, it shows you the contents of $form in a structured manner, so that you know where to make the change to add a button.
    // Add code here to add button in the form etc.
  }
}
?>

The above code snippet assumes your module name is custom and your content type name is mynodetype

To understand what code you need to write to add new form element (in your case a button), refer drupal form api - http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7


Transfering a drupal site from localhost to online and viceversa

the best way will be to use Git to keep you code updated and Features to keep you configuration up to date.

A good free source code hosting for git is BitBucket. It gives you unlimited private repositories but limited users. Github gives you unlimited users but you pay for private repositories.
Anything you change in code can be hosted in one of those code hostings and you can push it from dev (your local) and pull it from your production environment (live).
Git keeps track of all your changes.

  Git is a free and open source distributed version control system
  designed to handle everything from small to very large projects with
  speed and efficiency.

For site configurations you can use Features

  the features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

You can use Features module along with:
Strongarm

  Strongarm gives site builders a way to override the default variable
  values that Drupal core and contributed modules ship with. It is not
  an end user tool, but a developer and site builder tool which provides
  an API and a limited UI.

  An example of such a variable is site_frontpage. In Drupal this
  defaults to node, which ensures that the front page gets content as
  soon as some exists, but for many Drupal sites this setting is simply
  wrong. Strongarm gives the site builder a place in the equation - an
  opportunity to set the site_frontpage to something that makes sense
  for their site.

and Features Extras

  Features Extra provides faux exportables (via Features) of several
  site-building components

This will be a good way to keep your code and your configuration aligned between two environments.

Second option, if you are not familiar with Git, you can just use an FTP software, download or upload files and then use Backup and Migrate

  Back up and restore your Drupal MySQL database and files or migrate a
  site between environments. Backup and Migrate supports gzip, bzip and
  zip compression as well as automatic scheduled backups.

  With Backup and Migrate you can dump some or all of your database
  tables to a file download or save to a file on the server or offsite,
  and to restore from an uploaded or previously saved database dump. You
  can choose which tables and what data to backup and cache data is
  excluded by default.

For your files folder you can use an FTP software.

To synronize nodes, you can use Deployment.

  The Deploy module is designed to allow developers to easily stage
  Drupal content from one site to another. Deploy automatically manages
  dependencies between objects (like node references). It is designed to
  have a rich API which can be easily extended to be used in a variety
  of situations.

Here is the documenentation about the module. Create 2 sandboxes and give a try to it. It also works with features.

For code and configuration sync, I strongly suggest you to use Git and Features.


How can I remove the checkbox from tableselect form header only?

The checkbox on the header is the Check all one. As the documentation about the tableselect form element says, just set the #js_select property to FALSE. In your case, the code would become the following one.

$form['listings'] = array(
  '#type' => 'tableselect',
  '#js_select' => FALSE,
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No Listing available.'),
);

See also the code of theme_tableselect(), the theme function responsible of rendering tableselect elements.

// Add an empty header or a "Select all" checkbox to provide room for the
// checkboxes/radios in the first table column.
if ($element['#js_select']) {

  // Add a "Select all" checkbox.
  drupal_add_js('misc/tableselect.js');
  array_unshift($header, array(
    'class' => array(
      'select-all',
    ),
  ));
}
else {

  // Add an empty header when radio buttons are displayed or a "Select all"
  // checkbox is not desired.
  array_unshift($header, '');
}


Prevent WYSIWYG+CKEditor from stripping html classes

I found a solution.

This turns off the filtering, it's working, but not a good idea...

config.allowedContent = true;

To play with a content string works fine for id, etc, but not for the class and style attributes, because you have () and {} for class and style filtering.

So my bet is for allowing any class in the editor is:

config.extraAllowedContent = '*(*)';

This allows any class and any inline style.

config.extraAllowedContent = '*(*);*{*}';

To allow only class="asdf1" and  class="asdf2" for any tag:

config.extraAllowedContent = '*(asdf1,asdf2)';

(so you have to specify the classnames)

To allow only class="asdf" only for p tag:

config.extraAllowedContent = 'p(asdf)';

To allow id attribute for any tag:

config.extraAllowedContent = '*[id]';

etc etc

To allow style tag (<style type="text/css">...</style>):

config.extraAllowedContent = 'style';

To be a bit more complex:

config.extraAllowedContent = 'span;ul;li;table;td;style;*[id];*(*);*{*}';

Hope it's a better solution...


Importing external resources via REST as nodes or other entities

I haven't looked at that module yet, but pretty much everything that involves the storage of an entity goes through the storage handler of a given entity type.

Drupal 8 provides to real implementations, SqlContentEntityStorage for content entities stored in the database and ConfigEntityStorage for config entities stored in configuration. And a few test and example implementations too.

So the first thing you need to implement is your own storage. Do whatever you want in the relevant methods like load()/save()/delete(), see EntityStorageInterface.

Additionally, you will have to implement a entity query, so you can create lists with conditions, sorts and so on. That also comes from storage (getQuery()), initialized based on a given service name, see for example entity.query.sql and entity.query.config. That's a factory that returns the actual query object and in there, you can again do whatever you want. For content entities, it's transformed to an SQL query while config entity queries are actually mostly implemented in PHP, with some optimizations and lookups.

If you also want to use views, you have to write a backend for that too, since it doesn't use entity query (yet). There's https://www.drupal.org/project/efq_views, not sure how far it is for Drupal 8.


How do I post a node to PayPal after node insert/update?

If you want to send this information and get and nid, the best place to do this is in:

hook_node_insert() to execute this action just after inserting the node and to have a nid.
hook_node_update() to execute this action just after updating the node.


After looking at the drush webform-export code I came up with the following code sample.
It appears to work, however jrockowitz advises me that using drush straight up should be the best solution. I'm sure there's something wrong with the following code. For one, it probably breaks when the export is too large.

$webform_id = 'easykit_vip_formulier';
$webform = \Drupal\webform\Entity\Webform::load($webform_id);
$submission_exporter = \Drupal::service('webform_submission.exporter');
$export_options = $submission_exporter->getDefaultExportOptions();

$export_options['delimiter'] = ';';
$export_options['multiple_delimiter'] = ',';
$export_options['range_type'] = 'date';
$export_options['range_start'] = '2018-02-18';
$export_options['range_end'] = '2018-02-26';

$submission_exporter->setWebform($webform);
$submission_exporter->setExporter($export_options);
$submission_exporter->generate();
$file_path = $submission_exporter->getExportFilePath();

print file_get_contents($file_path);

unlink($file_path);


unable to get webform submissions into our mail

I have disabled all dependent modules for token and then disabled token module also again enabled all modules now working fine.


how to manipulate entity field values in drupal 7 in custom module

My suggestion, now that I understand you're trying to calculate certain values' amounts based on the amount of a different field, would be to use the Rules module.

Then you can accomplish what you need without writing a custom module.  Rules are sometimes a little clunky to create, but the module is really reliable - I use rules for all sorts of things, and once you set it up, it works beautifully.

Here are (roughly) the steps you'd need to take to create a rule that modifies a certain field based on another one.  Adjust as you need to, so it suits your particular needs.

After enabling the module, go to /admin/config/workflow/rules to add a new rule
Set the 'Event' that triggers the rule to be something like 'After updating existing content'.  That will trigger this re-calculation any time the node is updated
Next you'll see that the rule also has 'Conditions' and 'Actions'.  Set the 'Condition' for your rule to be 'Content is of type' and select the content type you want to apply this rule to from the given list.

Finally, let's go onto the actions.  You'll have to do two steps for each of the fields you're modifying 1) First calculate the value from the base_salary field (and store in temporary variable -- that's how it works) and 2) set the appropriate field with the value of this temporary variable.  Here are the 'Action' options that correspond to these

When you're calculating the value for one of the fields, the interface has, by default, a field to select from the top, an operator, and then a text field into which you can enter a number.  If you would rather add/multiply/etc two fields, just change the bottom one to a data selection option with the following button

If your calculation is more complicated than simply adding/subracting/etc two values, just keep selecting the 'Calculate' value action and keep working on the number with multiple chain operations until you're ready and then add the 'Set a data value' at the end.

Hope this helps! I can't do an entire tutorial on using Rules here, as it's a complicated module, but the above should get you started and point you in the right direction. :0)


@Drupality was right...It does require custom coding.
I installed Multi Term Views which will allow nodes to be filtered that contain different, multiple taxonomies from different vocabularies.
So you could have a filtered view at taxonomy/term/27+35 which will show all nodes in term id 27 and 35 or you can have taxonomy/term/27,35 which will show all nodes that are exclusively in both 27 and 35.  After that was set up I just wrote a custom menu and put it in a block in the sidebar.
So I have 3 vocabularies that are Year, Make/Model, and Type.  Make/Model is two terms deep.
Not the best solution - but if a highly customized menu is needed then apparently this is what must be done.

Thanks @Drupality for your help.


hook_form_alter() does not work for the contact form?

This is the array structure of the relevant part of the form.

Using `$form['field_consumer_name']['widget'][0]['value']['#title'] = 'Individual Name'; worked for me.


cannot login after theme change or backup/restore

Try the following:

check the existence of .htaccess file in Drupal root
truncate the cache tables in the database
check and eventually increase the PHP memory limit in /etc/php5/cli/php.ini
Read and check some other trouble shooting ideas at
http://drupal.org/node/158043


How can I have drupal commerce create a sku and adjust prices on the fly?

Try this rule, it will alter the line item's label based on tokens specified when a product type "Product" is added to cart. This is how you can keep it specific to a certain product type. A line item's label is defaulted to the product's SKU.

All of your term-reference attributes will be exposed as tokens. For formatting ideas, check out Commerce AutoSKU which generates product SKUs at product creation (not line item.)

{ "rules_alter_line_item_sku" : {
"LABEL" : "Alter line item label",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"IF" : [
  { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
  { "data_is" : { "data" : [ "commerce-product:type" ], "value" : "product" } }
],
"DO" : [
  { "data_set" : {
      "data" : [ "commerce-line-item:line-item-label" ],
      "value" : "[commerce-product:type]-[commerce-order:uid]"
    }
  }
]
  }
}


How to make the "Height" of Views Slideshow Fully responsive?

I normally take care of the height with javascript.  First I make sure that I am handling the width properly with CSS:

.views-slideshow-cycle-main-frame,
.views-slideshow-cycle-main-frame-row,
.views-slideshow-cycle-main-frame-row img {
  width: 100% !important;
}

Then I create a function that sets the height.  This will take whatever container your slideshow is in as a parameter and find the slideshow within it.

/* Slideshow resize function */
Drupal.theme.prototype.slideshowResizer = function (target){
  var slideheight = 0;
  $(target + ' .views-slideshow-cycle-main-frame-row').each(function(){
    slideheight = $(this).find('.views-slideshow-cycle-main-frame-row-item').innerHeight();
    if(slideheight != 0){
      $(target + ' .views-slideshow-cycle-main-frame').css('height',slideheight+'px');
      $(target + ' .views-slideshow-cycle-main-frame-row').css('height',slideheight+'px');
      return false;
    }
  });
};

And finally I call the function on the window resize event:

Drupal.behaviors.slideshowResize = {
  attach: function (context, settings) {
    $('.your-slideshow-container', context).once('processed', function () {
      Drupal.theme('slideshowResizer', '.your-slideshow-container');
    });

    $(window).resize( function() {
      Drupal.theme('slideshowResizer', '.your-slideshow-container');
    });
  }
};

Also, make sure your base img tag has height: auto;


A simply solution is to use 7 regions for each day and put a view block in each of them.

More flexible is a solution in page preprocess putting the view block in variables:

foreach ( $days as $day ) {
  $variables['view_block_' . $day] = views_embed_view('menu_view', 'block_' . $day);
}

And use the variables in a similar twig loop.

Think about holidays or other special cases, in code you can realize all these things. If it gets more complicated, use contextual filters and arguments as third parameter of views_embed_view().


Within a field template, how can I print the value of another field from the same node?

This is the node object that you have found in the field template.

You can access the field values like this:

{{ element['#object'].field_field1.value }}


The solution to this problem was to un-enable the Devel module, uninstall the Devel module, clear the cache, and rebuild permission, then re-enable the Devel module. Not sure that clearing the cache and rebuilding permissions was necessary, but this solution did allow the Devel module to be enabled and view the permission page.


Custom install profile fails at creating folders

You've setup the Drupal code from the command line and now run the install from UI? Then this is normal if you have different users for the command line and the webserver, which is recommended. Only cheap hosters use one user for both. Drupal is supposed to have write access only for the sites/*/files folder and temporarily for settings.php during installation.

So you need to run this from the command line. Build the folders in a script or install the profile with a console command, which probably works without that you need to change anything in code.

Btw. this is why installing Drupal from the command line is so efficient, you get the permissions right from the start.


When to use a new field on the user account or a custom table and when use user.data service?

The purpose of the UserData API is to allow the storage of certain pieces of information related to a particular user. Its concept is similar to the State API in that the type of information stored is not a configuration that should be exported. In other words, it is specific to the current environment (but belonging to a given user rather than a system or
subsystem).

Users are content entities, who can have fields of various data types. These fields are typically used for structured information pertaining to the user, for example, a first and a last name. However, if you need to store something more irregular, such as user preferences or flag that a given user has done something, the UserData is a good place to do that. This is because the information is either not something structured or is not meant for the users themselves to manage.

In the other hand if you want to be able to export and import your user information in different environments then you should use fields.


In most cases, you just set the cache context directly on the render array you return in your build() method.

I have finally found what my issue was, with the help of @Berdir and @4k4.  If you are using a custom template, such as block--myblock.html.twig and you output the variables individually, such as {{ content.foo }} instead of all at the same time like {{ content }}, it ignores your cache contexts passed directly into your block build array, when logged out.  See What is the correct way to set cache contexts on custom blocks?

So, to answer the original question:

1) Cache contexts passed directly into a custom block plugin are sometimes ignored.  You can test this by altering the SyndicateBlock, and then creating a custom template in your theme block--syndicate.html.php in which you output the variables individually like this:

{% block content %}
  {{ content.foo }}
{% endblock %}

As you change the url arguments, you'll see the block doesn't respect the cache context.

Now if you change it output all the content as a piece, it works:

{% block content %}
  {{ content }}
{% endblock %}

Now, it respects the cache context, and the block is unique per page.

2)  For now, to work around this, you can just output what's in your block in it's own template.

 public function build() {

    $search_form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\SearchForm');
    return [
      '#theme' => 'mycustomtemplate',
      '#search_form' => $search_form,
      '#cache' => ['contexts' => ['url.path', 'url.query_args']]
    ];

  }

This circumvents the block module's esoteric caching exceptions and your form is now unique per page when logged out.

3) Should you create your own theme template to fix this, or just add a method for getCacheContexts() in your custom Block plugin?  It's better to create a new theme template, rather than add a getCacheContexts() method that overrides the natural order of bubbling up of cache contexts, and may break metadata deeper in your build array.


I'm pretty sure you have to override core/modernizr with a later version in order to get objectFit.

Download an updated modernizr.js and include objectFit.
Place the file somewhere in your theme's path (js/ or scripts/)
In your theme's info file (theme-name.info.yml) , override the existing modernizr library

libraries-override:
  core/modernizr:
    js:
      assets/vendor/modernizr/modernizr.min.js: scripts/modernizr.js

You should now have access to objectFit.


In order to expose your field to Views, you need to implement Views API:

http://views-help.doc.logrus.com/help/views/api

This can be made much easier if you implement your field as a proper field, rather than a form alter. The Examples project has some examples, notably Field Permission Example.


How to get real thumbnails (not onthefly scaled down large originals) in grid from media gallery depending on certain tag using views

I worked it out: here's my solution: http://groups.drupal.org/node/183909 credit to Drupal Gardeners Moderator Staff @mstef, @Jeannie.Finks, @Sara.Roy @mongolito404 (on groups.drupal.org/media ) for providing the basis and hints.


Programmatically change view path without views_alter

I managed to find the right way. The following code works great for me.

$view = views_get_view($view_name, TRUE);
$view->display['page']->display_options['path'] = $new_path;
views_save_view($view);


How to create multiple option field for product display?

How the products have no influence on how they are rendered on a product reference field.

What matters is what data the products hold, you need to be able to create unique combinations for all, and setup the reference field to try to do this. The problem you might be facing is that some products are too similar. To reviewing the product data and the products reference in the product reference field.

It's likely that you have created near identical products forcing the user to pick from a list containing all products, instead of have multiple select boxes.


Add Block to Content but set it to appear after the node content?

Go to "Structure >> Block" and drop down your block to the main content.


Well there is Form Block

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Download and install the module.
Navigate to admin/structure/block You can see Registration form as a block there.


I think in this case you should set access to the view directly under page access in the view itself (assuming this is a page view). You would select Access > Role > "member" (and any other role that needs access).

Then users who do not have the role "member" should get a 403, and your custom redirect should work.


Programmatically enable the entity view display

I figured it out. You can enable Layout Builder by running the following code in a custom module:
$entity_type = 'node';
$content_type = 'article';
$view_type = 'default';

\Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay::load("{$entity_type}.{$content_type}.{$view_type}")
  ->enableLayoutBuilder()
  ->setOverridable()
  ->save();

Hopefully this helps someone else. Having to do it via the UI is painful if you have a lot of content types. I'm actually surprised this isn't a Drush command yet. Oh well.
Source: https://www.drupal.org/project/drupal/issues/3158916


How does 'access content' permission string works?

Read: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7

'access content' means 'Node: View published content' on permission list. Check this link for list of permissions provided by node module: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_permission/7
'access content' will be passed as a first argument to user_access() which is default access callback for new menu items. You can change default access callback like this:

function custom_menu_menu(){
  $items = array();
  $items ['status'] = array(
    'title' => 'My Status',
    'menu_name' => 'main_menu'
    'page callback' => 'status_page',
    'access callback' => 'custom_menu_access_callback',
    'access arguments' => array('access content', 'something else'),
  );
  return $items;
}

function custom_menu_access_callback($arg1, $arg2) {
  // arg1: access content
  // arg2: something else
  // if this function returns TRUE user will get access to page callback
  // if this function returns FALSE user won't get access to page callback
}


Move Multi-lingual Content with Migrate Module

You can create two migrations, both with the same mapping (except for the nids), but one saves nodes in English and the second in French.


Export nodes inside Panels by their UUIDs through Features

Try this module https://www.drupal.org/sandbox/danylevskyi/2399993
It will work fine, if you don't have reference fields in your node.


Could be and over lap of composer requests. This example is for Pantheon resipe but it may help https://github.com/lando/lando/issues/340


I won't recommend views_php module. This will hamper performance of the site.

You can use hook_views_query_alter(&$view, &$query) for this. What you have to do is - add field_xyz filter inside view, and override it in hook_views_query_alter(&$view, &$query).


The reason your current code isn't working is because your submit handler doesn't follow the correct naming convention (i.e. FORM_FUNCTION_NAME_submit) and you don't explicitly attach the submit handler to the form anywhere so it's not being run.

You can solve this by simply changing the nameof your submit handler:

function example_form_form1_submit($form, $form_state){

Or you could look at system_settings_form() which automates much of this process for you.


Customizing filter criteria search of a view

use hook_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
if ($form['#id'] == 'views-exposed-form-search-page...'
$form['my_link_element'] = array('#markup' => l(t('Seacrh word taken from form_state'),'node/5'));


Custom language negotiation module not working

I did the configuration with yml file.. try this solution

https://www.drupal.org/node/2775809#comment-11502283

It worked for me.


How can I access/arrange elements in the {{ content }}?

You don't have to use {{ content }} only - this is a variable made up of all the renderable elements in the entity being rendered.

For instance, if you have 4 fields, Field A, Field B, Field C, Field D, you can dictate how/where they are output in the entity template like so, by rendering individually:

  {{ content.field_a }}
  {{ content.field_b }}

{{ content.field_c }}

{{ content.field_d }}

The most common thing most people will encounter in theming will be the theming of fields and entities (like node).

If you wanted the markup within the field, you'd create/edit the appropriate field-- template in your theme and move it there. Lets say you wanted to move the h4 into the Field C template:

field--field-c.html.twig:

{% for item in items %}

{{ item.content }}

{% endfor %}

Now anytime that field is rendered, it is wrapped with an h4 (per value, if it is a multivalue field - check field.html.twig for more info).

Then, back in the node template you remove the h4:

{{ content.field_c }}

The h4 is still in the page, it's just in the field template now. You can break it down any number of ways that is suitable for you.

Let's say you did a mytheme_node_preprocess in your themes mytheme.theme file and created some new variables for the node template. Now that you know how to break down the content variable, you can intersperse custom variables with that:

{{ title }}

{{ content.field_subtitle }}

{{ custom_var }}

{{ content.field_a }}

{{ custom_var_2 }}

{{ content.field_b }}

and so on.

Here is a real example from a project of mine to demonstrate a little further:

node--collection.html.twig

{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
    'hl__full-template__page-content',
    'hl__full-template__page-content--full',
    'hl__collection-details'
  ]
%}

  {{ title_prefix }}{{ title_suffix }}

  {% if node.field_featured_image %}

      {{ content.field_featured_image }}

  {% endif %}

    {{ content.body }}

Accessing These Materials

        {{ content.field_how_to_use }}

      {% if view_records %}

          {{ view_records }}

      {% endif %}

Contact

              {% if node.field_contact_person.target_id %}
                {{ content.field_contact_person }}
              {% else %}
                {% include '@mytheme/misc/freeform--contact.html.twig' %}
              {% endif %}

      {% if node.field_call_to_action.target_id %}
        {{ content.field_call_to_action }}
      {% endif %}

  {% if node.field_related_collections.target_id or node.field_related_how_tos.target_id %}

  {% endif %}

  {% if node.field_related_collections.target_id %}

Related Collections

          {{ content.field_related_collections }}

        {% if node.field_see_all_collections %}

            {{ content.field_see_all_collections }}

        {% endif %}

  {% endif %}

  {% if node.field_related_how_tos.target_id %}

          {{ content.field_related_how_tos }}

  {% endif %}

The more you try things, the more you are going to learn. You cannot do any PHP in Twig templates, which is why that has to be deferred to preprocess functions in the theme file, custom field formatters etc that tell Drupal what to do with the data you are about to output.

edit: the {% if node.field_name.value %} lines are simply checking in the node object that the field has an actual value before we output markup and render the field for it. node and content are two separate things.


Using Site A to authenticate users of Site B?

Have you checked out the Multisite Login module? This allows sharing logins across different domains, and I've had luck with it. They also have a Drupal 7 version available in dev.


Try setting up a new Relationship within the View.

Add a new relationship to "The node the comment is a reply to."
Check box that "requires this relationship"
You should now be able to add a new field for the node title


Help with a D7 database query and update

Something like this should work, but I have not tested this code. Please comment on this if you have questions.

$result = db_select('menu_links', 'ml')
  ->fields('ml', 'mlid')
  ->condition('ml.plid', $plid, '=')
  ->orderBy('ml.link_title')
  ->execute();

$i=0;
foreach ($result as $row) {
  db_update('menu_links')
    ->fields(array('weight' => $i))
    ->condition('mlid', $row->mlid)
    ->execute();
  $i++;
}

At this point they would all be ordered by title, and you could print the menu wherever needed.


No HREF on Content menu on admin toolbar

I found the answer to my original problem.

I went through the .info file and commented out JS files until the console no longer reported a mutation event.  Turns out that there was some odd JS code:

jQuery( "li:nth-of-type(2) > a" ).removeAttr("href");

The selector is too vague. Guess what number the LI containing the Content menu is?  It's 2! And this little bit o'code took the HREF right off!

Thanks to @Clive for suggesting mutation observers.  Learned a lot from this bug.


I'd try to create a rule that's fired when new content is added and when a user is subscribed to it (check this with a condition). Use the 'Send email' action to send an email to the subscribed users.


Dropdown whose options are dependent on a choice made in a previous dropdown

Maybe you should consider using thee Reference field option limit module to implement what you're trying to do. Here is a quote from its project page:

... allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

Here is an example of how to use this module (also from its project page):

Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.


Add a select list to the content of the view

Please read post Programmatically Creating Forms with Views in Drupal 7 which is very close to your requirement.


Custom field in order not shown on checkout panel

There is no code that shows custom order fields at checkout. You will need to write a custom checkout pane plugin.


Update cart on checkout page with tax rule

There is no way right now to show the update without custom code, though it could be done by adding AJAX functionality to the form like the shipping module does. You can see how it updates shipping rates when address data is entered, and if I'm not mistaken it even provides a hook for you to add additional AJAX commands to the response. You should be able to update the order at that time and update the cart contents checkout pane display, too.


I would recommend starting with Drupal Commons as a base. It comes with a lot of prebuilt configuration that's very nice, like the fb-style walls for groups and for users. You get all the standard things you mentioned except for forums, but that comes with Drupal core, or you could go for a more advanced solution. You can disable any features you don't want in a per group basis. Commons already comes with a nodes as profiles solutions, so you just need to add the fields you want to the profile node. For chats you will also need an additional module, there are several, maybe this will help get started.

To answer your question more directly, yes Drupal Commons is right for you. It will save you a lot of configuration time, and you can see some best practices in configuration from what they did. Remember to back up your db often and don't be afraid to modify everything to suit your needs, you will learn a lot that way. As long as you have a a backup you can always revert.


How to align three blocks on the front page using CSS

Well, after looking at your code I concluded that your css codes are terrible! you may use this code (I didn't test it but it should work or at least a few modifications will make it to perfectly match what you need):

                    //In here load the slider block and display in here

                    //In here load the top right  block and display in here

                     //In here load the bottom right  block and display in here

This is CSS

#content{
       text-align:center;
       width:100%;
       height:auto;
       display:inline-block;
}
#blocks-container{
       margin:auto;
       width: 975px;
       height:auto;
       display:inline-block;
}
#left-block{
       float:left;
       width: 760px;
}
#right-block{
       float:right;
       width: 215px;
}
#right-block > div{
       clear:both;
       width: 100%;
      float:left;
}

Never use margin to align elements to the right, because the margin is calculated based on the parent which in your case is the browser, so If you resize the browser, the browser will try to move the elements to regard the margin.

I recommend you strongly to forget about the DIV and float, try to learn how to work with flexbox it is very easy to use.


No response from Services Entity API when added '.json' to the end of alias

Okey,

You shouldn't add the suffixes like .json or .xml to the end of the alias name like you do with some other resources if the resources are provided by services_entity module. Adding the suffix directly to end of the whole url solved it.

example.com/endpoint/resource_alias/resource_id.json ie:
example.com/api/entity_node/5.json


How to access entity from EntityReferenceItem?

If entity in the foreach loop is not empty you should be able to do

$entity->field_name->entity
//or perhaps
$entity->field_name->referencedEntities();


How to override jquery update preprocess page

JSAlter module for D6 should solve your problem..

Project page says

  This module will not be ported to Drupal 7, because Drupal 7 core
  natively includes a hook_js_alter(). Note that the signature and when
  the hook is invoked is slightly different in Drupal 7 core than it is
  in this module.

  This module adds a hook_js_alter() hook that other modules can use to
  modify the javascript that gets output to the page. The module
  provides no end-user functionality, but other modules can use this
  module as a dependency. Check out the JS Registry, JS Debug Helper,
  and jQuery Form Update modules for examples.


Organic Groups: Error, The website encountered an unexpected error.

Clearing the caches worked for me with a "drush cc all".


The correct way to include jquery in a module's form

You should not have to manually include jQuery:

"When JavaScript is added to a page through Drupal, jQuery is automatically added to the page."

-- https://www.drupal.org/node/171213


Did the purchase-module create and implement the entire purchase node type or did you create that in the admin system?

If you created it in the admin-system you can't use those functions. They are for node type modules (a rarer and rarer kind of module use these days).

You probably want hook_nodeapi. It's a common misconception.
http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_nodeapi/6

function hook_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'update':
      if($node->type == 'purchase') {
        echo 'Updating';
        exit(0);
      }
    break;
  }
}


Content type with Multiple fields reference

The simpliest way to do what you like is to use ief module. But i dont sure it works with node reference field type. So you will need to use entity reference as a generic entity reference field.


node-edit-protection module not working in CK Editor window

Open node-edit-protection.js file in module's folder,
Find this code

window.onbeforeunload = function() {
     if (edit && !click) {
     click = false;
            return (Drupal.t("You will lose all unsaved work."));
     }
}

replace above code with following

    window.onbeforeunload = function() {
    if (typeof(Drupal.settings.ckeditor) != 'undefined' && typeof(CKEDITOR) != 'undefined' && typeof(CKEDITOR.instances) != 'undefined') {
         for (var i in CKEDITOR.instances) {
          if (CKEDITOR.instances[i].checkDirty()) {
           edit = true;
           break;
          }
         }
        }

         if (edit && !click) {
          click = false;
          return (Drupal.t("You will lose all unsaved work."));
  }
}


Can I limit a view mode to show on the "Manage Display" settings page for only one node type?

No, view modes are per entity type, not per bundle.


Add view with contextual filter to XML sitemap

There is an XML Sitemap Custom submodule in the XML Sitemap module

You can use this to set Page Views' paths for inclusion in the XML Sitemap

You might also check this module out: https://www.drupal.org/project/xmlsitemap_aliases
From the project page:
"Anything with a path in the aliases table can now be included in your XMLsitemap by the click of a button! (This is particularly useful when you have too many to enter manually as custom links, for example: views with arguments!)"


Using the Date API module (part of the Date module), you can do something like this...

<?php
$form['payment_expirationDate'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiration Date:'),
    '#date_format' => 'm', OR  '#date_format' => 'y',
    '#default_value' => $expirationDate,
    '#date_year_range' => '-1:+10',
    '#required' => TRUE,
    '#date_label_position' => 'within'
 );
?>

The date_select type will give you select box form elements for your field. And the #date_format array key allows you to use a PHP date format string to control what select boxes appear and what goes inside them.

Reference


How to fix this error in drupal: ajax: ajax.form.ajaxSubmit is not a function

You'll need to include the Drupal ajax drupal_add_library('system', 'drupal.ajax');


Have you actually tried to visit /taxonomyname/taxonomyterm?

The /taxonomy/term/123 isn't actually a taxonomy page, it is a Views showing content tagged with the term from the URL. It's a separate thing.

What do you expect to see on that page? Just the term name and description? That should work with the Pathauto as you have set it up.

If you want to see the content, like that Views page, you can use the Taxonomy term Views, Duplicate it and disable the original just for future reference, and modify the Contextual filters and Path to your preference.

You will need to add the Relationship to the term so you could use the Taxonomy: Name Contextual filter to get the term name in the URL.

You can also set up aliases for the default Taxonomy term Views so they use names, but I think it would have to be done manually, and isn't at all elegant/smart solution. It make more sense to set up the Views as you intend it to be used.


What you can do is you can create a small table which keeps your order id, user id and anything else you want. Whenever the order is saved you can check whether a record exists for the particular order id. If there is no you add the record otherwise you don't change the current record.
For that you can use hook_commerce_order_presave(). Inside this hook you can use your code l

option 1

function yourmodule_commerce_order_presave($order){
    if(!db_result(db_query('SELECT * FROM {your_table} WHERE orderid = %d', $order->id)))
        $user = $GLOBALS['user'];
        if ($user->uid) {
            $form['field_order_created_by'][LANGUAGE_NONE][0]['target_id']['#default_value'] =       $user->name;

        //add new record to yuor table
    }

}

option 2

function yourmodule_commerce_order_presave($order){
    if(!check_record_exists($order->id))
        $user = $GLOBALS['user'];
        if ($user->uid) {
        $form['field_order_created_by'][LANGUAGE_NONE][0]['target_id']['#default_value'] =       $user->name;
    //add new record to your table
}

function check_record_exists($oid){
    $exists = db_result(db_query('SELECT * FROM {your_table} WHERE orderid = %d', $oid));
}


Information added by Drupal.org on Distribution

Whoever is getting the same error it is probably you got some patches and themes that are not from Drupal.org

The 2 links below helped me see what my problem was:

https://www.drupal.org/docs/develop/packaging-a-distribution/how-to-package-a-distribution-on-drupalorg

https://www.drupal.org/docs/develop/packaging-a-distribution/drupalorg-distribution-packaging-requirements


Here is a simple setup:

You need two content types:

Gallery
Image

The gallery content type will contain a body (gallery description) field.

The image content type will contain:

Image field
A reference field

The reference field will reference a gallery content type.


Add review content type form while viewing book content type is viewed by using hook_nodeapi().

Create one field on review content type(node reference of book node).
Add that node_form in book content type view with $form_state of the book node id.
Create a view for review list with a filter of book content type and use this block under book content type view.


Post to anonymous user's Facebook Wall with rules

You didn't say what have you tried, so how can we know if we're suggesting some new solution? Anyway you could try Facebook Autopost https://www.drupal.org/project/fb_autopost if it isn't on you personal "All solutions I came across" list


adding media content to a Drupal Commons Group page header?

I solved it by enabling the Media component and then adding its widget in the CKEditor configuration.


Can anyone give me an example of a seperator used in table style in views

Dunno about drupal 7 but in in 6 youd go to your View, then View Style, select table, click on the wee wheel for options,  and then select which coloum you want your fields in.


How should I file an issue on drupal.org that affects multiple modules?

Personally, I would pick the one with the highest level (or least mature), and post in that issue queue.  By highest level, I mean the one closest to the user, the one with the modules dependent on it, etc.  In your case, I think logintoboggan would be most appropriate.

Then in the issue, explain the situation in detail and mention the other modules.

If the project owner thinks a lower level module is the culprit, then they will decide what to do.  More than likely, they will post a comment, and reassign to a new queue.

I would not post the issue in multiple queues, though.  It makes tracking things too hard.


Can I use Apache 2.2.15 with mod_rewrite enabled?

Yes, you can go with Apache 2.2.15 as long as you have mod_rewrite enabled (so you'll have pretty urls).

From Drupal issue Regression fix: allow Drupal 8 to work without Apache mod_rewrite

  Apache 2.2.16 is only required if mod_rewrite is NOT enabled


For Ubuntu

export PATH="$HOME/.composer/vendor/bin:$PATH"
source $HOME/.bashrc
composer global require drush/drush:8.x


View based on months or days - display certain items during specified times of the year

Here's an idea for something you could do in the Drupal admin UI (using only modules that are part of Drupal 8 core) since it seems you don't have access to the codebase.
As you noted, the date field requires a year.  So you can't use it if you want your months to be year-agnostic.
I assume that your requirement is "each node should be assigned to one or more months" and we don't have to worry about days (for example, a node could be "January and February", but it could not be "Jan 12 - Feb 10").
In that case, you can add a field of type List (Text) to the node content type that you want to sort in Views.  For the value of the field, enter the 12 months and allow multiple values so that multiple months can be selected.
Then, you can configure the view to filter based on your month field.  To set the current month, I'm pretty sure you can use Twig date in a Views filter to input the current month (not tested, from memory).


How to compare two fields for filter criteria in view

With latest views in 7 you have under global filters, "field comparison" filter that you can select any 2 fields which you added into fields of that view (they can be hidden fields) and that is it. Image below shows how this looks:


Export custom module strings for translation

You can give Translation template extractor a spin. While there is no official release for Drupal 8 available (yet), there already is a development version that seems to work for your use case when using the GUI:

https://www.drupal.org/project/potx/releases

Using composer, just install it like

composer require drupal/potx

After enabling the module, you'll have a new menu entry Configuration > Regional and language > User interface translation > Extract (/admin/config/regional/translate/extract)

There you can extract language and module specific translation templates from your custom module's PHP files.

Disclaimer: As mentioned, this module's Drupal 8 version has not been released yet. It may contain bugs and is not feature complete/en par with the 7.x version. Better use it in your development environment only.


Deletion of some watchdog messages with subquery

You were close; this should work for you:

$subquery = db_select('watchdog', 'w')
  ->fields('w', array('wid'))
  ->condition('type', 'blabla')
  ->range(0, 250)
  ->execute()
  ->fetchCol('wid');

// Deletes the previous selected values.
db_delete('watchdog')
  ->condition('wid', $subquery, 'IN')
  ->execute();

You weren't executing the subquery (meaning there were no results), and you mixed up the order of arguments passed to query condition.


I hope, Drupal 7 main-menu - change item text if user logged in you check this first.

If this does not complete your requirement, then, u have to override the theme_menu_link hook.

http://api.drupal.org/api/drupal/includes!menu.inc/function/theme_menu_link/7

You can check whether the user is logged in or not by checking boolean $logged_in. If it is true, user is logged in else not.


Your Option 1 and Option 2 seem to both implement "answers" as comments...

Another option (= Option 3) would be to implement Answers as another content type, combined with an entity reference field (multiple values allowed) added to your Questions content type.

By using a content type for both Questions and Answers, it would probaby simplify anything about voting (either Question or Answers), and you could also use the Flag module (e.g. to mark "an" answer as the "accepted" answer).

At this time it's too early (= not ready for D8 yet) for some typical other modules that could be added to this later on:

the Rules module, to implement whatever logic you'd want (eg: only question authors can flag one, and only one. answer with the fag to mark an answer as accepted.
the Userpoints module, to implement your reputation system.

PS: you probaby have a good reason why it has to be implemented in D8, but if D7 would be "good enough" (at least for now), you could implement something similar to this Option 3 by using what is explained in this answer to "How to implement a reputation based system with badges in Drupal similar to StackExchange sites?".


How do I include taxo description in a View's no argument summary?

Hmm. Interesting that no one replied to this. I would have thought this was a common need.

Turns out the answer was not a plugin but another display. Using the Views Group By module (https://drupal.org/project/views_groupby - thanks Phase2!) I created a page with the summary links but also including the taxo description. Made the links bring up the other display, and all is well.


Entity form with pre-populated entity reference from URL

The prepopulate module is now able to handle this in the usual way like

http://www.example.com/node/add/child?edit[field_parent_ref]=17


How to create a page with all the nodes of a specific user?

Nope, that's totally fine. What you are looking for is the power of Views' built-in contextual filters. With that you can pass arguments from an URL to a view.

  The classic example of how contextual filter values are provided to
  views is by the view path. If a view has the path example.com/my-view,
  the URL example.com/my-view/story/22 will call the view along with two
  values for contextual filters (in this case story and 22). But there
  are more ways of providing contextual filter values.

Just a rough outline so you can get the idea:

Build a Views page with a path that contains a wildcard. Let's say it's usersnodes/%
Build the "more" link on the user's profile page then to dynamically hold the user's uid. So that would be usersnodes/123 for example.
In the view you created in step one now set the contextual filter (I think it's on the very right in the UI). There you have to possibility to grab an argument (or two, or three ...) from the URL and pass it as a contextual filter to the view to only get the nodes of the user whose uid was in the URL.


Custom redirect after "admin create user"

Try to use Login Destination module. This may solve your query.

Or you can do this by using Rules module.


How do you change the order of uploaded videos?

The listed videos are created using a view. It looks like the view is called Resources (or something similiar). Edit that view, and there should be a tab called 'block', where you can edit the block view. In there, under 'sort', choose 'nid' and set it to sort descending.


unable to create new draft programatically for published node

I've not tested or checked against the source code but I think you should try to node_load after node_save and before workbench_moderation_moderate.

node_save($node);
$saved_node = node_load($node->nid);
workbench_moderation_moderate($saved_node, 'published');


This is definitely possible (and preferable). There are a few ways to do this, but I think the preferred approach is to first specify your form in your routing entry (mymodule.routing.yml)

mymodule.some.route:
  path: '/foo/bar'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
    _title: 'My form title'

The routing system will automatically build your form for you. The class \Drupal\mymodule\Form\MyForm should implement FormInterface. An easy starting point is to extend \Drupal\Core\Form\FormBase.

There are several examples of this in core. For instance, the entity.user.admin and user.admin_permissions routes in users.routing.yml.


Take a look under admin/structure/block and check if there's a block that's set to show in your Content region.


Sounds like you're looking for String Overrides.  It will work with any string that is handled in the proper manner (ie, it is run through t()), not just messages.


Any way to add an associated url redirect to a content view?

Set that variable in the user's $_SESSION and then when an order gets created, check to see if that $_SESSION variable is there when you save a new order and if it is, write it to $order->data.

Alternatively, you can check out Commerce Affiliate which allows you to set up affiliates and provides some extra conditions and actions that you can use. This includes grabbing URL params and storing them on the session.


Adapting a superfish menu to what I want

If you need the menu to render to the full width of the screen make sure the containers the menu is in doesn't have any set widths, and then set the main ul to a 100% width. Superfish comes with a lot of default styles that can be hard to override. If you use the Drupal Superfish module, configure your Superfish block and set the 'Style' to none, and make sure drop-shadow is ticked off. If you don't use the module you can do this when you call Superfish with drupal_add_js (or in your init.js).


how to access custom function in twig template file

Depending on the nature of your function, maybe but probably not.

As Clive pointed out, you can use certain functions in Twig. These functions however are mostly variable filters (formatters) for last minute alterations on variables. These can be used to translate, link, or in any way alter a provided variable. These functions are a combination of those provided by twig and some additions by Drupal. You can register your own Twig function, by extending on the TwigExtension class (example).

However most functions will probably be for adding additional data to the template and not to alter existing data. Instead you should place your custom function in a preprocessor and define a variable there. Then display this variable in the template.

Custom preprocessor (replace my_theme with your theme or custom module name):

function my_theme_preprocess_node(&$variables) {
  $variables['my_variable'] = 'value';
}

Twig:

{{ my_variable }}

Here is some reading on twig best practices: Twig best practices.

Some example code on preprocessors is here: template_preprocess_node(). Which is in fact systems invocation of hook_preprocess_HOOK().


How to Set Hidden Form Field Values Permanently via Form Alter

Ok webforms are a bit tricky ... but this will work i don't really care to set hidden fields just set the data direct to the entity.

if this is not a multy step form you could probably ad another submit handler in your form alter aka ...

function MODULE_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if ($form_id === FORM_ID) {
     $submit[] = 'MODULE_form_alter_submit';
  }
}
// then
function MODULE_form_alter_submit(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
     // get the data you need.. via this ..
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    $prog = getLeadProgramContact($previousUrl);
    // or ($_GET) or session or cookie whatever you chose.. Then set    it

    // GET the form Object.
    $webform_submission_object = $form_state->getFormObject();
    // GET the submission object.
    $webform_submission = $webform_submission_object->getEntity();
    // Optioanl default values if need to play with them ..
    $orig_data = $webform_submission->getOriginalData();
    // set form state
    $form_state->setValue('referrer', $prog->...);
    // set submission field value.
    $webform_submission->setElementData('referrer', $value);

    $form_state->setValue('program_name', $prog->...);
    $webform_submission->setElementData('program_name', $value);
    // Save it so it cant go away.
    $webform_submission->save();

  }
 }
}


Sorta embarrassing, but adding the solution to my problem, just in case anyone else runs into this. If you configure the date field in the content type. There is a drop down of time zone handling. Ours got set incorrectly somewhere down the line. After fixing that, and rerunning the migration everything worked as intended.


How to allow the banner to be editable via front end?

You have two ways without coding:

Use Nodeblock to create nodes for banners. Give users right to edit nodes and place them where you need them as a blocks.
Use Views to create a block displaying (random?) node of content type banner. Give your users right to create, delete and edit them.

You could also use Advertisement module, but for a simple case like this it's an overkill, I think.


Use skip_on_value plugin in Migrate Plus module.

Sample code:

id: custom_menu
label: Menu
migration_group: custom
migration_tags:
  - Drupal 7
source:
  plugin: menu
process:
  id:
    -
      plugin: skip_on_value
      equals: true
      source: menu_name
      method: row
      value:
        - devel
        - features
    -
      plugin: static_map
      bypass: true
      source: menu_name
      map:
        main-menu: main
        management: admin
        navigation: tools
        user-menu: account
  label: title
  description: description
destination:
  plugin: entity:menu


Drupal 7 page template for right to left languages e.g. page--rtl.tpl.php

In Drupal 7, what you'll want to do is something along these lines:

function THEMENAME_preprocess_page(&$variables) {
  if($variables['language']->language == 'ar') {
     $variables['theme_hook_suggestions'][] = 'page__ar';
  }
}

which will cause Drupal to look for a page--ar.tpl.php file (or even a THEMENAME__page__ar() function, which is the reason for the underscores in the variable value btw) when $language is set to ar.

A possible enhancement:

function THEMENAME_preprocess_page(&$variables) {
  if(isset($variables['language'])) {
     $variables['theme_hook_suggestions'][] = 'page__' . $variables['language']->language;
  }
}

will cause Drupal to look for page--XX.tpl.php files and will use them if they exist; otherwise, will just keep looking for a less specific template and will end up using page.tpl.php.  This way, you don't have to have a lot if's in your preprocess logic.

For that matter, you can also do something like this:

function THEMENAME_preprocess_page(&$variables) {
  if(isset($variables['language']) && $variables['language']->dir=='rtl') {
     $variables['theme_hook_suggestions'][] = 'page__rtl';
  }
}

and now you would have one page--rtl.tpl.php file for all rtl languages.

Lots of possibilities abound here, a quick:

drupal_set_message('<pre>' . print_r($variables['language'], TRUE) . '</pre>');

in the beginning of your preprocess function will show you what you have to work with.


Deprecated code cleanup: Updating EntityManager to EntityFieldManagerInterface

EntityFieldManager has no shortcut in \Drupal, so you need to get it through \Drupal::service():

$fields = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($entity_type);


The "files" directory of your installation (usually located at sites/default/files) must be writable by user the execute the server (Apache, for example).

So, if you have access to a console could try:

sudo chown -R www-data:www-data sites/default/files (for Ubuntu or Debian)
sudo chown -R apache:apache sites/default/files (for Centos or Redhat)


How do I translate hard coded words in twig file

{{ myword }} is a variable, not a string. You need to use {{ 'myword'|t }} (with quotes)


Is it good practice to style the panel layout?

It's perfectly acceptable to add CSS ids and classes to panel layouts.


How to get attachments out of a twig file

Usually ajax commands which add html are able to catch attachments bubbling up when they render the content. Don't know EmbedInsertCommand(). The name clearly says it is an command inserting html, so it should be able to do it.

For commands not able to handle attachments you can render the content already in the controller and add the attachments to the response here:

  $response = new AjaxResponse();
  $html = \Drupal::service('renderer')->renderRoot($build);
  $response->addCommand(new EmbedInsertCommand($html));
  $response->setAttachments($build['#attached']);
  return $response;

This is only a workaround, not the recommend way, because Ajax does some more processing of the attachments before adding them to the response, but for a single command this should be OK.


Hi what you can do is that create a content pane from a view display and configure it in the following screen shot listed below.

Next in the fields section you can add the image field and other fields as per you like.

 ![Add fields accordingly][2]

Also you can clone the view that comes default with OG.

OG:CONTENT(clone this view and add fields)

Hope this helps. :)

Edit:- For displaying images

I havent done anything like this before. But I think you can do this by "rewriting" the result of the url field.

You can do this by clicking the field with the url that you will find under "FIELDS" in your view settings. Then under "Rewrite Results" you can write something like

<img src="[image_url]" />

here, 'image_url' must be the name of the field. you can verify this in the list displayed under "Replacement Patterns"

Hope this helps. :)


Got it.

In your hook within your theme file:

  $status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
  if ($status && $status->getStatusCode() == 404) {
    $page['#attached']['library'][] = 'themename/notfound';
  }


Computed field - count number of taxonomy terms in term reference field

Your first code was correct as far as it went: count($entity->field_termref) will return a count of one because the array has only one item, the list of terms.

To count the members of the list your will need to drop down into the array to actually count the list:

$entity_field[0]['value'] = count($entity->field_termref[LANGUAGE_NONE]);

The members of the list can then be counted:

$entity->field_termref[LANGUAGE_NONE][0]
$entity->field_termref[LANGUAGE_NONE][1]
$entity->field_termref[LANGUAGE_NONE][2]
...etc


How do I pass dynamic parameters to a service?

Giuseppe, I recommend defining your service using the Factory design pattern. You can then instance the factory and call a copy of your business logic class, initialized with the nid. I believe that this pattern is what @kiamlaluno was hinting at in his comment about using DatabaseBackendFactory.
Factory injection example
A simple and common example of this pattern would be getting an instance of a storage controller from the EntityTypeManager.
In your .services.yml file:
example_service:
  class: Drupal\my_module\MyExampleClass
  arguments: ['@entity_type.manager']

In your service class:
<?php

use Drupal\Core\Entity\EntityTypeManagerInterface;

class MyExampleClass {

  /**
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $termStorage;

  /**
   * @inheritDoc
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->termStorage = $entity_type_manager->getStorage('taxonomy_term');
  }
}

In the example above, the EntityTypeManager, which acts as a factory, has been injected, and then we call the getStorage() method to get an instance of \Drupal\Core\Entity\EntityStorageInterface that has been initialized for the taxonomy_term entity type.
Similarly, you could define a service that is, itself, a factory, and the factory would then be responsible for creating instances of your business logic class.
You could inject your factory service, as in the example above, by replacing the EntityTypeManager service with your own. You can also create an instance in a hook, like this:
my_module_node_view($node, $view_mode, $langcode) {
  // Get instance of your factory service.
  $my_service = \Drupal::service('my_service');
  // Get an instance of your business logic class from the factory,
  // initialized to use the nid that we provided from $node->id().
  $node_processor = $my_service->get($node->id());
  // Make the call to process the nid.
  $node_process->doBusinessLogic();
}

Plugins
It might also be helpful to know about Drupal 8's plugin system. Drupal 8's plugin system is essentially a specialized version of the factory pattern. If you have Drupal Console, then generating new Annotation plugins is easy. Depending on all of the requirements of your project, a custom plugin type might be exactly what you need.
Here are some tutorials and references on plugins that I have found to be useful:

https://robvarkonyi.com/blog/ultimate-guide-drupal-8/plugin-system-drupal-8
https://www.drupal.org/docs/drupal-apis/plugin-api
https://www.sitepoint.com/tutorial-on-using-drupal-8-plugin-derivatives-effectively/
https://drupalize.me/tutorial/what-are-plugins (requires subscription)


Aggregated CSS/JS file names, when regenerated?

You're looking for drupal_build_css_cache & drupal_build_js_cache. The building happens when the file doesn't exist or when the combination of files used in the aggregate is different than before.

Looking at drupal_clear_css_cache & drupal_clear_js_cache the variable gets removed & any file older than 30 days gets deleted. By removing the variable, drupal will then check to see if the contents of the file has changed, if yes a new aggregate will be built. So the file name is built by using a hash of the files content and the quick lookup is built by a hash of the file names used.

If you want something that's a little smarter than core, doesn't cause a stamped of writes to the variables table on a cache clear, and keeps files around based upon usage instead of a 30 day window give Advanced CSS/JS Aggregation a try.


As far as I'm concerned there are three ways you can achieve this:

You can use the Drupal UI /admin/reports/updates
You can use Drush drush ups
You can use a Third Party Service Drupal Status.

I wrote an article that explains how to integrate multiple Drupal website with Drupal Status.


A flag that is created with the Flag module is indeed a boolean variable (it is "on" of "off"). In this specific case you should implement 3 possible values, i.e.:

Participant
Maybe
No

Here is how you can get that implement by using 3 flags:

Flag 1, with something like these "Link text" values:

(to Flag) = Yes I plan to participate.
(to Unflag) = Please ignore my "Yes I plan to participate" from before.

Flag 2, with something like these "Link text" values:

(to Flag) = I'm not sure yet if I'll participate.
(to Unflag) = Please ignore my "I'm not sure yet if I'll participate" from before.

Flag 3, with something like these "Link text" values:

(to Flag) = No I will not participate.
(to Unflag) = Please ignore my "No I will not participate" from before.

If it fits your requirement, you could "assume" that for somebody who did  NOT set Flag1 and did not set Flag 2, the default applies which is something like "user does not want to participate, or didn't bother to let us know about it". That will avoid you need Flag 3.

If you're not familiar enough with the Flag module yet, I strongly recommend watching the set of 8 video tutorials about this module.

For more details, you may also want to refer to my answer to the question about Display unique text and button in nodes in a view in drupal 7. It contains the details about using the Entity Reference module for this, in combination with the Flag module, and possibly also the Rules module.


How to get referring items from a Entityreference field in the opposing item list? (back reference)

At the moment I only see 2 (edit: 3) options to solve the backreferencing issue without creating SQL request duplicates:

Using Views Field View for nesting a list of type A nodes referencing node type B via contextual filters in the second view to filter for each items nid (possible performance issue).
Syncing 2 Entityreference fields from both content types and maybe automate them with Rules and using the second Entityreference field for the back reference list in Views.
Using the CER module (I know you said no but), I think after testing that this module is the best option at the moment if you know that you want this connection synced "fix" and not individually changed.

First would have a huge performance impact if the lists and nested lists are long. And the caching modules required to compensate it are not ready yet for D8.

Second can have other issues sinces Rules not always work flawlessly and I am not 100% sure if Rules supports the needed triggers for this approach.

EDIT: Third is my recommendation. After testing around I was quite impressed about its simpleness and working warranty. It's not as flexible as using rules, but as I sad, rules is a story of ots own. So maybe you give it another try (CER).


How to print a custom user field in comment.tpl.php?

I've got it working! I've used user_load($comment->uid) to load the author relationship.

I placed the code in a copy of comment.tpl.php in my sub theme.

<?php print render(field_view_field('user',user_load($comment->uid), 'YOUR-CUSTOM-USER-FIELD'));?>

Cheers and good luck!


Yes, this is possible with hook_ENTITY_TYPE_presave

/**
 * Auto check checkbox whatever, etc, etc.
 *
 * Implements hook_ENTITY_TYPE_presave()
 */
function my_module_node_presave($entity) {
  if ($entity->bundle() == 'team') {
    // Check if there is content in the body field.
    if (!empty($entity->body->value)) {
      // Set checkbox field.
      $entity->set('my_checkbox_field', 1);
    }
  }
}

Then, you'll probably want to remove the checkbox field from your form display on the Manage Form Display screen and also update the field settings so it's not checked by default since you'll be programmatically checking it if your body field has a value.


If you are using drupal6(you haven't specified) then try the AdvancedBookBlocks module. It is built on the ideas of the jquery menu module and could help you.

If you are on drupal7 there is a port of the drupal 6 module though still a sandbox project. I have tried it out and it works. You can find it here


Escape of Upscaling image in Scale and Crop option

A separate scale image effect followed by a separate crop image effect won't give you what you want.
Imagecache Actions does not offer a single image effect that does what you want.

However, what you could do is use the aspect switcher image effect of imagecache_actions:

aspect switcher:

if portrait: scale to 110x(empty) (no upscaling)
if landscape: scale to (empty)x110 (no upscaling)

crop to 110x110


How to remove "leave blank for all" message from Views exposed filter

There is a problem with view 3.13. It happened due to this commit https://www.drupal.org/node/339384#comment-10548388.

Stated as:

  Issue #339384 by colan: Added help text to keep the exposed filter
  terms list unset to keep unfiltered "Any" option default.

Apply this patch or revert your view back to version 3.11.


If possible, it might be beneficial to create a separate Date field for your content type. I often find that if I need to do custom filtering in a view, filtering by the date field instead of node post date is much easier. Being able to collect different granularity such as day and month can be helpful also.


How do I retrieve values from a webform?

Try this:

$ticket = array(
  'description' => $form_state['values']['submitted']['description'],
  'subject' => $form_state['values']['submitted']['subject'],
);


how to have conditional required fields through hook_form_alter?

In Drupal 7, I would use the following code.

/*
 * Implements hook_form_alter().
 */
function test_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'your_form_id':
      $lang = $form['name_field']['#language'];//get field language
      if(isset($form_state['values']['field_draft'][$lang][0]['value'])){
        $form['name_field'][$lang][0]['value']['#required'] = FALSE;
      }
      break;
  }
}

Note: Never use und try to get the language for multilingual sites. If site is not multilingual, then best to use the constant LANGUAGE_NONE and not the string 'und'.


About the template for poll recent block in drupal 7

block--poll--recent.tpl.php will work if you clear your system cache (configuration > development > performance > clear all caches).

Worked for me.

See complete template suggestion list for Drupal 7 here : http://drupal.org/node/1089656


Programatically speaking, if a View is involved in a template, the module injects the $view object into the available variables. So you can get to it pretty easily:

function MYMODULE_preprocess_node(&$vars) {
  if (isset($vars['view']) && $vars['view'] instanceof view) {
    if ($view->name == 'foo') {
      // ...
    }
  }
}

From a UI perspective, enabling the Contextual Links module might be a good solution to your problem. That will add direct edit/delete/etc links to nodes/blocks/views, and others depending on the contrib modules you have installed).

You can browse the site and simply click the edit link on a view to be taken to the edit page, where you can find out everything you need to know. Same for content, assuming it's been rendered in an entity view mode and not as fields.


I just want to add my experience to the lot. I had similar issues using Drupal menu. The solution I used is:

Set all menu items with children to "Expanded". This as to be done manually: Structure > Menus > List links, edit links which has children, check the Show as expanded checkbox.
Use menu_tree_page_data function (example: $menu_tree = menu_tree_page_data('main-menu')) to get the menu, with all its children AND with active trail.
Create a renderable array using menu_tree_output function (example: $renderable_array = menu_tree_output($menu_tree)) to prepare the menu for rendering.
Use the renderable array as content for my custom block, but you could call drupal_render($renderable_array) to get the rendered HTML representing the menu.


How to make a reservation and a booking of seminars during the Commerce checkout process?

Your usage of the terms "booking" and "reservation" seems a bit strange to me. In the context of Drupal they are often used as synonyms of each other. I am not sure if I correctly interpret the difference you make, but I think this is crucial for you to differentiate (define?) them:

Booking = item that must be payed at checkout time.
Reservation = item that you must also be able to checkout, but you don't have to pay for it (or at least not yet).

So I think your question actually consists of 2 questions:

How to integrate this in Drupal Commerce?
How to ensure availability?

Below is what I think might help you find a possible solution.
Drupal Commerce integration
You should look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site, or just use that distribution (attention: it only has a beta release so far).
Here are some more details about this distribution (quotes from its project page):

... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.
It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts.
Easy booking profile is powered by Drupal Rooms and Drupal Commerce - widely used and popular contributed decisions, which means active maintaining and timely technical support.

Check availability
Take a look at these modules, which all have a stable (not alfa or beta only) release:

Availability Calendars (Reported installs: 2.061 sites).
MERCI (Reported installs: 441 sites).
Resource Conflict (Reported installs: 329 sites).
Simple Reservation (Reported installs: 202 sites).
Room Reservations (Reported installs: 156 sites).

I've ordered the list above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module. So do your homework to pick the right one for you.


How do I associate multiple users to a node?

User Reference sounds perfect for what you are trying to achieve. Not much is simpler than being able to select the users in the edit node form. Can you describe what kind of GUI you would like to use to select the use


How do I separate the "Product" select list & "Add to cart" submit form in a node product display?

I realized that you can't, albeit after several hours of experimenting.

However, you can add a price field (and other fields) to your "add to cart" form by adding a "price" form item element. Follow the instructions here for more details: http://drupal.org/node/1300798#comment-5328550

Tell me if this helps.


How to do an embedded select (with count()) with the Drupal 7 database api?

I don't think there's any existing method that will let you add a structured sub-query as an expression, so you're probably going to be left with something like this:

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

$sub_query = '(select count(*) as count from node_cnt nc where nc.nid = n.nid)';
$query->addExpression($sub_query, 'node_count');

// Build the rest of the query.


How do I get the category links as I had them in Drupal 6, before migrating the site to Drupal 7?

check this migrate and migrate_extras module, it is very handy framework to migrate content, you can easily migrate

node
taxonomy/categories
users

Edited:

Let me clarify with your scenario,
while migrating from source(D6) to destination(D7),

you have to define source field and destination fields as shown in below code sample.

first you have to migrate Taxonomy terms from D6 to D7.
later on you have to migrate node entity, while preparing node migrate class, you have to migrate term reference field as it is. so that in prepareRow function we can replace with old term_id with new term_id which is already migrated.

For example see sample code.

abstract class JiveBlogMigration extends Migration {

public function __construct() {
// Always call the parent constructor first for basic setup
parent::__construct();

// With migrate_ui enabled, migration pages will indicate people involved in
// the particular migration, with their role and contact info. We default the
// list in the shared class; it can be overridden for specific migrations.

  }

}

/**
 *
 * Jive Blog Post Information Migration class.
 *
 */
class JiveBlogPostMigration extends JiveBlogMigration {

  public function __construct() {
  // The basic setup is similar to BeerTermMigraiton
  parent::__construct();
  $this->description = t('Jive Blog Post Data Migration.');
  $this->map = new MigrateSQLMap($this->machineName,
                array('jive_blog_post_id' => array(
                        'type' => 'int',
                        'not null' => TRUE,
                        'description' => 'Jive Blog Post ID.'
                    )
                ),
                MigrateDestinationNode::getKeySchema()
   );

// Added ContainerType field for mapping
$query = db_select('migrate_jive_blog_post', 'mjbp')
        ->fields('mjbp', array('jive_blog_post_id', 'jive_user_id', 'jive_group_id', 'jive_container_type', 'subject', 'body', 'permalink', 'minorEdit', 'creationDate', 'modificationDate', 'status', 'displayName', 'blogstatus', 'feedEnabled', 'feedFullContent', 'pingOverride', 'pingServices', 'trackbacksEnabled', 'trackbacksModeration', 'trackbacksNotification')); //SELECT the fields from node
//generate the count for the number of records to be imported
$count_query = db_select('migrate_jive_blog_post', 'b');
$count_query->addExpression('COUNT(jive_blog_post_id)', 'cnt');
$source_fields = array(
    'jive_blog_post_id' => t('The id of a particular document in the jive system'),
    'term_data' => t("The taxonomy terms associated with the node"),
    'jive_container_id' => t("The social group or space id associated to the node decided in prepareRow()."),
);
$this->source = new MigrateSourceSQL($query, $source_fields, $count_query);

// Set up our destination - nodes of type blog
$this->destination = new MigrateDestinationNode('blog');

// Mapped fields
$this->addFieldMapping('title', 'subject')
        ->description(t('Mapping beer name in source to node title'));

// References to related objects (such as the author of the content) are
// most likely going to be identifiers from the source data, not Drupal
// identifiers (such as uids). You can use the mapping from the relevant
// migration to translate from the old ID to the Drupal identifier.
// Note that we also provide a default value of 1 - if the lookup fails to
// find a corresponding uid for the aid, the owner will be the administrative
// account.
$this->addFieldMapping('uid', 'jive_user_id')
        ->sourceMigration('JiveUserAccount')
        ->defaultValue(1);
// Mapping for Tags
$this->addFieldMapping('Tags', 'term_data');

// Additional mapping fields
$this->addFieldMapping('field_displayname', 'displayname');
$this->addFieldMapping('field_pingoverride', 'pingoverride');
$this->addFieldMapping('field_pingservices', 'pingservices');
$this->addFieldMapping('field_feedenabled', 'feedenabled');
$this->addFieldMapping('field_feedfullcontent', 'feedfullcontent');
$this->addFieldMapping('field_status', 'blogstatus');
$this->addFieldMapping('field_tbmoderation', 'trackbacksmoderation');
$this->addFieldMapping('field_tbnotification', 'trackbacksnotification');
$this->addFieldMapping('field_minoredit', 'minoredit');
$this->addFieldMapping('field_trackbacksenabled', 'trackbacksenabled');

//This is for path
$this->addFieldMapping('path', 'permalink');
$this->addFieldMapping('pathauto_perform_alias')
        ->defaultValue(0);

// Group mapping for space, personal, group associated Blog posts
$this->addFieldMapping('og_groups', 'jive_container_id');

$this->addFieldMapping('body', 'body');
$this->addFieldMapping('created', 'creationdate');
$this->addFieldMapping('changed', 'modificationdate');
$this->addFieldMapping('status', 'status');

// Unmapped destination fields
$this->addUnmigratedDestinations(array('revision_uid', 'teaser', 'revision', 'language', 'promote', 'sticky',
    'field_group_sticky', 'field_content_images', 'field_featured_content',));

//specify the unmapped source fields.
$this->addUnmigratedSources(array('jive_group_id', 'jive_container_type'));
}

public function prepareRow($current_row) {

 $source_id = $current_row->jive_blog_post_id;

 //populate all the tags associated with a particular node using the getDrupalTags() method
 //that returns an array of all the tags associated with a particular node.
 $term_data = JiveMigrationUtilities::getDrupalTags($source_id, 38); //38 is the object type for the blogpost in jive.
 if ($term_data) {
  $current_row->term_data = $term_data;
 }
 if ($current_row->jive_group_id != 'NULL') {
  $current_row->jive_container_id = JiveMigrationUtilities::getDrupalContainerNid($current_row->jive_container_type, $current_row->jive_group_id);
  }
 return TRUE;
}

}

Usual flow of migration module, it will create a mapping table for each migration class like migrate_map_jiveblogmigration, it contains sourceid1 and destid1 columns. for example D6 nid is as sourceid1 and D7 nid is as destid1.

in prepareRow function you can write a logic to replace old term_id with new term_id for each row of node migration.