Set the width of the select box in Drupal form Currently I have a select box in a form as follows :

$form['fieldset']['event_trigger'] = array('#type' => 'select',
    '#title' => t('E-mail event trigger'),
    //'#default_value' => $edit['mail'],
    '#size' =>20
    //'#options' => select_eventtrigger_dropdown(),
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
  );

But here #size attribute is not fitting my requirement. It should have been the width of the select box.  How can I achieve this or is there any workaround?

The size attribute you are trying to set there is related to how many items are shown at one time. So in those terms the height would increase and it would show a scrolling list of items to choose from if you added size to the select box. See Form API Docs for more information.

You need to target the select box with CSS to change the width (most themes/browsers set the width of a select box to width: auto; so it would be as long as the longest item to be selected).

So for instance if you want to set all of your select elements to take up the entire width of their containing divs you would set:

select {
  width: 100%;
}

Or if you want to target all select elements with a class of .form-select you could use:

select.form-select {
  width: 50em;
}

You can use id's also like select#id-of-element but using a class is the more generally accepted best practice for styling (not just in Drupal but general FED practices also).


How to access "add a card" page in Commerce Card on File? I would like to allow users to add a "card on file" outside of the payment workflow. I have authorize.net configured and I'm able to save a "card on file" during order completion. The cards list view appears correctly at the path user/1/cards:

This path is provided by commerce_cardonfile's implementation of hook_menu():

$items['user/%user/cards/add'] = array(

So logged in as user 1, I should be able to add a card from the page at the path  user/1/cards/add

But I get "Access denied"... How can I access a form to add a card outside of the payment workflow?

commerce_cardonfile looks for a 'create callback' from the payment method modules. commerce_authnet does not come with the callback, but this patch adds one:

add_card_on_file-2051357-21.patch

Here is the discussion: https://www.drupal.org/node/2051357

After I applied the patch, commerce_authnet_cim_cardonfile_create() was defined on both lines 760 and 1021. I renamed the latter so that Drupal was happy. Then "+ Add a card" became available on each user's "Stored cards" tab. And... it works!

Can I get my +250 points back? ;)


How to display user submitted nodes in the node detail view of the same user? I'm aware of such modules as Relation and Entity reference but I can't figure out how I make automatic relation between nodes that depend on the user that submitted those nodes.

Site has users A, B, C ... Let's say user A submits 10 nodes. When any user clicks on any of his nodes you can see his other 9 submitted nodes in the detailed view. When you click on node submitted by user B you can see his other submitted nodes and so on. This should work automatically without manually building relations between nodes.

How do I achieve this?

Thanks a lot
Ray

I tried the following and it seems to work:

Create a new block view
Add a Contextual filter of type Content: Nid
Add a relationship of type Content: Author (Required)
Add a relationship of type User: Content authored that uses the previous relationship and is required
Under Format you set Show: Content | Full Content - You must also use the User: Content authored relationship for this one

You could also change the number of related nodes that will be shown and also you might wan't to add a filter of Content: Type to restrict what kind of nodes to display. Notice that you could create a template for a specific content-type ie node--<YOUR_CONTENT_TYPE>.tpl and load and execute the view from there.

In you node.tpl file you would load this view doing something similar to:

$view = views_get_view('YOUR_VIEW_NAME');
$view->set_display('YOUR_VIEW_BLOCK_NAME');
$view->set_arguments(array($node->nid));
$view->execute();
echo $view->render();

Note I think you should specify every field you wan't to use, in other words you shouldn't use Show: Content | Full Content - because this will result in an infinite loop. I don't think this is a complete solution, but perhaps it will point you in the right direction.

If you are using fields in the view you could create a separate template named views-view-fields--YOUR_VIEW_NAME--YOUR_VIEW_BLOCK_NAME.tpl that will be used to output the actual fields.

To exclude the current node from the listing you need to modify your contextual filter.

Click the More button for Content: Nid and choose exclude you should also make this filter use your relationship for Content: Authored


Module to suggest node revision to node author Is there a module which facilitates functionality of allowing users to suggest node revision to author and author finally can publish the revised suggestion. Till the author is not accepting or rejecting the revision the existing node will be displayed.

check out revisioning. It seems more like it's set up for moderators to view revisions before approving content, but perhaps it can be used for what you need.


How to call a specific library file inside the div I have declared the external library and calling this library for a particular page using preprocess html.

The Library file has been called for the particular page and showing the script content at the bottom of the page.

Now I want to wrap the script content between the div

How do I wrap the script content between the Div using preprocess html or Any Other ways to wrap the script ?

Attaching a library via the #attached tag will add it to the header (or bottom of the page if that's the settings). It does not get added into the "content" area. So, wrapping it in a
 is not applicable.

If you are using JS to generate some content that needs to be placed on the page, then it needs to be written to find some selector and insert the content.  E.g.

jQuery('#my-dynamic-content').html("My new div content");

Then just add the

 to your template/content as needed.


Question and Answers setup Trying to figure how to setup drupal 8 to function like StackExchange.

My goal is to be able to allow users to mark answers helpful so that best answers get moved to the top. Similar to StackExchange.

I can think of two ways to do this but would like some feedback from the experts.

Option 1: Create content Question and add comments to it. Use flag module to flag helpful replies. Create a template for question comments so that each top replies + its replies are groped together.

Option 2: Create Question, Create comment type Answer, Create a new comment type called replies and attach it to comment type Answer.

Or is there another alternative that I am not thinking off?

What would be the best way to create a similar setup such as StackExchange?

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?".


Need to know if user is coming from frontpage using jquery On a Drupal 7 site I need some jQuery-animation on a page, only if user is coming directly from frontpage. My programming skills are very limited and need some help on that. I found something with parent.history.back()-function, but I don't know if and how I can use that in an if-statement.
Any help is very appreciated

jQuery(document).ready(function($) {
  var referrer =  document.referrer;
  if (referrer == 'http://domain.tld/') {
    // Make whatever you like
  }
});


Custom user profile displays I have added some extra fields in User entity like address, twitter account e.t.c. The requirement is that each user should be able to choose whether his profile will be completely public to other users or some fields should be hidden. The user does not get to choose which ones are hidden or not, he only chooses via a select menu (term reference) what his profile view should be: "Complete" (all fields visible), "Partial" (some predefined fields are hidden) or "Basic Info" (only name and pic).

My question is, what is the best practice to implement the three different profile views according to the user choice? My thoughts so far:

via the respective template using if statements to display or not some fields
via custom display modes, but I don't know how to delegate to another mode conditionally when view_mode is already set to "full"

Any other suggestions are welcome. Thanks in advance.

I would suggest that following best practices this should definitely not be accomplished by modifying template files. If you change your theme for example, this functionality should not be effected.

A custom module would be a better place to accomplish this using hook_user_view() http://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_view/7 and modify $account->content to drop the fields that should not be displayed.


PHP cli script for flushing drupal cache So I have created script that flushes drupal's cache and it's ran in CLI.

The problem is after first use, I can't use the script again, because some classes ('SelectQueryExtender' or 'DrupalDefaultEntityController') are missing. Clearing cache via drupal admin menu (admin_menu/flush-cache) fixes it and I can rerun.

Now the question is why clearing cache from via HTTP works and from CLI doesn't?

I'm running on Drupal 7 and code can be found below:

define('DRUPAL_ROOT', '/srv/www/'); // Drupal root folder.

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Clear cache.
drupal_flush_all_caches();

EDIT: when I clear cache via drupal_flush_all_caches and later make curl call for cache clearing through apc-status.php, then even website itself gives Fatal on above mentioned classes missing.

Install Drush. It's your friend. Then you can issue

drush cc all

To clear caches.

You can also rebuild registries if needed to if you have that module installed.


How can I automatically visually number each webform component? e.g. 1) ... 2) ... 3) I am building a webform and would like to number each question (webform component). What is the automated way to do this (rather than number the component label text)?

Webform 3 (but may move to Webform 4 later).

I've searched a bit for this, but get results about phone number fields :/

Thanks for your time.

Update

I have clarified the question to state that I want to visually number the components, the numbers themselves would not be related to the component id, rather, they would be for the benefit of the user. It would be used to number the questions e.g.:

Question
Question

etc.

You could use an entirely front-end solution with CSS counters: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters

I believe components are siblings of each other which would make this quite easy.


WSOD for logged users after upgrading some module I have updated the following modules on my website:

ctools
context
devel
ds
libraries
metatag
pathologic
rel_to_abs
variable
webform

After the upgrade whenever I log in, I am not able to access any page (not just the administration area).
Anonymous users have no problems.
Downloding the whole website and installing it locally with the backup before the update, everything works fine.
I have enabled debug logs and all possibile error reporting options, but I have no error or warning of any kind.
I have increased the memory limit, clean every cache and run the registry rebuild via php.
I have no ssh access to the host, so I cannot run any remote debugging.
Can someone point me out to a possibile solution?

go into you database, set the status to 0 on the rows for each of the modules you mentioned. Reinstall each module one by one to find the problem module.

you could also try adding this to the top of index.php (remember to remove it later)

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);


Are $form_state values cleaned of malicious code even if #limit_validation_errors is set? I'm building a multi step form with a bunch of required fields on each step. The user has to be able to save the current step of the form, even if they haven't filled out all the required fields.

I will then save it to a custom entity I've created.

I'm using code like this:

#limit_validation_errors => array(),
#submit => array()

to disable validation. So will Drupal's internal code still clean these values of malicious code when I trigger a submit/save them to the entity? Or do I have to do it myself?

I'm using $this->set('key', $value); to save the data.

If you set #limit_validation_errors, only elements passed into the value are validated. Everything else is not validated. So for example with this:

#limit_validation_errors = array()

Nothing in the form is validated. And with this:

#limit_validation_errors = array('field_1', 'field_2')

Only field_1 and field_2 will be validated.

To continue on with this, only fields that are validated become part of $form_state['values'], and are then passed on to any submit functions. These values will be as safe as any values in a FAPI form submission, as they will be both sanitized and validated.

Any fields not included in the array passed to #limit_validation_errors will not be part of $form_state['values'], and therefore there is nothing to sanitize, nor any malicious code to validate. The element will simply be missing (or maybe empty, I can't remember off the top of my head) from $form_state['values'] in the submit functions.

For myself, the only use case I've ever found for #limit_validation_errors, is one I stopped using. I would use it on a back button for ajax forms, so that the user could step back a step, without getting errors for any fields on that step of the form. The problem however is that any partially filled fields are then lost on that step of the form when going back, since the submitted values are entirely ignored.

What I do instead, is in my validation function, I check to see if the 'next' button has been clicked before validating.

Example form definition (imagine this is step 2 of a multi-step form)

function some_form_step_2($form, &$form_state)
{
  $form['some_field'] = array
  (
    '#type' => 'textarea',
    // See comments after code about why I did this:
    '#title' => t('Enter a value') . '*',
    '#default_value' => isset($form_state['values']['some_field']) ? $form_state['values']['some_field'] : '',
  );

  $form['actions'] = array
  (
    '#type' => 'actions',
  );

  $form['next'] = array
  (
    '#type' => 'submit',
    '#value' => t('Next'),
  );

  $form['back'] = array
  (
    '#type' => 'submit',
    '#value' => t('back'),
  );

  return $form;
}

function some_form_step_2_validate($form, &$form_state)
{
  // check to see if the clicked button was the 'next' button
  if($form_state['op'] == $form_state['next'])
  {
    // Ensure a value has been entered into some_field
    if(!strlen($form_state['values']['some_field']))
    {
      form_set_error('some_field', t('Please enter a value'));
    }
  }
}

function some_form_step_2_submit($form, &$form_state)
{
  // Here, if the 'next' button was clicked, the value in
  // $form_state['values']['some_field'] will be sanitized
  // and validated

  // However, if the 'back' button was clicked, the value in
  // $form_state['values']['some_field'] will be sanitized,
  // but not validated, as the validation only needs to happen
  // when advancing to the next step, not stepping back to the
  // previous step
}

As you can see from the code, the validation only happens when the 'next' button is clicked. The field some_field is actually required, however, if #required is set on the field, it will always be validated when the back button is clicked. This can be prevented with:

$form['#limit_validation_errors'] = array();

However, if the user has entered a partial value into this field, #default_value will be empty if the user goes back to the first step, and then returns to this step, since the value will not be made part of $form_state['values']. The way I've built it, the 'required' asterisk (*) is included with the form field title to show the user it is required, but the validation of the required field only happens when advancing to the following step, not when going back to the previous step. This way the user can go back whether a value has been entered into the field or not.

Another added advantage of this method is that a custom error message can be shown for required fields. If #required = TRUE was set on the field above, instead of  using the method I did, the error message would be 'Please enter a value? is required' (or something close), which is not very clean English. With the code above, the message is instead 'Please enter a value', with the field highlighted.


Search API Views - How to display facets on a views block? I am using Search Api Views and Facet API to achieve that.

I am trying to enable facets to a views block, or when calling a view programmatically, but unfortunately they are not displayed as expected.

However facets are correctly displayed on the page created under views interface:

I tried to create a block via views interface, and then adding it through blocks, but the facets block doesn't appear.

Either if a try to print the view programmatically this way:

$view = views_get_view('news_search_api_');
$view->set_display('page');
$preview = $view->preview('page');
print $preview;

The facets are not loaded at all.

The answer depends on your theme; but this is an example of how to do it with 'Commons'

in > admin > Structure > Blocks

  Search for your facets and select the block you want them to go in .  ie 'Sidebar First'

  SAVE

  open your View > Page .

  under FORMAT change Show to 'Panel Fields'

  In Settings choose your Panel Layout from the list.  ie 'AT One Column' should display the above block example.

  And then still in the VIEW - making sure you are in the 'Page' display; otherwise you won't see this option.  Under 'Advanced' - you should now see under 'Exposed Form' the text 'Exposed form in block:'  - Change this to Yes.

  once you've added this to the view you'll now be able to
  go back to > structure > blocks.
  And see the exposed form here to move to the block you wish.

This information should be enough to point you in the right direction.


How do I alter a database schema defined from another module? Since hook_schema_alter() was removed from Drupal 8, how do I alter any existing schema defined from another module in Drupal 8?

I have used mymodule_update_8201 (hook_update_N()) in my .install file, but no new field or column gets added into my existing table. Is there any other way to achieve this?

This is the code for the first module (a.install).

function a_schema() {
  $schema['my_table'] = array(
    'fields' => array(
       'type' => array(
          'description' => 'registration type',
          'type' => 'varchar',
          'length' => 255,
        ),
     ),
  );
}

This is the code for the second module (b.install).

/**
 * Implements  hook_update_N().
 */
    function b_update_8201() {
     $spec = array(
        'type' => 'varchar',
        'description' => "New Col",
        'length' => 20,
        'not null' => FALSE,
      );
     $schema = Database::getConnection()->schema();
     $schema->addField('my_table', 'newcol', $spec);
     return $schema;
    }

hook_schema_alter() was not used for adding fields to the schema, it was used for reporting alterations to the schema by your module. This was so that functions such as drupal_get_schema() knew the alterations you had made. These functions have all been removed from Drupal 8 however, so there is no need to report your changes in hook_schema_alter().

You can add fields to another schema using:

\Drupal::service('database')->schema()->addField()

Documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Schema.php/function/Schema%3A%3AaddField/8.2.x


How can I insert into table a row which contains an auto incremented field? I am using drupal 7.41, I have a database table and it contains an auto incremented column/field. I am trying to insert some data into that table by using db_insert but it keeps displaying syntax error. Am I missing something in this syntax?

db_insert('my_table')
-> fields(array(
    'id' => NULL, //my auto incremented field...
    'name' => $form_state['values']['name'],
    'link' => $form_state['values']['link],
    'group' => 2 /* I have already tried this field with and without integer data and string data. Eg '2' and 2*/
    )) -> execute();

My mysql table contains four columns: id (Auto incremented, int), name (varchar(50)), link(varchar(200)), group (int).

I have tried every syntatic way but no to avail. And lastly here is my error message when I execute the query above:

I think there is no access violation here, since I was able to insert some other rows into different tables. Only difference is that that table has no auto incremented integer field and other integer fields. Just two varchar fields.

Thank you.

The problem is you are using the keyword GROUP as a column name. Drupal's PDO code doesn't always escape column names, so you should avoid using MySQL keywords.

See the MySQL documentation.

  Most of the reserved words in the table are forbidden by standard SQL as column or table names (for example, GROUP).


Fivestar: How to display description text inline By default, the Fivestar module offers (at Structure » Content types » Article » Manage Display » Fivestar settings) to show "Text to display under the stars". It looks then like this:

How to show the description text inline beside the stars?

I wasn't able to do that in CSS (or to find the caused code in the module).

It's doable with CSS. You need to declare the parent of the description and the stars as flex or inline-flex or -webkit-inline-box: .field-type-fivestar .form-item { display: -webkit-inline-box; }


Show User Information in Block from View I have a block that shows some data from the User area (People) in Drupal 7. I have a rewrite setup that shows "VACANT" if there is no user selected for the content type. When logged in, I see users for 3 of the 4 contents I have created, which is correct. When logged out, I see VACANT for all of the contents.

Is there some restrictions on showing User data to the public? How can I make a certain Role visible to everyone?

EDIT::: Thanks to @Clive: View user profiles [x] for anonymous.

Go to /admin/people/permissions and tick the "View user profiles" permission for anonymous users:


Possible parent values for parent of links I am trying to create links in my Drupal 8 module, following this tutorial. So far, I have a link as follows in my module.links.menu.yml file:

module.admin_settings:
  route_name: module.adminForm
  title: 'Module Configuration'
  description: 'Set up module on your website'
  parent: system.admin_config_system

My question is, how do I find all possible values for the parent property? I looked in the docs but couldn't find one. However, there is a paragraph in the above tutorial which says:

  Determining the parent menu_link name can be a little tricky at first.
  If you know the path of the parent menu item, you would need to search
  for it in all available *.routing.yml files (most text editors and
  IDEs should allow you to search all files in a project) and find the
  route name for that path. Then, you would need to search for the route
  name in all available *.links.menu.yml files. The menu_link whose
  route_name matches is your link. Alternatively, if you know which
  module is defining the parent menu link (or one of the parent menu
  link's children), you can go straight to that module and perform your
  search.

But I am not sure I understand as I am new to Drupal. Is there an easy way to find the set of possible parent values?

Thanks.

You can go to the menus structure and click on edit of the menu link under which you want to place the new link. The example from your question would open in this url:

/admin/structure/menu/link/system.admin_config_system/edit

Then you'll find the parent name in the slug before /edit.

But the easiest way is to register the menu link without parent, which would place the new link in the top level of the menu and then drag and drop the link where you want it to be.

You probably need to specify the menu name in the yaml file:

menu_name: admin

In the exported configuration the links you've moved in UI appear in this configuration file:

core.menu.static_menu_link_overrides.yml

where you'll find the parent value where you dragged the link to. You could then use this information for module.links.menu.yml, if you want to deliver your module with this information.


How are menus rendered? When Drupal renders a menu, it shows only those links that the current user has the right to actually click on and visit. Instead of that behavior, I would like to see permissible pages as clickable links and non-permissible pages as non-clickable menu item titles, so that the user can see what they cannot yet click.

I have code that so far loads menu links and creates a list like this, but it doesn't support hierarchy, expanded/collapsed, site-wide menu theming, etc. because all it does is build a <ul> with a <li> item for each menu link title. If you want to look a the code so far, it's Foreshadow Menu (in my Github account). My goal is to render my version of the menu in a way that is consistent with and retains the features of the Drupal-rendered menus.

My question is: how does Drupal render menus? Specifically, how does it determine whether to show/hide a link? Does it use show() and hide() somewhere internally, where I could override and change the menu output? Or am I going about this all wrong?

_menu_tree_check_access() should go a long way towards understanding what Drupal does internally.

It declares a new array of items, then loops through each item currently in the menu and checks access. Only if the current user has the correct access is the item added to the new array. At the end of the function, only the new array is returned. So Drupal's method is actually a bit more low-tech than I think you were going for.

Just so the process is a bit more obvious the functions are called in this order:

menu_build_tree() calls
menu_tree_access() which in turn calls
_menu_tree_access()

If you're looking to emulate the way Drupal builds its menus, I think menu_build_tree() is probably the best place to start.


D7+ i18n: What is the normal way: a single node with 2 translations or a different node for each translation I am having a difficult to understand this issue:

My D7 + Internationalization create a different node for each translation. Is this the normal way? Than how does Drupal know they belong to a same article.
I remember in D6 was one node and one editing page for all the translations of the articles.

I think the normal way is to keep a single node and different paths with different prefix: /fi or /en.

What do you think?

I believe this is the normal way. In /admin/content it lists the content and you can sort by language.

It knows which belong to which because it writes that info into the node table in the database by defining the 'tnid': The translation set id for this node, which equals the node id of the source post in each set.


How to Display popup block when user scrolls down to the bottom of node I am using drupal 7. I want to display a popup block for a user to share the node on social media, but i want this popup to appear as the user scrolls down to the bottom of the node. Any module(s) possible to achieve this?

I have tried the Popup and Popup On Load modules but none seems to achieve this objective.

Any help or suggestions appreciated. Thank you

You could do It without modules using some CSS and javascript.

You can create the block with the content you want to show, keep it hidden by CSS and, once the user scrolls down enough, trigger a js event that toggles the blok class to a visible one.

Here You can find how to trigger an event when scrolling to a certain point:

https://stackoverflow.com/questions/21561480/trigger-event-when-user-scroll-to-specific-element-with-jquery

Using the example code, you could use something like:

$(window).scroll(function() {
   var hT = $('#scroll-to').offset().top,
       hH = $('#scroll-to').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
       $('#yourblock').toggleClass('visible');
   }
});


Empty view is rendered even though there is no result I have created a view in order to create a block for slide show in drupal 7.
In my view I used a conditional field. This field gets the id of node from URL so I set "When the filter value is NOT available" to "Provide default value" and in TYPE drop down menu I set "Content ID From URL"

This view works with no problem. However, when the view is empty (there is no rows for fetched parameter value from URL) I see some rendered codes.

What is your solution for this problem? As far as I know when a view returns no row, it must not be rendered in source code. In above codes, you see there is no result but the codes of block are printed !!!

Thanks a lot for your guidance.

You should add a filter criteria for any one of the fields. For example if you have a field called company then you could add a filter criteria for this field and then choose "Is Not Empty (NOT NULL)" from the Drop down. This would make sure that the view is rendered only if the required field is present.

In normal case  when you are passing a Contextual filter the view is rendered even though the result is null. but if we provide a filter as I mentioned above it does not display at all.


Add extra html to ubercart cart and checkout pages I need to wrap ubercart cart, cart/checkout and other front-end pages in extra html, but cannot find a way to do it (some template files or way to add my extra html).

For example, mydomain/cart ubercart content is inside

, and i need to add more html before and after that div.

I could watch for ubercart in page.tpl.php with current_path(); and on occurance add that extra html, but would like to know is there any more propper way.

Update: it is Drupal 7 with Ubercart 3

You can achieve this in following ways,
1) define a template file:- in your template.php, define a template file for checkout page

/**
* Implements hook_theme().
*/
function themename_theme($existing, $type, $theme, $path) {
  $items = array();

  $items['uc_cart_checkout_form'] = array(
  'render element' => 'form',
'template' => 'uc-cart-checkout-form',
  'path' => $path . '/templates/',//where the tpl files are located
   );

   return $items;
 }

Then in your templates folder create a file uc-cart-checkout-form.tpl.php, here you can render your form with additional htmls

2) Override the theme

Check this instruction on Ubercart How to Theme the Checkout pane in Ubercart 3, by following this you can include your custom html.

Similarly the above methods are applicable to cart page also


My hook_menu_alter() and page callback don't get triggered This question relates to How do I redirect a taxonomy menu item to another path?

I followed the recommendations of Clive and wrote a hook_menu_alter to provide my callback.

function material_menu_taxonomy_page_callback($term) {
  dsm('Entered material menu callback');
}

function material_menu_menu_alter () {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_menu_taxonomy_page_callback';
}

I placed a code line dsm("Altering"); in the callback to see where in the process the callback is being called, but it never shows up.

I am fairly certain that I have the code correct.

The hook has the name of the custom module.
The callback name is correct.
the callback is in the same file as the hook
I have turned the module off and then on so that I can be sure that Drupal knows about mymodule_menu_alter
And I have flushed the caches.

My assumption is that mymodule_menu_alter()' should change the callback in the menu item array and that the callback will be called each time the menu item is selected. That suggests that mydsm()` message should display at the top of the page requested by the menu.

While Clive's test indicated in his answer worked, my revisions did not. Following Clive's answer recommendations I revised the code as follows.

material.info file contained in modules subdirectory = sites/all/modules/Custom/material

name = Materials
description = Redefine the path for materials menu
package = CR-Hub
core = 7.x
; Includes
files[] = material.module

material.module file in same subdirectory

function material_taxonomy_page_callback() {
  drupal_goto('taxonomy/term/1');
  // return 'Entered material menu callback';
}

function material_menu_alter(&$items) {
  // return 'Entered Material Menu Alter';
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_taxonomy_page_callback';
  return $items;
}

When I select any menu item neither drupal_goto(), or return 'any text' lines redirect the selected path from the menu item.

You haven't passed $items into the function ;)

function material_menu_menu_alter (&$items) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_menu_taxonomy_page_callback';
}

Without that you're not actually altering anything as $items doesn't exist in a global scope.

You'll also need to clear the caches again once you've made the change.

UPDATE

Working code that I've just verified:

material.info:

name = Materials
description = Redefine the path for materials menu
package = CR-Hub
core = 7.x
; Includes
files[] = material.module

material.module

function material_taxonomy_page_callback($term) {
  // Calling drupal_goto() here will result in an infinite loop.
  // This is the page callback for pages with a URL like taxonomy/term/1 so
  // there's no need to redirect...you're already where you need to be.
  // This function is used to build up the new page content for the taxonomy page

  // As a test just output the name of the term related to this page.
  return $term->name;
}

function material_menu_alter (&$items) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_taxonomy_page_callback';

  // You don't need to return anything from this function as $items is passed in by reference...anything you change in that variable will be reflected in the $items var in the calling function.
}

Once installed if I go to any taxonomy page the content region contains just the name of the taxonomy term for that page (using return $term->name). If it's not working for you the only thing I can advise is to clear Drupal's caches, or check what custom/contributed modules you've got installed that might be overriding your code.


Drupal commerce donate: Safely update to dev version of module on live site I need to update my charity website to the dev version of commerce donate because we have recently discovered that donors cannot donate decimal amounts with the current recommended release (e.g donate £5.20) and this is something that we need as people need to pay in fundraising money etc.

I am weary of uninstalling the current module and reinstalling as we have several products that are created using the donation content type and don't want to lose them or the existing donations people have made from the system.

Is there a way to do this safely and (preferably) easily?

If you go through the normal process to update the module (which for me means drush dl --dev commerce_donate in this case - or you might download & un-tar the module directly), no uninstall will be necessary.  In general you should not uninstall a module before installing an update, for exactly the reason you fear.


How to archive drupal forums? How can I add archive state to drupal forums so that:

  They are not visible in search results
  They are shown in a different container
  They are visible only to some users based on user-roles

I don't want to unpublish them-

I also want a spam state to differentiate unpublished and spam posts

They are not visible in search results

http://drupal.org/project/search_config

They are shown in a different container

Templating system, or blocks, or panels

They are visible only to some users based on user-roles

EDIT

Those 2 steps are equal, but becose my understanding problem the last point can be different.

In /admin/people/permissions you should have the options to allow only some roles to access the forms nodes.


How to add library to Paragraph bundle using hook_preprocess_theme? I wanted to add a library to a specific paragraph bundle. I know I can do {{ attach_library('my_theme/my-library-name') }} using twig, but that means I have to create a file for each bundle. The goal is to be able to use just the my_theme.theme file to add the library.

Question

How to add library to Paragraph bundle using hook_preprocess_theme?

Here is what we tried, but it didn't work even after cache clear.

function mytheme_preprocess_paragraphs(&$variables) {
  $elements = $variables['elements'];
  $paragraph = $elements['#paragraph'];
  if(isset($paragraph) {
    $paragraph_bundle = $paragraph->getParagraphType()->id();
    switch($paragraph_bundle) {
      case 'my_bundle':
        $variables['elements']['#attached']['library'][] = 'my_theme/my-library-name';
        break;
    }
  }
}

You have to do like this instead:

$variables['#attached']['library'][] = 'my_theme/my-library-name';

So you attach the library directly to $variables instead.


Bitnami Installation forcing me to flush caches while theming I recently set up a Drupal 7 installation on an AWS ec2 instance with Bitnami.

When I'm theming, or editing any kinds of files in the sites directory a regular browser refresh won't show the changes, I need to hit Flush all caches > Css and Javascript to view the changes.

I've disabled caching in Development > Performance, and I don't have Advanced Agregation installed or anything.

Is there something to the Bitnami installation, or ec2 that could be caching the theme files?

Update for anyone who comes here in the future:

Bitnami comes with Google PageSpeed installed & enabled by default It's a pretty useful tool, but it's tricky to figure out what's caching your css when there's nothing apparent.

To check for it, take a look at the  of your drupal site & look through the <meta> & <style> tags for compressed css files, they'll look like lkjsdhf.gkdfsgklkshr.pagespeed.kljhasdfgk.ljsdhflgk or somesuch.

To disable it, navigate to your installation's apache configuration folder, mine was /home/bitnami/stack/apache2/conf & edit pagespeed.conf

Look for the line ModPagespeed on (mine was line 20) and change on to off

After that, restart Apache. You can also log into AWS and reboot your instance.


How to deal with the "Payment failed at the payment server" error? I'm trying to get my website integrated with SagePay.
Everything works well untill the payment is made.
Once a client makes payment he/she gets the following error message:

Notice: Undefined index: crypt in commerce_sagepay_form_redirect_form_validate() (line 55 of /sites/all/modules/commerce_sagepay/includes/commerce_sagepay_form.inc).

Payment failed at the payment server. Please review your information and try again.

And I get the following info in the logs:

Response could not be converted to tokens

Despite these errors the payment was taken, but the order remains in the shopping cart with the status Checkout: Review

I'm using Commerce SagePay 7.x-1.0 and the integration option is Form.

I had a similar problem with the token conversion, be sure you're using the -dev version (2014-May-23 or later) of Commerce Sagepay before trying anything else.

Note: probably related to: https://drupal.org/node/2115203


How is the node revision ID getting updated? I have a question related to _node_save_revision function in drupal 7. I just want to know how I can get the new revision ID after saving a revision using this function

It is mentioned in the documentation here.

  The resulting revision ID is available afterward in $node->vid.

But how does this happen? Where is the new revision ID assigned to the node object?

drupal_write_record handles that.

vid is the primary key on the node_revision table, as declared in node_schema, and drupal_write_record knows that because it introspects the schema when writing the record.

From there it just takes the ID returned from the database query, and populates the correct property on the object that was passed in. In this case, that's the vid property on the node object.


how to link to sections in the same page? How to create menu items with links that link to the same page (like scroll down further)?

Example: http://eshbeata.com/ , clicking on "Work" or "About" just scrolls down the same page.

This isn't so much a Drupal thing as an html link thing.

As you can see from the URL when you click on one of those links, you'll notice that they look like this:

http://eshbeata.com/#about

or

http://eshbeata.com/#works

Note the hash tag and word at the end (#about and #works).

That's called an 'anchor' and is essentially a link to a specific part of a page rather than a link to just the page.

Using anchors requires a two-part setup:

First you have to label the place you want to jump TO with your link.  So, by the exact place in the page that's the 'works' section, the author of that page would have the following:

It's just an empty link that names this spot in the page with the name 'works', and that's precisely what the link below will look for

Second, in the link "Work" in the top menu, there is the anchor '#works' at the end of the link.

Work

Hope this helps.  You can read much more about this online just by searching for something like 'html anchors' or similar terms.


Views Data Export - Selectable fields Is it possible to select fields for the export?

For example: When i click button it shows me a popup, where i can select content i want to attach to the exported file.

Currently this is not possible. You can always build a view that contain only fields you need. Or select fields when configuring view's display.

Developers needed to choose between GUI on export and unattended processing. They choose automation capabilities, and for good reasons - large exports can take a long time, so it makes sense to trigger them at night using drush.

If you believe there should be such option, then you can fork project - it's opensource, GPL v2, so you have full right to do so. You can also file a feature request in module's issue queue, but personally I don't think it would be implemented by maintainers. If you will provide ready to use patches, then maybe.


Menu Block (or custom menu display): expand immediate children of active item I need to show a menu which only displays nodes one or two levels into the menu hierarchy, unless these nodes are immediate children of the node currently being viewed, in which case they should also be shown. (I explain what I'm after more fully in the lengthy 'example' below.) The Menu Block module almost lets me do this, but lacks a setting to expand the immediate children of active item. I added this as a feature request for Menu Block but have had no reply. Is there any way I can implement this myself, either using Menu Block or writing code to display the menus myself? Any code pointers would be very helpful.

(Background info: I'm using Drupal 7)

An example of what I'm after

Suppose you have a menu with these items (with the number of dashes before them representing their level):

-i1
--i2
--i3
---i4
---i5
----i6
--i7

If in Menu Block I set my menu block up with 'Starting level' = '1st level' and 'Maximum depth'=1 then it'll look like:

-i1
--i2
--i3
--i7

However, I'd like there to be an 'expand the immediate children of the active item' setting in Menu Block. If this setting were chosen then if the active item were i3 or i4 you should see:

-i1
--i2
--i3
---i4
---i5
--i7

And if it were i5 or i6 you'd see:

-i1
--i2
--i3
---i4
---i5
----i6
--i7

Like we figured out in the comments the problem was that the "Expand all children of this tree" option was checked for the menu block. Without checking this the children will only be shown if the user is on a related page, which was the desired result.


Will disabling the Form Builder UI do anything to my webforms? I want to disable the form builder UI so that I can select "multiple option" for a select list in the default webforms editor. This feature is missing in form builder. Can I do this or will it clear out all the work I've done building the forms within the form builder UI?

Form builder is just a user interface. It does nothing to the forms themselves. The display and use of the forms is dependent upon the modules that implement the forms. so, yes, you can disable it with no effect on your existing forms.


Digest of suggested content based on user activity Twitter acquired Summify that employs users' browsing activity, social trends, and other black magic to build email digests of suggested content that are very effective at drawing traffic back to their site.

I know in Drupal it should is relatively easy to build digest emails or suggest content blocks based on content or tags that the user follows, commented on or authored. I'm wondering how to take the next step towards calculating a relevancy score of suggested content based on the user's browsing on the site, and/or based on the activity of other active users (trend makers) on my site.

I'm asking for guidance to accomplish this using any or all of the following approaches:

existing modules that uses browsing activity of authenticated user to score relevancy of a given piece of content. Or something like this.
paid services that support Drupal and preferably have a module to interface easily with Drupal. One of Summify's competitors?
could Apache Solr help in any way?

This wiki page on d.o has a review of some relevant contrib modules.
http://groups.drupal.org/node/12347


Free Pager and Contextual filter I just can't get my head around the following problem.

I have two content types. One is ISSUE the other one is ARTICLE.
I use the Node Reference module to link and ARTICLE to an ISSUE.
Then I am using Free Pager module to have a pager on every page to click to the next and previous node.

The pager works but for all ARTICLES of all ISSUES. Now I want it to work for only the ARTICLES in the same ISSUE as the current node.

I tried to get this to work with the normal Views filter and the Contextual filter but for some reason it doesn't work. Does anyone have a solution for this? Or another option with other modules that do the trick?

Thanks in advance
Joost

It can be done using Views:

set up the view in the format you want so that all Articles show
create a filter on the Node Reference Field in Content:Articles
expose this filter
make the operator: Is one of
Options: Select all - this should automatically update as new issues are created
Pager: Mini, Mini pager, 1 item - this will create a simple pager with only one item per page


sort views comments by vote result keeping thread I want to show comments of nodes ordered by vote result (most popular comment at the top of the list).
I have installed voting API, rate and views module. Then add a yes/no voting to comments and enable threading for comments in order to let users reply each other.

I created a views to show comments in most popular order with these sort criteria:

Comment: Thread (asc)
SUM(Votes: Value)

Now the problem is that when views tries to keep thread it sort theme by post date (asc/disc) and do not see the second sort criteria.

So how can I sort comments by vote results keeping threading?

EDIT:

Main problem
Currently there is no way to tie all the children and grandchildren comments to the Main Parent (original/first ever parent). Also, need a way to separate the Main parent from all the children.
TL, DR Solution
Use the Views field view module to separate the children from main parent, and add all children as a field. That way, we are able to sort Main Parent's by Votes without affecting the children and grandchildren.
But there is no way to just show all children and grandchildren of a Main Parent CID; therefore, create a custom module to solve this problem, so we can use the view field technique.
Detailed Solution
Requirements:
Views field view, Entity API, Main PID (custom module below).

main_pid.info
name = Main PID
description = Links all children and grandchildren comments to the main parent by saving main parent cid into main_parent_pid field when comment is saved.
package = custom
core = 7.x

main_pid.module
<?php

/**
 * Implements hook_comment_presave()
 */
function main_pid_comment_presave($comment) {

  $pid = $comment->pid;

  if ($pid > 0){

    while ($pid > 0) {
      // Implements comment_load()
      $load_comment = comment_load($pid);

      $pid = $load_comment->pid;
      $cid = $load_comment->cid;

    }

    $comment->field_main_pid[LANGUAGE_NONE][0]['value'] = $cid;

  }

  elseif ($pid == 0) {

    $comment->field_main_pid[LANGUAGE_NONE][0]['value'] = 0;

  }

}

Now in comments add a new field called Main PID with machine name of field_main_pid. You can do this programmatically or using the Drupal UI (I will leave this up to you)

Now, hide field from display

In your view:
In fields, add Comment: Rendered Comment (Thanks to Entity API)

In fields, add Comment ID

Now add a new block

Click on block, and change the display name

In fields add Depth

In fields, add Comment: Rendered Comment (Thanks to Entity API)

The style settings will allow you to indent the children with CSS.
Example:
.depth-1 { width: 480px; margin-left: 10px; }
.depth-2 { width: 470px; margin-left: 20px; }

In Filter Criteria, add Content: Main PID

Only the Main parent has PID of 0, therefore, this will show all the children only
Then add Content: Thread in Sort and Main PID in Contextual Filter
So your Children View should look like this:

Going back to the first View:
In Filter Criteria add Main PID

This time equal to 0, since we only want the main parents.
Now in Fields, add Global: View (Thanks to Views field View)

Your Original/Main View Should look like this:
Important: Add contextual filter of NID here (forgot to do that).

Lastly, In Sort Criteria, add the Votes Value (Not shown on screenshot since I did not bother to install Voting API and Rate) and remove the default Post date.


How can I programmatically create a link/URL with querystrings set from parameters? In Drupal 8 I customize the filter in the block in the sidebar menu. When the user clicks on the option in the block, I need to pass his choice to the URL.

$this->args = \Drupal::request()->query->all();
$args[$id] = $value;
$url = $this->url = Url::fromRoute('<current>');
$url->setOptions(array('query' => $args));
$link = 'toString() . '">' . $label . '';

And in the end, my URL looks like

 drupal/page_view?content_type=type

but I need my URL to look like

drupal/page_view?content_type%5Btype%5D=type

Do you know how can I modify my code?

Let's say if your $args is an array like below:

$args['content_type'] = 'type';

Then you have to append type to it rather than just giving your $id to $args

$args['content_type'] = ['type' => '123'];

Then your overall query will be like:

$this->args = \Drupal::request()->query->all();
$this->args = [$id => $value];
$url = $this->url = Url::fromRoute('<current>');
$url->setOptions(array('query' => $args));
$link = 'toString() . '">' . $label . '';


Drupal shortcuts - link with question mark included When I add a link to shortcut set which looks like this:

admin/work?date_filter

shortcut module changes this question mark sign "?" into this "%3F" and this link doesn't work anymore. I believe I can't avoid it - looks like it's a bug, so my question is how to add link as a shortcut programically?

The shortcut module is more strict about valid URLs it can use compared to what the menu module will allow (e.g. no external URLs, no query param).

One way to circumvent this is to use hook_menu in a custom module to define a valid path that redirects where you want it to go and add that path to your shortcut set.

function MYMODULE_menu() {
  $items['MYMODULE/work'] = array(
    'access arguments' => array('access content'),
    'page callback' => 'drupal_goto',
    'page arguments' => array('admin/work', array('query' => array('date_filter' => 'XXX'))),
    'type' => MENU_CALLBACK
  );
  return $items;
}

This makes MYMODULE/work a valid path for your shortcut set.


How do I add a 'Title' and 'Label How do I add 'Title' to a search Engine? For Section 508 compliance i need to add 'label or 'title' to the following section :

<input placeholder="Search" type="text" id="edit-search-api-views-fulltext" name="search_api_views_fulltext" value="" size="26" maxlength="128" class="form-text" />

I have created funtion.js with the following query:

$(document).ready(function(){

            $('#edit-search-api-views-fulltext').attr('title', 'Search');}

This doesn't seem to be working. View source says:

 <input placeholder="Search" type="text" id="edit-search-api-views-fulltext" name="search_api_views_fulltext" value="" size="26" maxlength="128" class="form-text" />

How do I add a Title?

I think you can better do this with hook_form_alter. Like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
      // alter your exposed form here
    }
  }
}

If you do a var_dump (or dpm if you use devel) on $form, you can easily find out which values to alter.


How to merge WYSIWYG fields from separate nodes I would like to know if it is possible to merge the contents of two separate WYSIWYG fields from separate nodes to create a new node containg both.

Does anybody know of a module that performs this function or something similar, or would this require the writing of a new module?

The use case is for a newsletter, the WYSIWYG fields being populated by articles, and saved to separate nodes. The end result would be a node that contained all articles in a single WYSIWYG field.

Welcome to Drupal Answers. You can use views module with simplenews to achieve above functionality.

Please find simplenews features below.

Sending nodes as newsletters to subscribers
Multiple newsletter categories with separate settings
Per category and multi-signup Blocks and Pages
Subscriber management including mass-subscription and export
Optional E-mail confirmations for anonymous users
Customizable newsletter templates
Support for HTML (including text alternative) newsletter when used in combination with a supported mail system module
Views and Rules integration
Support for multi-language newsletters


Google CSE autocomplete setup I'm new to using Google search on local website installations.

I have successfully installed the Google-CSE module and upon searching, results are successfully displayed from Google.

However, my problem is there are no auto-suggestions when a user begins typing content into the search textfield.

Can anyone tell me how to configure my Drupal textfield to show auto-suggestions when input is typed, please?

PS:

My Google site index has autocomplete enabled.

The solution I used was to copy the scripts/autocomplete.js folder from Googles' GSS module into a custom module, include the autocomplete.js in mymodule.info and imitate the few lines of code in GSS.module which implements the autocomplete functionality.

If you ask me, Google left the CSE unfinished.


How to override node comment form template? I usually override a form template this way.

/**
 * Implementation of hook_theme().
 */
function MODULE_theme() {
  return array(
    'user_login' => array(
      'render element' => 'form',
      'template' => 'user_login',
      'path' => drupal_get_path('module', 'MODULE').'/templates',
    ),
  );
}

I create templates/user_login.tpl.php in my module folder; then, I can override the form.

I tried overriding a node comment form this way, but it didn't work: The node comment form didn't use my custom template file.

I have googled a lot, but I got nothing about overriding a node comment form template.

How can I force Drupal to use a template file for the node comment form?

In Drupal 7, and in the case of the user login form, your trick works because the form doesn't set the #theme property; in that case, Drupal will use the theme function whose machine name is equal to the form ID. (For the login for, that is user_login.)
That is not true for the comment form, for which its form build (comment_form()) sets the #theme property.

$form['#theme'] = array('comment_form__node_' . $node->type, 'comment_form');

There isn't a match between the machine name of the theme the form builder wants to use, and the comment-edit form ID; the latter is comment_node_CONTENT_TYPE_form, not comment_form__node_CONTENT_TYPE. If you were defining a comment_form theme function, that should work.

In Drupal 6, there is no #theme property for comment_form, which is the form ID of the comment edit form.


Adding taxonomy filter at the top of image gallery I've spent some time trying to discover how can i add taxonomy filter at the top of the gallery view in Drupal 7. I've created View called Gallery which contains of images,title and author. In content type I've declared that it is a term reference to Gallery type taxonomy. My purpose is to allow user to sort the image gallery by tag, simple example would be animal gallery, for example:

'all' 'pigs' 'dogs' 'cats'
'image' 'image' 'image'
'title' 'title' 'title'
'user'  'user'  'user'

So far I've created this View of images,title and author, I've no idea how to include taxonomy tags. I hope this explanation is understandable. Any help would be appreciated.

You can create menu block with items/links which you need and then add this block into views header via Views block area module


How to use Rules to send separate email to every user referenced in user reference field? I have a node with a user reference field, in which a user can select unlimited users who they have a relationship with. I'd like for the saving of this node to trigger a separate email to be sent (via Rules) to each user chosen in that reference field, or a single email with all of those users BCC'ed. Currently, the "send mail" action with "node:field-friends-you-wish-to-invite:0:mail" selected in the "To" field of the Rule only sends an email to the first user selected in the list, no matter how many other users have been selected.

How can this be accomplished?

You should create a rule that looks like so (in Rules export format):

{ "rules_send_email_to_selected_email_ids" : {
    "LABEL" : "Send eMail to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to [current-email-id:value]." } },
            { "mail" : {
                "to" : "[current-email-id:value]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details about the above rule:

Rules Event: After saving new content of type "Article" (adapt the type to fit your needs, ie to XYZ).
Rules Action: a "loop" for all selected values of a multi value select list (which contains the eMail IDs), with machine name field_email_addresses (adapt the machine name to fit your needs). For each item (= current_email_id), an eMail is created with some subject and message that also contains the title and url of the node being created. Note: this will send 1 separated eMail to each of the selected eMail IDs (there is no way to send a single eMail to all selected eMail IDs).

If you have the Rules UI enabled, you can import the above rule in your own site, after you adapt the machine names of the content type and the field name containing the list of eMail Ids.

After you're convinced the rule works as expected, you may want to remove the Rules Action that displays a message after the node is saved (with drupal_message).

Video tutorial: have a look at the List and loops video which show a similar scenario.

Update

If you don't have such field with eMail IDs, but a field which is an entity reference field to user ids, then you can use a minor variation of the above rule. Instead of field_email_addresses, you'd want to loop over the list of users (indicated via the user reference field, let's assume it's named field_user_ids). And for each "item" (which I'd name "current_userid"), in the "to" field you'd use the current-userid:mail token for the user being processed. Here is how such rule could look like (in Rules export format):

{ "rules_send_email_to_selected_user_ids" : {
    "LABEL" : "Send eMail to selected user IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-user-ids" ] },
          "ITEM" : { "current_userid" : "Current user ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to eMail ID [current-userid:mail]." } },
            { "mail" : {
                "to" : "[current-userid:mail]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}


Organic Group activity with grouped results I'm currently running a D7 system and want to build an admin-only view of Organic Group activity.

I want that view to have two exposed filters:

Group name
Date posted

In a nutshell  user should be able to select the 'group name' and 'date posted' and gets presented with a list of content which was posted within the group X form 'x date' to 'y date'.

Something like:
Following items has been posted in the group 'X'

news total 32
webforms total 12
galleries total 10

Any help would be much appreciated.

I achieved this by creating two different views and two exposed filters:

Filters
 - Group id
 - Date filter
Views
 - View 1 with content base table
 - View 2 with comments base table

.Then I have used views aggregation to present results


View displays only the title I've got a view for the content type article to display them. I'd like it to display the full content or the teaser.
As a format I've chosen unformatted list.

But whatever I choose (rendered entity/display suite/teaser/full content) I will only see the titles in my view and a read more link.

The body field is Long text and summary but I didn't use the summary so far.
Does anybody know this behaviour? I'm sure it's just a small setting somewhere but I didn't see this before and I ran out of ideas where to search for the solution.

Edit: Even in the content type, everything looks fine. In full content and teaser, all fields are beding displayed.

Just to be sure, navigate to admin/structure/views within your site. Then perform an "edit" of your view. On the next screen, select the "views display" for which you're having this issue. Then verify if all the "fields" that you want to be shown in your view are actually included.

E.g: if you'd only have field "Title" shown in the list of fields (and "Content: Body" is not in the list of fields to be shown), then that would explain your issue. In that case, use the "Add" button next to "fields" to add the fields you want to be added.

Curious to hear if this is the "... small setting somewhere ..." that you were looking for.


How to write a WHERE clause with the '=' operator using db_select()? I have MySQL query as:

SELECT *
FROM `field_revision_field_innostream_state`
WHERE `field_innostream_state_tid` =187
LIMIT 0 , 30

How to write a WHERE condition within db_select?

db_select('field_revision_field_innostream_state', 'innostream')
  ->fields('innostream')
  ->condition('innostream.field_innostream_state_tid', 187, '=')
  ->range(0,30)
  ->execute()
  ->fetchAssoc();


Font Awesome not working in my sub theme of the Open Framework theme I have created a sub theme of Open Framework and everything seems fine, except for the Font Awesome feature. I add the following HTML in a block, but no icon shows up.

<i class="fa fa-facebook-square"></i>

Is there something I need to do in order to enable Font Awesome?

Edit:
I can see the following in the source of my page, and I have verified that the path to font-awesome.css is valid.

<style type="text/css" media="all">@import url("http://www.example.com/sites/all/themes/open_framework/bootstrap/css/bootstrap.min.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework/bootstrap/css/bootstrap-responsive.min.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework/fontawesome/css/font-awesome.min.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework/css/open_framework.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework/css/ie.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework_triangle/css/frontpage.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework_triangle/css/views.css?n2r8cn");</style>

Your html is perfect - I think you probably just need to include the font-awesome.css library file itself.

There are a few ways to do this. I usually just include this in my pages <head> section:

<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

But some people prefer to actually download the font-awesome.css from fontawesome.com, place it in their theme folder and point to that.


How to query for entities without a value for a specific field? Using EntityFieldQuery it is pretty easy to query for entities with a given value for a specific field. But I fail to find a way to query for entities without a value for a given field. Let's say I have an optional Taxonomy Reference field on all my content type. I can query the nodes associated with a given taxonomy term using:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'file')
  ->fieldCondition('field_tags', 'tid', $tid)
  ->pager($limit);
$results = $query->execute();

But how would I query for all nodes not associated with any terms (ie. which have no value for the field_tags field). I tried setting $tid to NULL and $query->fieldCondition('field_tags', 'tid', $all_tids, 'NOT IN') without success.

The SQL implementation of EntityFieldQuery doesn't support this, because it builds the query using INNER JOINs instead of LEFT JOINs. I consider this a bug, please open an issue in the core queue.


Display language in entity reference field I am running a multilanguage website and I have some content types using entity references. Now, the problem is that when I am adding content, if I have two content with the same name but different languages (a product name for instance), I have no way to know which one I am choosing in the entity reference field.
So I want to be able to display language in the entity reference select box. Something like this :

Lorem Ipsum (EN)
Lorem Ipsum (IT)
...

Is there any module I can use for that or some hooks?

You can do this with views. Views allows you to add a "Reference" display. There you can choose how your title or your reference entry should look like. The view can then be chosen from the settings of the node reference field.


How to create a select box field to select from a filtered list of articles? in this example, I want to make the select box to select from a filtered list of articles.

What is the proper way to customize the options available in this select box ?

Step 1

To have such a list of articles that can be referenced, you should first (repeat: first) create a view (with the Views module) to create a list of all the articles that are allowed to be selected. And the display type of such view must be an Entity Reference display.

Step 2

Your select box field (to select from a filtered list of articles) should be field that looks like so:

Field Name = Anything you want, eg field_articles_list.
Field Type = Entity Reference, using these additional settings for it:

Target type = node
Number of values = 1 (probably, though something like "unlimited may do as well).
"Mode" (within "entity selection") = Views: Filter by an entity reference view. However, before you can select an appropriate view at this point (which is eligible to do so), you first need to create a view with an Entity Reference display, or add such a display to an existing view. In your case, you should select the view created in "Step 1".
Pick any of the other options to define this field as you see fit.


How to customise Webform results table So its Christmas eve and this is really dampening the Christmas spirit.

I need to be able to customise the submissions results page table to show the county taxonomy for the submission user.
I have never really done anything with SQL before but I can get all the information I need by running the below select query in phpMyAdmin:

SELECT `sid`, `nid`, `serial`, `uid`, `is_draft`, `submitted`, `remote_addr`,
field_data_field_counrty.field_counrty_tid as CountryID ,

(select name from taxonomy_term_data where taxonomy_term_data.tid=field_data_field_counrty.field_counrty_tid) as Country

FROM `webform_submissions`

inner join field_data_field_counrty  on webform_submissions.uid =field_data_field_counrty.entity_id

And i know that the below code is where it generates the submissions table in webform.submissions.inc:

// Build the list of submissions and load their basic information.
$pager_query = db_select('webform_submissions', 'ws')
// Ensure only one row per submission is returned. Could be more than one if
// sorting on a column that uses multiple rows for its data.
->distinct()
->addTag('webform_get_submissions_sids')
->fields('ws', array('sid', 'nid', 'serial', 'submitted', 'remote_addr', 'uid', 'Country', 'is_draft'));
foreach ($filters as $column => $value) {
$pager_query->condition($column, $value);
}

// Join to the users table to include user name in results.
$pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
$pager_query->fields('u', array('name'));
if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
if (!empty($_SESSION['webform_submission'])) {
  $anonymous_sids = array_keys($_SESSION['webform_submission']);
  $pager_query->condition('sid', $anonymous_sids, 'IN');
}
else {
  $pager_query->condition('sid', 0);
}
}

But i have no idea what to do from there.
If anyone could offer any advice, tips or anything, I would really appreciate the help.

Happy holidays everyone!!

OK, so I solved it myself.

Open and edit the webform.submissions.inc file in the includes folder of the module

In the Return all the submissions for a particular node. section find the code with the comment "// Join to the users table to include user name in results."

 // Join to the users table to include user name in results.
  $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
  $pager_query->fields('u', array('name'));
  if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
    if (!empty($_SESSION['webform_submission'])) {
      $anonymous_sids = array_keys($_SESSION['webform_submission']);
      $pager_query->condition('sid', $anonymous_sids, 'IN');
    }
    else {
      $pager_query->condition('sid', 0);
    }
  }

To add my country section I had to find the table in phpMyAdmin that contained my taxonomy data. In this case it was "field_data_field_counrty" (I've spelled country wrong i know but I couldn't change it after).

From that I figured out that the entity ID was the the user ID in the Users table. This is because I had used the country taxonomy on the registration form.

The syntax for the inner join query is 'Table, Table Alias, Condition, Arguments'.
From that my innerjoin became,

 $pager_query->innerJoin('field_data_field_counrty ', 'fld_Country', 'fld_Country.entity_id = ws.uid' );

The field syntax is 'Table Alias, Field Name', so my field selection became,

$pager_query->fields('fld_Country', array('field_counrty_tid'));

This gave me the country ID number that had been assigned to the taxonomy term. I then had to cross reference that field with the taxonomy data table to retrieve the name of the country the ID referred to. That was done with another innerjoin.

$pager_query->innerJoin('taxonomy_term_data ', 'taxonomy_Country', 'taxonomy_Country.tid = fld_Country.field_counrty_tid' );

This time the field I needed to retrieve was called name. However, 'name' had already been used further up in the original code for the user name. So to add an alias to the field I had to use addField instead of fields. The syntax for addField is 'Table Alias, Field, Alias'. My code became,

 $pager_query->addField('taxonomy_Country', 'name', 'tax_name');

The code as a whole is:

 // Join to the field country table to include Country ID in results.
  $pager_query->innerJoin('field_data_field_counrty ', 'fld_Country', 'fld_Country.entity_id = ws.uid' );
  $pager_query->fields('fld_Country', array('field_counrty_tid'));
  $pager_query->innerJoin('taxonomy_term_data ', 'taxonomy_Country', 'taxonomy_Country.tid = fld_Country.field_counrty_tid' );
  $pager_query->addField('taxonomy_Country', 'name', 'tax_name');

Further down in the code is the section:

 $result = $pager_query->execute();

  $sids = array();
  foreach ($result as $row) {
    $sids[] = $row->sid;
    $submissions[$row->sid] = new stdClass();
    $submissions[$row->sid]->sid = $row->sid;
    $submissions[$row->sid]->nid = $row->nid;
    $submissions[$row->sid]->serial = $row->serial;
    $submissions[$row->sid]->submitted = $row->submitted;
    $submissions[$row->sid]->remote_addr = $row->remote_addr;
    $submissions[$row->sid]->uid = $row->uid;
    $submissions[$row->sid]->name = $row->name;
    $submissions[$row->sid]->is_draft = $row->is_draft;
    $submissions[$row->sid]->preview = FALSE;
    $submissions[$row->sid]->data = array();

In this section I added the line:

        $submissions[$row->sid]->CountryID = $row->tax_name;

To display the data, we now need to edit the webform.report.inc file. Find the section near the top that says,

 foreach ($submissions as $sid => $submission) {
    $row = array(
      $submission->is_draft ? t('@serial (draft)', array('@serial' => $submission->serial)) : $submission->serial,
      format_date($submission->submitted, 'short'),

    );
    if (webform_results_access($node, $user)) {
      $row[] = theme('username', array('account' => $submission));
      $row[] = $submission->remote_addr;

I then added the following line after the format_date section to add my new column after the submitted column.

      $submission->CountryID,

To  add the header for the new column find the section with the comment,

 * Theme the header of the submissions table.

I then added the following line after the submitted section,

    array('data' => t('Country'), 'field' => 'tax_name'),

Save both files and view a webform results page (providing it has a submission).
Your new column should now display.

I hope this helps anyone else that is confused on this subject!

Happy new year everyone!!!


How do I add a CSS class to a form label? I want to add a CSS class to a label on a page that is using Drupal 8 Form API.  I have been unable to find a reference online on how to apply that.
I have used the following workaround, but it produces some strange results.

public function buildForm(array $form, FormStateInterface $form_state)
{
    $form['label1']  = array(
        '#type' => 'label',
        '#title' => $this->t('QUESTIONNAIRE'),
        '#id'         => 'lbl1',
        '#prefix'     => '
',
        '#suffix'     => '
',
    ) ;

and the HTML rendered is:

QUESTIONNAIRE

Not only is the div statement in the wrong place but it is rendered twice.

I had found postings from several years ago that show this was not possible, but I am hoping that since then, and with D8, it has been fixed.
I do not want to do it with prefix/suffix, but as a separate array element.

PS: this site is Drupal 8.0.0-rc2

I know this is an old thread, but for anyone Googling.

The clue to this is in template_preprocess_form_element().

$element += [
    '#title_display' => 'before',
    '#wrapper_attributes' => [],
    '#label_attributes' => [],
  ];

#label_attributes is a standard attribute array, so very easy to set a class with ['class' => ['my-class', 'other-class']]

#title_display takes 3 values:

before: The label is output before the element. This is the default.
after: The label is output after the element. For example, this is used for radio and checkbox #type elements.
invisible: Labels are critical for screen readers to enable them to properly navigate through forms but can be visually distracting. This property hides the label for everyone except screen readers.
attribute: Set the title attribute on the element to create a tooltip but output no label element. This is supported only for checkboxes and radios


Moving Exposed Views Filter into another region of the page Is there any way to move the exposed filters of views into another region of the site? i.e. I want to have a Search functionality attached to the a view by exposing the "Search: Search Terms", but I want the search to reside to the right in the "Right Side Bar" region and not directly above or below the actual Views field display.

Or put another way: Is there a relatively straightforward method of replicating the Exposed Views Filter functionality of one View through another Block that resides on the same page? This way, the Block which would act as the filter "controller" would reside separately from the View on a different region of the page.

There is a module called 'Views Better expose filters' which allows you to create blocks from view exposed filters.

Project can be found at: http://drupal.org/project/better_exposed_filters
or
drush dl better_exposed_filters; drush en better_exposed_filters

There is also some excellent documentation at http://drupal.org/node/766974


Superfish - how to integrate main & user menu together I am using superfish module to decorate the menu system but found one issue. i need to show my "main menu" & "user menu" blocks on header region. so that if user is logged in, they can see all the main menu along with "user menu" otherwise only they can see the "main menu" items such as [home, Games, Blog]. Please suggest some alternative if this approach is not recommended or proper.

Drupal version - 7.23
Bartik 7.23
Superfish module 7.x-1.9

Go to main menu and add My account with path user and add Log out with path user/logout

SO that links will appear as you expected


Problem installing in local "The translation server is offline" I'm trying to install Drupal 8 on my laptop (localhost on a WAMP server), and I always get the following error in the first steps:

  Requirements problem

  The translation server is offline.

  The installer requires to contact the translation server to download a
  translation file. Check your internet connection and verify that your
  website can reach the translation server at http://ftp.drupal.org. Check the
  messages and try again.

That step is mandatory, and I can't continue the installation process. Opening http://ftp.drupal.org, I can see the website with no problem.

I've disabled anti-virus and firewall, and I have tried the process from different locations (different Internet access) on the same computer, with the same result. I'm using EasyPHP WAMP on Windows 8.1, with versions that meet the requirements of PHP, MySQL.

What can be blocking the access to the translation server? Is there any way to omit this step?

I think you didn't select English in the first step, and probably your Internet connection is behind a proxy and I guess Drupal doesn't support it.

You can select English and continue or:

Go to Translation server and download the specific language, the Spanish for example

Copy the download file in sites/default/files/translations
Continue with installation


Is there any hook_node_pre_submit() like hook? I have a Drupal 6 site where I am using the  Webform module. There are business validations written in JavaScript, but users can bypass them by disabling JavaScript.

Is there any hook_node_pre_submit() kind of hook in Drupal 6 that doesn't allows users to submit the form if the validation fails?

I think hook_form_alter is also a good option to overcome this issue. You can validate by altering the webform.

for example:

function mymodule_form_alter($form, &$form_state,$form_id) {
  //dpm($form);
  if ($form_id == 'your_form_id') {

    //validate function call
  }
}


Administration theme for certain roles How do I force certain roles to use exclusively administration theme? These roles are only allowed to add content in administration and there is no problem for that. But some pages, like the user profil page, still use the front office theme and I need them to always use the administration theme. Any good solution for that?

Thanks

You might want to look into the hook_admin_paths function where You can define the pages that should use the administration theme.

For this to work on specific roles just use something like:

function mymodule_admin_paths() {
  global $user;
  if(in_array('administrator', $user->roles)) {
    //Make the changes for the administrator
  }
}


Installation profile similar to openatrium but focusing on projects I'm looking for an install profile (or Drupal based app) similar to Open Atrium, but focus on projects rather than on contacts and tasks; something that is similar to Basecamp.

Not an install profile, but there is a good module for that (6 only), called Storm.


Hook to compare the already saved value of moderation state of node and updated value I'm using Workflow state on a content type.
What is the correct HOOK should I use in my custom module to check if the workflow state of the node changed from value to another value to add some actions.

I Used hook_entity_presave and compared values by using  $entity->original
and $entity


how to default value to select list CCK with form_alter I am usingCCK 2 (2.9), and I know that CCK field give the option to assign the default value using the pipe, for example

Please select|Please select

But I am just curious about if exist a programatically way to assign a default value to a select list. I have several tries, using this kind of syntax:

$form['field_color']['value']['#default_value'] = 'Black'; //or
$form['field_color']['#default_value'] = 'Black'; //or
$form['field_color']['#default_value'][0]['value'] = 'Black';

but nothing. To me not is clear what is the correct syntax.

thanks in advance.

CCK requires a little voodoo to alter values with a hook_form_alter(). You need to implement a special type: after_build, so put this code in a custom.module:

//Declare the callback for after_build for page node form
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'page_node_form) {
    $form['#after_build'][] = 'custom_after_build';
  }
}

function custom_after_build($form, &$form_state) {
  //For a select list you have to modify this to set default to black
  $form['field_select']['value']['#value'][0] = 'black';
  //if your field is multivalued you can put more
  $form['field_select']['value']['#value'][2] = 'red';

  //for a single text it's a little different:
  $form['field_text'][0]['value']['#value'] = 'black';
  //have a look at the form after after_build
  dsm($form);
  return $form;
}

Here are some (a little confusing/complicated but useful) articles regarding this:

hook_form_alter() and CCK fields
FAPI/CCK Confusion: 'value' vs '#value'


How to check if a link field uses  in template I have a Custom Block type.
It has a link field that allows <nolink>
In the twig template for that Custom Block type I want to check if the link field has <nolink>.

I can see there is a protected value under #url for routeName that is NULL when there is a link, and <nolink> when <nolink> is used, but I can't figure out how to check it.

I can also see there's a protected uri under #url with a similar situation. If <nolink> is used, that value is NULL. If there is a link, the link is in there.

Assuming your link field only allows 1 value.

{% if content.field_link.0['#url'].toString() is empty %} # or use "is not empty" if you're checking if there is a url.
    # your code goes here
{% endif %}

If your field allows multiple link values then loop:

{% for link in content.field_link %}
  {% if link['#url'].toString() is empty %} # or use "is not empty" if you're checking if there is a url.
    # your code goes here
  {% endif %}
{% endfor %}


duplicate entry on using commerce_product_ui_product_type_save()? Reference to the code https://www.drupal.org/node/1059624#comment-4083864

 $product_type = commerce_product_ui_product_type_new();

  $product_type['type'] = 'prestation';
  $product_type['name'] = t('Prestation');
  $product_type['description'] = t('A basic prestation.');
  $product_type['is_new'] = TRUE;

  commerce_product_ui_product_type_save($product_type, FALSE);

When I execute the folllowing code given above I get a

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry 'prestation' for key 'PRIMARY': INSERT INTO
  {commerce_product_type} (type, name, description, help, revision)
  VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] =>
  abcs_new15 [:db_insert_placeholder_1] => abcs new15
  [:db_insert_placeholder_2] => abcs new15 [:db_insert_placeholder_3] =>
  [:db_insert_placeholder_4] => 1 ) in drupal_write_record() (line 7239
  of

You are getting the error because you are setting $product_type['is_new'] to TRUE, which is saying to the module the product type is new, but that evidently is not true. That is what the error is telling you.

Set $product_type['is_new'] to FALSE, or don't set it at all, and you will not get any error.

If you are programmatically creating new product types, be sure you give to $product_type['type'] a unique value for each of the product types you create.

Reference

commerce_product_ui_product_type_save()


How to prevent data loss from custom field when using Views Bulk Operations? I have developed a custom field type, widget etc all in its own module.

We also use Administration Views module with Views Bulk Operations.

Our content guys used the VBO action Publish from the Content Overview (Views) screen to mass publish few nodes which have this custom field. This caused data loss from all the nodes, but only the data from my custom field.

What causes this and how to prevent it?

The action does this:

  $node->status = NODE_PUBLISHED;
  entity_save('node', $node);

So the fail is not coming from VBO, you have a bug in your field code. Hard to tell where without looking at it.


Views: Define table without describing it as a base OR join table? The Views API in advanced help says "For Views to use your table, it has to either be a base table, or know how to link to an existing base table. Or sometimes both. "

I'm trying to add an "address" table to joins to the "person" table. The "person" table is a base table, "address" is not.

I can do this:

  $data['address'] = array(
    'table' => array(
      'group' => t('Address'),
      'join' => array(
        'person' => array(
          'left_field' => 'id',
          'field' => 'personID',
        ),
      ),
    ),
  );

However, this creates an implicit join relationship in views, meaning it will automatically make all fields in the "address" table available to the view and join the data with LEFT JOIN.

What I want to do is instead just add a relationship handler to the "personID" field so that the relationship is explicit, meaning a user must manually add the relationship.

I have successfully added this relationship handler to the "personID" field, and I can add the relationship. When adding the fields from this table, I can chose to use the relationship to add the field instead of the implicit relationship.

I want to completely remove the implicit relationship, and only allow users to add the data from the relationship handler. When I remove the 'join' data above, views won't allow me to add the relationship manually.

Is this possible? Or does that require that I define my joined table as a base table as well?

You should be able to add a relationship by using hook_views_data. You should however not use the join, but the relationship (right below the huge php comment on the linked page):

// Node ID table field.
$data['example_table']['nid'] = array(
  'title' => t('Example content'),
  'help' => t('Some example content that references a node.'),

  // Define a relationship to the {node} table, so example_table views can
  // add a relationship to nodes. If you want to define a relationship the
  // other direction, use hook_views_data_alter(), or use the 'implicit' join
  // method described above.
  'relationship' => array(
    'base' => 'node', // The name of the table to join with.
    'base field' => 'nid', // The name of the field on the joined table.
    // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
    'handler' => 'views_handler_relationship',
    'label' => t('Default label for the relationship'),
    'title' => t('Title shown when adding the relationship'),
    'help' => t('More information on this relationship'),
  ),
);


How to set up multiple hierarchy taxonomy? I am struggling to find the solution for the following situation: I am building a tourism site with POIs as nodes (Drupal 7). The POIs are categorized/tagged in a State-County-City hierarchical vocabulary. I want to add two another cathegories - Historical region and Tourism region. Each City belongs to exactly one historical region and one tourism region and these regions do not cover the same area (meaning that e.g. two cities belong to the same county, but to different historical and tourism regions). While creating new node/POI the user/editor selects the State-County-City via Simple Hierarchical Select module (this structure is generally well-known) and I want to automatically assign the corresponding Historical and Tourism region to the node, based on the City selected (as the division into Historical and Tourism regions is not obvious for the general userbase, but I have the corresponding database available).

How to generate the relationship between the terms for Cities in the State-County-City vocabulary with the corresponding Historical and Tourism regions, while maintaining the possibility to list all nodes/POIs in a State/County/City/Historical region/Tourism region?

I have thought about having two additional vocabularies but failed to find a way to connect them with the City terms in the first. I also thought about having multiple parent terms in one vocabulary for the Cities - but this messes up the vocabulary (and Simple Hierarchical Select) completely and is therefore inapplicable. Any help appreciated.

It's quite simple:

State-County-City hierarchy you have figured out
Create separate taxonomy for regions
Go to /admin/structure/taxonomy/*/fields and add a taxonomy field to terms in first tree. That way you will be able to assign cities, counties and states to regions

Later, you will have to switch to Views for display, as regular taxonomy pages will not be enough to display nodes by historical region - but that's for another question.


Why I should use dependency injection in Drupal 8? Why is this

__construct(MyService $my_service ) {
   $this->my_service = $my_service;
}

create (ContainerInterface $container) {
  return new static(
      $container->get('my.service'));
}

better than

__construct() {
    $this->my_service = new MyService();
}

?

From Services and dependency injection in Drupal 8:

  ... is best practice to access any of the services provided by Drupal via
  the service container to ensure the decoupled nature of these systems
  is respected.

A clear example can be found in Drupal 8 Dependency Injection, Service Container And All That Jazz:

  Take the following simple class:

class Car {

  protected $engine;

  public function __construct() {
    $this->engine = new Engine();
  }

  /* ... */

}

  When you instantiate a new class Car you go like this:

$car = new Car();

  And now you have an object handler ($car) that has an $engine property
  containing the handler of another object. But what if this car class
  needs to work with another engine? You'd have to extend the class and
  overwrite its constructor for each new car with a different engine.
  Does that make sense? No.

  Now consider the following:

class Car {

  protected $engine;

  public function __construct($engine) {
    $this->engine = $engine;
  }

  /* ... */

}

  To instantiate an object of this class, you go like this:

$engine = new Engine();
$car = new Car($engine);

  Much better. So now if you need to create another car using another
  engine, you can do so easily without caring about the Car class too
  much since it is supposedly equipped to work with all the engines in
  your application.

$turbo = new TurboEngine();
$car2 = new Car($turbo);

  And that is dependency injection. The Car class depends on an engine
  to run (dooh), so we inject one into its constructor which then does
  what it needs to do. Rather than hardcoding the engine into the Car
  class which would not make the engine swappable. Such constructor
  injections are the most common but you'll also find other types such
  as the setter injection by which we would pass in the engine through a
  setter method.

  So there you go. Dependency injection is a very simple concept that
  has to do with the practice of decoupling functionality between
  classes. By passing dependencies to objects we can isolate their
  purpose and easily swap them with others. Additionally, it make is
  much easier to unit test the classes individually by passing mock
  objects.


No results because of relationships, unless "Bypass content access control" is selected I have a view that lists faculty members in a table. Everything was working fine until I decided to go into incognito mode to view the table. It wasn't rendering anything at all. So I went back and tried a few things:

Since it was a view/display issue, I thought it was caused from the permissions. So I changed all the permissions to access: none (and a bunch of other combinations). This didn't seem to be the issue.
Selecting Bypass content access control worked fine, but I don't want to use this because of the security implications.
Getting rid of the relationships works, but I need the relationships.

Note that this view works if I am logged in as administrator user; it doesn't work when I am in incognito mode (logged out/anonymous user). So I suspect it is a permission issue (given that "Bypass content access control" worked), but I am not really sure.

I have 6 different pages in this view.

https://www.drupal.org/project/commerce/issues/1276450

The above link solved it for me (#5: Disable SQL Rewriting).


Issue license without an order I'd like to issue free Commerce Licenses to files for users of certain roles without creating orders.

I haven't been able to find a tool for this in the Commerce License UI. Have I missed it? Or is it possible to create such a tool without having to code?

Thanks in advance for your answers

I'm not sure if this solution applies to your specific case, but on my site, I award a role with the license.  So, when I want to "give away" a license without creating an order, I just add the role to the account.  Or, I use the Rules and Flag modules to flag a user (and there is a rule that automatically adds the role).

If you really wanted a license, you could also probably use Rules to create an order and fill it with dummy information, then award the license that way.  Commerce License has decent Rules module integration, so you can get pretty far without any coding.