Enable/ disable „Display author and date information“ per node? It is passible to enable or disable the „Display author and date information“ for each node depending on the content of a field?

The base:

Drupal 8.3.0 (rc2)
field „Where to publish“

Case 1: field „Where to publish“ = „public“
Case 2: field „Where to publish“ = „internally“

-> in Case 1: disable „Display author and date information“

-> in Case 2: enable „Display author and date information“

How can this be realized? Is that possible?
Or should I use two different content types?

First part runs:

function kanu_preprocess_node(&$variables) {
if ($variables['node']->getType() != 'test') {
    return;
  }
$field = $variables['node']->field_where_to_publish;
}

Completed it returns an unexpected error:

function kanu_preprocess_node(&$variables) {
  if ($variables['node']->getType() != 'test') {
      return;
  }
  $field = $variables['node']->field_where_to_publish;

  if (!field->isEmpty() && $field->entity->label() == 'public') {
     $variables['display_submitted'] = FALSE;
  }
}

You can override the variable display_submitted in a preprocess hook:

mytheme.theme:

function mytheme_preprocess_node(&$variables) {

  // check if this is the right content type where the field exists
  if ($variables['node']->getType() != 'article') {
    return;
  }

  // plain field
  if ($variables['node']->field_where_to_publish->value == 'public') {
    $variables['display_submitted'] = FALSE;
  }

  // taxonomy field
  $field = $variables['node']->field_where_to_publish;
  if (!$field->isEmpty() && $field->entity->label() == 'public') {
    $variables['display_submitted'] = FALSE;
  }

}


Restrict access to parts of admin pages I've setup a site for a client I want them to have access to edit content, but some of the permissions grant too much control for my liking. Can someone give me a way to be a bit more selective with permissions. These are my areas of interest.

I have a custom block which contains 2 editable fields, To allow access I have to grant access to Administer Blocks, which give the user access to reposition the block, I would like this to disabled, and also the Regional and Visability settings to be disabled.
When editing a Basic Page node, I have an image field which I dont want the user to be able to adjust.

Any clever people out there know the answers?

The only way I can think of is to implement hook_form_alter() and add the "#access" property to the form fields you don't want to be accessible from the user.
Normally you should use code similar to the following one, but every function that returns FALSE when the current logged-in user should not access the form field would work too.

$form['form_field']['#access'] = user_access("access form_field");

The permission the code checks can be any of the permissions the module implements, or other modules implement.


Add a span and class to menu items that has children I'm customizing the main menu using the Menu Block Module. I need to set a class for all li elements that has children regardless of level. I might need to add a span inside the a-tags as well. Is it possible to do this in the template.php or do I need to alter module files. I would preffere not to edit module files if possible.

Like:

   Menu item name

Is this doable with some:

function theme_menu_link(array $variables) { ...?... }

[edit]

Menu items with no children has the class="leaf". It should be possible to style the menu items li (has children) and then cancel the rule-set for the class li.leaf (has no children). The span can be added by using some li::after rule-set and removed with eg li.leaf::after {display:none;}

In this way it can be solved with CSS only. The problem is I need to use the   for a click event. So at least I need a real span inside the li a witch is not a "leaf".

Anyone who can help me with a theme functions for this?

Menu items with no children has the class="leaf". It is possible to style the menu items li (has children) and then cancel the rule-set for the class li.leaf (has no children).

A span can be added to all li's (set to display:none for leafs).
How do I insert a <span> </span> tag inside the <a> </a> tag on my main menu


How to embed a comment in an entity-field query In reviewing the slow query log, some of them are entity-field queries. With a normal select query, I can have something like:

$query = "/*" . __FILE__ . ":" . __LINE__ . "*/ SELECT...

and with pdo object notation, I can add

->comment(__FILE__ . ":" . __LINE__)

but how do I add a comment to an entity-field query? Apparently comment() is not a valid method.

Provide the comment information via EntityFieldQuery::addMetaData, and then add the comment to the query in hook_entity_query_alter().


In a Views template, how can I mimic the effect of "Link this field to its taxonomy term page"? I have a view of taxonomy terms that displays Fields, including Taxonomy term: name and Taxonomy term: Term ID.

I am attempting to use a views template to customize the output of this view.

In the Views UI, if I click Taxonomy term: name, I can get an option to Link this field to its taxonomy term page.

I would like to use the link generated by this option in my views template output.

However, when I dpm($row), only the term name and term ID are returned.  How does Views create the link to the taxonomy term, and how can I mimic this in my template file?

One easy-ish way to do that within the Views UI is with the option:

"Rewrite the output of this field"

Add term id field Check "Exclude from display"
Order the field so it's above the other fields
Edit the field you want to convert into a link
Check "Rewrite the output of this field"

e.g

[name]

to create a link.

You can also add a global "Custom text" to add arbitrary text using the replacement tokens there as well.

In that way, tokens from your view fields can be made available as replacement pattern options in your View.


How to Collapse "Locale settings" (TimeZone) in User Profile with hook_form_FORM_ID_alter(); I cannot seem to get "Locale settings" fieldset to collapse using hook_form_FORM_ID_alter().

Here is what I've tried so far.

function fsrsys_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['timezone']['#type'] = 'fieldset';
    $form['timezone']['#collapsible'] = TRUE;
    $form['timezone']['#collapsed'] = TRUE;

    $form['#after_build'][] = 'user_profile_form_afterbuild';
}

function user_profile_form_afterbuild($form, $form_state) {
    $form['timezone']['#collapsed'] = TRUE;
    //dd($form['timezone']['#collapsed']);  // <-- shows '1'
    return $form;
}

The fieldset is still 'open.'

For good measure, I've cleared both the Drupal cache and the browser cache twice.

What am I doing wrong?

This is a bit of a hack but it worked for me.

My desired effect was to have the Locale Settings start out collapsed and be expandable, every other solution out there suggests just "turning it off".  I still need to use the Locale settings though.  Anyway!!! Execute this jquery on the edit user profile page ( I inserted it using a hook_form_alter):

(function($){
  $(document).ready(function(){
    $('#edit-timezone .fieldset-wrapper').toggle();
    $('#edit-timezone').addClass('collapsed');
  });
})(jQuery);


Drupal 6 - specific template if node contains specific form element I am trying to do a check for if some node contains an input element of type = hidden and with value = 'something'. If this is the case, some specific template should be used for the template.

I am trying to do this check in template.php using the template_preprocess_node() method where I have access to the $vars ($vars['node']) variable. However the only solution I can come up with is to loop through $vars['node']->webform['components'] and to check for the input type and after that the value.

However I dont find this approach elegant, what are my options?

The relationship between nodes and webform components is maintained in the webform_component table so you should be able to get the data directly from there:

$sql = "
  SELECT COUNT(*)
  FROM {webform_component}
  WHERE nid = %d
  AND value = '%s'
  AND type = 'hidden'";

$args = array($vars['node']->nid, $field_value);

$count = db_result(db_query($sql, $args));

if ($count > 1) {
  // The webform has a hidden field with the correct value
}


Put class error when I use validate I am working with the Metatags module, and I have these fields.

I need that looks like as in the following screenshot, when the fields meta description and meta keywords are validated.

This is my code, I don't know how can include the class error and put the * symbol.  My question is related with styles.  I want the field keywords and description looks as fields required for the user.

mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {
    $form['#validate'][] = 'mymodule_test_validation';
  }
}

function mymodule_test_validation($form, &$form_state) {
   if (($form_state['values']['metatags']['description']['value'] == '')) {
        form_set_error('Description', t('field is required'));
      }
      if (($form_state['values']['metatags']['keywords']['value'] == '')) {
        form_set_error('Keywords', t('field is required'));
      }
}

If the only validation you are looking for is to make sure the fields are required, then you don't need to call to a validation function. The solution in that case will be to set the "required" attribute to TRUE for the fields description and keywords in the "form_alter" function. This solution will give you the style you are looking for in the required fields.

Something like this (this is a proof of concept):

mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {
    // Make META DESCRIPTION required
    $form['metatags']['description'] = array('#require' => TRUE,);

    // Make META KEYWORDS required
    $form['metatags']['keywords'] = array('#require' => TRUE,);
  }
}

To get the right field names do the following:

mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {

   print_r($form);

  }
}


How can I validate a fieldset or any other kind of group in drupal Form API? I want to create a survey witch contains a couple of questions for every group. For example: I have a group about dogs with 5 difference question (every question has 3 options) and I have a group about cats with difference quetions. Now I want to validate by group. for example making it require to answer at lease two quetions on each group. How Can I do it?

You could do it with custom code by implementing hook_form_alter() and then adding a custom validation function and checking for the relevant field values (I don't know anything about your form so I'm not going to write any code).

Or, you can use the field validation module, which allows you to configure via the drupal UI, extra field validation requirements.

It is a very flexible module and a couple of its validation options are:

Require some of several fields (in the field validation extras sub-module).
Require at least one of several fields

There are many more options so it would be worth playing with it to see if you can achieve what you want.


I want to get the real password(not md5 encryption) when edit the account profile via user profile form and save. how to do that? Possible Duplicate:
  How can I get the real password via hook_user_update()?

I want to change the current user password, and get the new password(the real password, not md5 encryption) when edit the account profile via user profile form(e.g.: example.com/user/1/edit) and save. would anyone can tell me how to do that? I tried using hook_user_update(), but it didn't succeed.

You cannot decrypt the password due to security reasons. Drupal 7 uses SHA512 by default with a salt. It will perform multiple hashes on the password. It's highly impossible to decrypt password.

See the better explanation provided here.

To reset the password see the solution provided here.


Change node configuration dashboard UI settings While creating a node content Drupal 8 provides the following settings.

I want the URL path setting tab to be open by default.

I want to achieve it through the Drupal 8 backend customization settings (more preferable) or even Javascript/jQuery.

You can't do this in the UI, you need code.

You could attach some JS to open it, but it's much easier to create a module with a form_alter and then you can make the element expanded by default.

https://api.drupal.org/api/drupal/core%21modules%21path%21path.module/function/path_form_node_form_alter/8.2.x defines the element, you can see that it defaults to open when there is an alias already.


index doesn't update I'm using Drupal 8's built-in search and it will not update the index.

I have cron running every 15 minutes and even tried running it manually but the search status page always says:

"0% of the site has been indexed. There are 80300 items left to index."

Another odd thing is that some nodes appear to be indexed, even though the status report says zero, because some (but not all) nodes will appear when searched for.

Any ideas what's going on?

This issue is solved. The issue was a malformed URI that was imported from the Drupal 6 website. The search indexing failed when it encountered this content (comment).

It turns out that it was old spam comments from the D6 site. I was able to delete those and indexing is working now.


How do I include a custom JavaScript file in a module? I want to include a custom JavaScript file in a module using the following code.

function profile2_form_user_register_form_alter(&$form, &$form_state) {
  drupal_add_js('http://localhost/prf2.js', 'external');
}

I then add scripts[] = js/prf2.js in the .info file, but it throws this error.

  Warning: file_get_contents(js/prf2.js): failed to open stream: No such file or directory in drupal_build_js_cache()

This is the right & simple way to include any JS file in Drupal 7.

Create a folder named i.e. js, inside your module folder.
Inside that folder place (modulename).js file.

Note: Drupal JS code has a specific format as follows:

(function ($) {
  $(document).ready(function(){
    alert("Hello world!");  //here we can add our JS code
  });
})(jQuery);

Open (modulename).info file & add:

scripts[] = js/(modulename).js
Clear Cache & Run.


Why does file_create_url() not work for theme images? With the latest Drupal 6 update, file_create_url() stopped working for all the files other than public or private files.

I think the assumption is that a file must be either in the public files or in the private files directory.

How can I get the image URL for those images that are in a theme or a module directory?

You don't need file_create_url() to turn those URIs into a URL to use in theme_image().

For theming images in Drupal 6, just supply a path string relative to base_path() (the base of the Drupal install directory). For module/themes this can path can be retrieved with drupal_get_path().

For example:

//Render an image under the admin_menu project
print theme('image', drupal_get_path('module','admin_menu').'images/bkg_tab.png'))


Clearing cache removed all styling I'm fairly new to Drupal, but when trying to install a new module, I was instructed to clear the cache. Now, all of the styling on my website is missing and I don't know what to do.

The webserver must not have the correct permissions to access those CSS and JS files. You need to set the correct permissions on the /sites/default/files/css and /sites/default/files/js directories. Allow read access at the very least.


How to redirect to a specifi page of a view? Here is the code of a custom form:

  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;
    $status = parent::save($form, $form_state);
    $values=$form_state->getValues();

some code here...

    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this->t('Le service « %label » a été ajouté.', [
          '%label' => $entity->label(),
        ]));
        break;

      default:
        drupal_set_message($this->t('Le service « %label » a été modifié.', [
          '%label' => $entity->label(),
        ]));
    }

    $form_state->setRedirect('view.services.page_2');
  }

The redirection doesn't work!
After validating my form, it goes to the first page of my view.
By the way, these two pages of the view are displayed as two tabs in a menu (the first being the default one)...

The solution has two parts:
1. The button that takes to my form in 'Add' mode was coded this way: Ajouter (/services being the first tab I mentioned).
So I removed the ?destination=services
2. Looking at the 'Routes info' provided by Devel, I got that:

So i changed my code to $form_state->setRedirect('view.services.page_2', ['arg_0' => $iSeliste]);  (thanks to the last comment of this page)

And now it works!


limit amount of upload images (through imagefield module) to only 1 by code/programmatically I use image field with possibility to upload unlimited images. BUT under the user registration, I want to limit the possibility to just one image. So that the anonymous user, who wants to become a registered user, can only upload one image. After they become users, then they can upload as many images as they wish.

Does anybody know how to do that?

You want to use a hook_form_alter to process this for just that form, ex.

function mymodule_form_alter(&$form, $form_state, $form_id) {

    if ($form_id == 'user_register') {
        // do stuff here
    }

}

The 'stuff' is the real challenge, especially since you are allowing for unlimited uploads. There is a previous post on this with a solution for a limited set (<10):

https://stackoverflow.com/questions/5701488/change-fields-number-of-values-per-role

My suggestion for resolving this (though not ideal) would be to add a custom handler as part of your logic that would check to see if one already exists and gently prod them not to add more than one.

if ($form_id == 'user_register') {

    $form['<image field name>']['#element_validate'] => array('_mymodule_only_one_image'),

}

and then for your validation function, you could simply test whether a 2nd image exists and prod the user to only submit one. Rough psuedo-code example here, haven't tied this to an actual form.

function _mymodule_only_one_image($element, &$form_state) {

    if (!empty($element['<image_field_name>'][1])) {
        form_error($element, t('Please only upload one image');
    }

}

Another option would be to try and disable the ajax handler that initiates the 2nd upload through your own custom jquery override, which you could also add in to this custom form through the above form_alter.


Adding existing contact form in another page There is a contact form in the contact page, which is perfectly working fine.
I want to add the same form in a different page (say product page).
How can I do that in Drupal 8?

You could use Contact Block module which will allow you to place a contact form block on whatever page and region you desire.

Once installed place a block as usual and filter for contact block, then in the block configuration settings you can choose which contact form to use. You can also add pages to display the block, remember to add pages with a slash "/my-pages-path"


Install and Configure XHProf (Ubuntu) Problem

I'm trying to use XHProf but I'm getting horrible php error every time it runs.

Warning: Invalid argument supplied for foreach() in xhprof_compute_inclusive_times() (line 1670 of /var/www/drupal/sites/all/modules/XHProf/xhprof.inc).
Warning: Invalid argument supplied for foreach() in xhprof_compute_flat_info() (line 1644 of /var/www/drupal/sites/all/modules/XHProf/xhprof.inc).
Warning: Invalid argument supplied for foreach() in theme_xhprof_overall_summary() (line 367 of /var/www/drupal/sites/all/modules/XHProf/xhprof.module).

The problem is solved here because the temporary folder doesn't exist, however mine does.

Set-Up Server Side

I'm running a fresh Ubuntu Server 13.04 with Drupal 7.

Install xhprof using pear following the instructions here.
I also added a temporary directory to php.ini, which I created manually.

extension=xhprof.so
xhprof.output_dir="/var/tmp/xhprof"

Drupal Set-Up

I have both the devel installed and I also installed the XHProf module.

In admin/config/development/xhprof, I enabled profiling of all page views and drush requests.

On following an xhprof link I get the error above.

Good god Batman. That was incredibly frustrating. Here's a guide to getting xhprof working. (Note: I am very new to Linux. I'm not sure if the permissions I use are safe, or whether there is a better way of doing it. I'd only do this on a test environment.)

IMPORTANT: It won't tell you anything about how to interpret it. I have no idea how to, I'm just happy it works.

Getting XHProf Working

1. What operating system are you running?

Mac or Linux?

It's possible.

Windows?

Probably not. To run xhprof on windows you have to have a compiled dll. There's a link to one in this thread, but I always had compatibility issues with it when I tried to use it on XAMPP.

I think it was compiled with a different version of Apache.

2. Getting it working on Ubuntu

It's possible on Mac. Here are two useful links:

http://www.lullabot.com/blog/article/installing-xhprof-mamp-and-php-52-mac-os-106-snow-leopard
http://www.midwesternmac.com/blogs/jeff-geerling/getting-xhprof-working-well

But I haven't done it. I managed to get it working on Ubuntu Server 13.04, although I think any recent version of Ubuntu Server would work.

I set-up my server on VirtualBox. VirtualBox is free but it might take a bit to learn how to set it up.

3.Installing XHProf

I'm going to assume we have a fully functioning Ubuntu Server.

First we need to install pear. We'll use this to install XHProf.

sudo apt-get install pear

We follow this up with phpdev which is also needed.

sudo apt-get install php5-dev

If these commands don't work and I've got them wrong, just go straight ahead with:

sudo pecl install -f xhprof

Ubuntu will tell you what you're missing and give you the prompt to install it. Once you've got all the dependencies install xhprof.

You might get an error on installing xhprof, it'll try to download the beta and fail. In that case try:

sudo pecl install -f xhprof-beta

Hopefully xhprof is now installed.

Now we need to configure it. Open your php.ini which is at /etc/php5/apache2/php.ini
and add the following two lines under the extensions section:

extension=xhprof.so
xhprof.output_dir="/var/tmp/xhprof"

The second line sets the output directory. If this folder doesn't exist you'll have to create it.When you've done that reboot apache using

sudo service apache2 restart

4. Checking if XHProf is running

Now we need to check if that worked.

Test 1:

Enter php -m

If you see xhprof in the list you're good to go. If not, don't worry, try this instead to check if it's working:

Go to your webroot /var/www/ and create a php file with only:

phpinfo();

Save it as phpinfo.php. Open this in your browser and you should see PHP information. Search for xhprof and if you see this then it's running.

5. Getting it working with Drupal

I couldn't get it working with the Drupal module. So instead I'm going to tell you how to get it working with the devel module.

First some config that I borrowed from here. I didn't really follow this part, but it works so gift horse and all that.

Create a new config file with the following command:

sudo nano /etc/apache2/conf.d/xhprof.conf

and insert the following code.

alias /xhprof_html "/usr/share/php/xhprof_html/"

Then we possibly need to create a symlink to our xhprof_html folder. So just in case set this:

ln -s /usr/share/php/xhprof_html /var/www/xhprof_html

This will create a folder in your webroot that points to the existing xhprof file. Then in your browser you can open http://mywebsitehere.com/xhprof to see all the runs you've made.

Then restart apache. Now it's time for a little devel config. Go to the devel settings, enable xhprof and set:

xhprof directory = /usr/share/php

XHProf URL = /xhprof_html

Now at the bottom of each page you should see a little link to xhprof.

And clicking it should take you to a page that looks like this. You're done. Congratulations!

If that didn't work and you're getting run errors it's probably because Drupal doesn't have permission to write to the tmp folder that we set earlier so enter:

sudo chown -R www-data /var/tmp/xhprof

And hopefully that works. We're done. Hoorah!

Unless you want graphing functions. Thankfully that's as easy as:

sudo apt-get install graphviz
sudo service apache2 restart

And now you should have graphing functions. Hopefully that helps!


how do i link a field to another field in views I have a Views on which I display an event calendar. Events get created through a separeate content type which contains a checkmark "Link to page" which will (if checked) display a "view" link in the table which links to the created content. Now i have added another field in the content type of type text "External link {will link to current page if left empty)" which should override the linkage to the current page and render the "view" link to link to the url entered in "External link" field. How would I do this?
Please advise!
Thanks!

edit 1

No, I currently hacve a checkbox that creates a link whichj links to the current content but nothing that woul consider the newly added field "External link (will link to current page if left empty)"...
How do I can I do this?

In theory, you should be able to use the link module to create a link field within your content, and use a default value pointing to the newly created content - this may require some customization of the code - it accepts tokens, but I don't know if the node id has been assigned at that point or not.

Assuming it works, one way or another, you would then simply include that field in the view, which should display as a link - if it is used, it would link to the external link, otherwise to the content (as default value).

If that isn't reasonable, you could try to use the same field (without modifications or default value) in the view, and create a NO RESULTS BEHAVIOUR that rewrites it to the content - meaning if there is no value in the field, it would link to the content, or use the value of the field (external link) if present.


Menu Block: Expand all children of this tree - ignored? Is anybody using Taxonomy Menu + Menu Block? I have a problem setting Expand all children of this tree, in that it seems to be completely ignored. My sidebar taxonomy menu lists all children expanded, regardless of the setting value.

Since I don't see the problem in issue queue for the project, I assume this could be only a local problem. It might be that I am overlooking some other module that could be causing that.

Open for your insights, please.

I had the same problem... Bug was dependant of my theme which have a theme_menu_link preprocess function. If I delete this function and clear cache, menu block works as designed.
To be quickly sure, enabled bartik and look the behavior of your menu block.

@see http://drupal.org/node/1425342#comment-5679426


Overwrite custom node view fail I've created a function that have custom content type and all went well, but the problem is now I'm unable to overwrite the node view page:

Here are my functions:

function xxx_theme($existing, $type, $theme, $path) {
  return array(
    'xxx_print' => array(
      //'variables' => array('node' => NULL),
      'function' => 'theme_xxx_print',
    ),
  );
}

function theme_xxx_print($node) {
  return '
test
';
}

If you are using panels node view template for your node view then your template file and node theme declarations would be overruled by panels.

If you want to verify, disable the panel node view. Make sure to flush your caches then visit a node you have and your theme override/addition will be there.


Show full content of related entity using Entity Reference in node view Basically I've created a relationship between two content types: Testimonials and Case Study as follow: in Case Study I've created a field Testimonial using the Entity Reference widget.

When I create a case study type of content I can choose a Testimonial to link with this case study. So far so good.

My question is this: When I view the newly created Case Study content, I can only see the title of testimonial but none of the additional field available in the testimonial content type.

In order to view the full content, do I need to create a View for it or is there a way to display the full content as it is?

Thanks

You don't need a view for this. Instead, you can set the display settings for your entity reference field to Full display.
On Structure > Content types > My content type > Manage display, for the entity reference field choose Rendered entity as format. You can then have Full content as a view mode.


How can I force HTTPS for all images? I'm moving my Drupal 7 website to https but I keep having issues with some images that gets loaded with full path, but with http://. For example the site logo and view images have http:// path. (Inside DB table file_amanged files are all saved with public:// path.) They are all files loaded through the Drupal UI.

How can I force all images to use https?

You need to use a module like Pathologic which will force protocol relative URLs for all assets.

https://www.drupal.org/project/pathologic

The public:// path is a stream wrapper, and has no effect on whether the browser sees http/https or not. Pathologic will fix all of this for you.


D6 to D7 upgrade error Invalid datetime format Incorrect integer value After upgrading a D6 to D7 site. I get this error when trying to save an existing page on the site that has uploaded image files, and the page will not save. If I remove the uploaded files, the error goes away and I can save the page.

  PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect
  integer value: '' for column 'field_upload_inline_image_width' at row
  1: INSERT INTO {field_data_field_upload_inline_image} (entity_type,
  entity_id, revision_id, bundle, delta, language,
  field_upload_inline_image_fid, field_upload_inline_image_alt,
  field_upload_inline_image_title, field_upload_inline_image_width,
  field_upload_inline_image_height) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7, :db_insert_placeholder_8,
  :db_insert_placeholder_9, :db_insert_placeholder_10); Array (
  [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 37
  [:db_insert_placeholder_2] => 25955 [:db_insert_placeholder_3] => page
  [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
  [:db_insert_placeholder_6] => 24 [:db_insert_placeholder_7] => NNSA
  Headquarters [:db_insert_placeholder_8] => [:db_insert_placeholder_9]
  => [:db_insert_placeholder_10] => ) in field_sql_storage_field_storage_write() (line 514 of
  /var/www/html/upgrade2a/modules/field/modules/field_sql_storage/field_sql_storage.module).

This is my table structure field_upload_inline_image, do i need to alter the Type or Null column?

entity_type (Primary) varchar(128)  No The entity type this data is attached to
bundle varchar(128) No The field instance bundle to which this row belongs, used when deleting a field instance
deleted (Primary) tinyint(4)    No 0 A boolean indicating whether this data item has been deleted
entity_id (Primary) int(10) No The entity id this data is attached to
revision_id int(10) Yes NULL The entity revision id this data is attached to, or NULL if the entity type is not versioned
language (Primary) varchar(32)  No The language for this data item.
delta (Primary) int(10) No The sequence number for this data item, used for multi-value fields
field_upload_inline_image_fid int(10)   Yes NULL The file_managed.fid being referenced in this field.
field_upload_inline_image_alt varchar(512)  Yes NULL Alternative image text, for the image’s ’alt’ attribute.
field_upload_inline_image_title varchar(1024)   Yes NULL Image title text, for the image’s ’title’ attribute.
field_upload_inline_image_width int(10) Yes NULL The width of the image in pixels.
field_upload_inline_image_height int(10)    Yes NULL

I'm using Media 7.x-1.5 Bundled with File entity 7.x-1.5. I am not using UUID module.
maybe I need to then I will need
the file_managed table is missing the uuid column

I should have posted the answer here instead, it may help someone. This is fixed. I had missing images in the /sites/default/files/ folder. This was a upgraded d6 to d7 site with 4000 nodes and many images. I did not have the latest images in my files folder. So saving a node with uploaded cck field images threw this error.


Using OCI8 Module to See OracleDB I have an external oracle db I'd like to use to show data in views. Has anyone used the OCI8 module, if so, (sorry for my ignorance) how do we see the data? Do I need to create a custom module and hook into it? I cannot find any how to on this.

The readme says: 1) Build out OCI8OracleSelectQuery class which will mimic Drupal's SelectQuery. This would include writing an oci8_db_select() function to create these

Where do I do this? Thanks!

That module provides a very basic API only; no UI, no methods to display/format data, and no integration with the Views module.

It currently provides developers with:

A database connection class for Oracle
A simple Oracle-specific version of db_query
A simple Oracle-specific version of db_query_range

and literally nothing else.

So yes, in order to see any data using this module, you're going to need to create your own module which uses the couple of query functions it provides, and displays the results in whatever way makes sense.

For something more automated, you could try the technique mentioned here to hook into Views and force it to use a different database for certain tables (which can theoretically be in an Oracle DB). I've never tried that so I can't comment on its effectiveness, or if it's genuinely even an option. Something tells me that you'd need a PDO connection to Oracle for that to work, but I might be wrong.

As an aside, the line you quoted from the readme looks like a TODO note; the maintainer is probably saying that the functionality hasn't been implemented yet, but that developers who want to make proper use of the module will probably find it beneficial to implement that per their requirements.


Webform skip page programmatically I know how to hook_alter a Webform build form.
I also know how to validate it using a hook_validate.

Is there a chance to skip a certain Webform page when some validation code results in false?

I cannot find any solution ;-(

I has just found a solution for it. Perhaps, somebody can find more pretty realisation.

So, first step:
Lets your 'hook_node_view' in custom module call early than webform 'hook_node_view', you can do it through hook_module_implements_alter() something like it:

function YOUR_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    if(isset($implementations['YOUR_MODULE'])){
      $group = $implementations[YOUR_MODULE];
      unset($implementations[YOUR_MODULE]);
      $implementations = array_merge(array(YOUR_MODULE => $group), $implementations);
    }
  }
}

Second step:
Remove unnecessary webform components from node object.

function YOUR_MODULE_node_view($node, $view_mode) {
  if (isset($node->webform['components']) && YOUR_CONDITION) {
    foreach ($node->webform['components'] as $key => $component) {
      if ($component['page_num'] == 2) {
        unset($node->webform['components'][$key]);
      }
    }
  }
}


Access denied when user tries to edit his Content Profile I’m having a strange problem on one of my Drupal sites running Drupal 6..

I’ve the Content Profile module installed and using Tab Tamer to create some tabs on the “My Profile” page where one of these tabs is “Edit my Profile” which directs to domain.com/user/uid/profile/profil

It works fine for me as Admin, it works fine for other users that are just regular registered users, but for one user both the “Edit my profile” tab is gone and when I try to manual enter the URL I get an access denied. I can’t seem to find anything different about the particular user when comparing to other registered users.

I’ve googled the problem and found that there is (or at least has been) some issues about the permission in the Content Profile, but since it works for everyone but this user I’m not sure that whether this is a bug in the permissions with the module or there is some strange other permissions that denies this user access.

I tried to change to users role to administrator, and then he has access to editing his profile – but when changing it back, same issue occurs.

Does anyone have similar experience or a solution for this problem?

Edit the node as an administrator
On the node edit form, under "Authoring Information" set the author to the content profile user
Save content profile node with updated author information.


Moving content fields to different theme regions with display suite I am trying to output node fields in different theme regions, particularly a node reference field into my theme's right sidebar region. I have read this is possible with display suite and display suite extra modules, but I only see display suite regions (left, right...) and doesn't seem to be aware of my theme regions. How can I accomplish this?

Try the cck_blocks module.
Once installed, you can enable field blocks per field via the field settings page.

Then in the display settings, hide the field in the default/full view and show it in the cck blocks view mode.


How can I listen for drupalOverlayBeforeClose in custom jQuery? I am monitoring a particular form for changes and want to warn the user before they attempt to navigate away from the form without submitting it. I've successfully gotten this working in all instances except for the overlay close button – because that element is bound to the Drupal.overlay.close() function, a user is able to click it and immediately close the overlay, even though I'm listening for all $('a') clicks.

I looked inside of modules/overlay/overlay-parent.js and see that it provides the drupalOverlayBeforeClose event so that other scripts can respond and stop the overlay from closing if needed, but I can't figure out how to implement this. Do I just listen for this event globally, through the $(document) or something? Or do I need to extend the Drupal object and attach my function to this event somehow?

You need to use the following code,

jQuery(document).bind('drupalOverlayBeforeClose', function(event) {
   // your code
   return false // This will prevent the overlay from closing.
});

click, dbclick and other methods are shortcut methods for bind('click', function(){}), bind('dbclick', function(){}) respectively. However there is no shortcut method called drupalOverlayBeforeClose, that's why the following code didn't worked,

$(document).drupalOverlayBeforeClose(function(event) {

});

So you need to bind drupalOverlayBeforeClose explicitly using bind. If you return false in your callback, then the overlay won't be closed.

Hope this clarifies the answer.


How to disable Toolbar on certain pages / theme? Before deprecation of hook_page_build/hook_page_build_alter() we used good old method:

$page['page_top']['toolbar']['#access'] = FALSE;

(Source)

It disabled Toolbar for specific route in specific theme.

Now I checked hook_page_top(), hook_toolbar() and hook_preprocess_page(). Nothing helped, so I temporarily removed {{ page_top }} region from my html.html.twig but it doesn't look as the right approach.

page_top and page_bottom are still available, but on html.html.twig. template_preprocess_html() initializes those variables with the following code.

  $variables['page_top'] = NULL;
  if (isset($variables['html']['page_top'])) {
    $variables['page_top'] = $variables['html']['page_top'];
    unset($variables['html']['page_top']);
  }
  $variables['page_bottom'] = NULL;
  if (isset($variables['html']['page_bottom'])) {
    $variables['page_bottom'] = $variables['html']['page_bottom'];
    unset($variables['html']['page_bottom']);
  }

Since toolbar_page_top() uses the following code, I take you can use hook_preprocess_html() to avoid the toolbar appears.

  $page_top['toolbar'] = array(
    '#type' => 'toolbar',
    '#access' => \Drupal::currentUser()->hasPermission('access toolbar'),
    '#cache' => [
      'keys' => ['toolbar'],
      'contexts' => ['user.permissions'],
    ],
  );

Bear in mind that a note on Added hook_page_attachments(_alter)() and removed hook_page_build/alter() says:

  You no longer can change $page['content'] (or, generally speaking, $page[$region_name]) into something completely different.


Move site from MySQL to MS SQL I've been trying to move an existing Drupal 7 site from a MySQL database to an MS SQL database. The tables and their contents has been successfully moved. I've seen some errors in datatypes and default values, but these has been manually altered.

The site is now working, well, almost working as it should. At the bottom of each page, I'm getting an error message stating:

PDOException: SQLSTATE[42000]: [Microsoft][SQL Server Native Client 10.0][SQL Server]The data types ntext and nvarchar are incompatible in the not equal to operator. in drupal_write_record()

I've been comparing some core tables from a fresh Drupal installation, and the datatypes ar the same.

Is this a database related error or a Drupal related error? Am I even posting this question at the right place? Any help appreciated.

The DBTNG Migrator module is in fact a great choice. I've used it very successfully.


How can I retrieve the product ID? I am trying to retrieve the product IDs. I can find a product SKU by looking on the product page and using commerce_product_load_by_sku() to load it.

How can I find the actual ID? I would like to use it in commerce_cart_product_add_by_id().

According to the docs I found here commerce_product_load_by_sku($sku) will return a $product object and one of the properties is product_id.

$product = commerce_product_load_by_sku($sku);
drupal_set_message($product->product_id);

The product object looks something like this:

[product_id] => 5
[sku] => EX151
[type] => class
[language] => und
[title] => Example Product
[uid] => 1
[status] => 1
[created] => 1316634672
[changed] => 1316639451
[data] =>
[commerce_price] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [amount] => 12500
                        [currency_code] => USD
                        [data] => Array
                            (
                                [components] => Array
                                    (
                                    )

                            )

                    )

            )

    )


It is safe to store custom information in the data field of a commerce_order or commerce_line_item entity? I have this

 line_item = commerce_line_item_load($form_state['line_item']->line_item_id);
            dpm($line_item);
            $line_item->data['data_custom']['name'] = $form_state['values']['name'];
            $line_item->data['data_custom']['phone'] = $form_state['values']['phone'];
entity_save('commerce_line_item', $line_item);

It is save? In theory I'm only the only one to work with this data, other modules should not even care about that being there, right?

Yes, you can do that.

That information is commonly used to store context or other information. For instance, you can use the $order->data to store transaction IDs or other relevant information that you might want to use later on in the lifecycle of the order. In some cases, $line_item->data might store remote keys or other information related to that line item specifically.

Just be very careful that you don't store something in there that you wouldn't want to otherwise store in your database: credit card numbers or other things that you wouldn't want if your security were ever compromised or a database backup fell into the wrong hands.


Secret forum visible only to users of a specific role I need to create a forum that is visible to only users with a specific role. It should remain hidden to other users including registered users. How can I achieve this?


Webform with File upload field throwing "... field is required" error I have created a Webform, which has two file fields (i.e. Attach document 1 and Attach document 2). Both of them are mandatory and files are to be uploaded in the "Private" folder.

Now when someone attaches the files and submits the form, it throws error messages "Attach document 1 field is required" and "Attach document 2 field is required". If I invoke the validation, then it works. I have checked in the server and the files are uploaded properly. So I think it is "Webform" or "Form" issue.

This can be solved by applying the patches found here:

#49 https://www.drupal.org/node/2675170#comment-10908802
#22 https://www.drupal.org/node/2678822#comment-10926613

This will hopefully be resolved just by updating for future versions of drupal core and webform.


How to add link to custom module configuration form in Drupal 8 I'm working on a custom module that has a couple configuration form for controlling it's settings. I want to add a link to this form to the admin configuration UI. The new link to my settings isn't appearing, but the form works fine if I navigate directly to it using the URL.

# stripedonation.links.menu.yml

stripedonation.admin:
  title: 'Stripe Donation'
  description: 'Manage settings for strip donations'
  parent: system.admin_config_system
  # menu_name: main
  route_name: stripedonation.settings
  weight: 1

NOTE: I cleared the cache after adding this.

# stripedonation.routing.yml

stripedonation.settings:
  path: '/admin/config/stripedonation'
  defaults:
    _form: '\Drupal\stripedonation\Form\SettingsForm'
    _title: 'Stipe Donation Settings'
  requirements:
    _permission: 'administer site config'

I also tried adding the key shown below to my *.info.yml file and it didn't help

# stripedonation.info.yml

name: "Stripe Donation"
type: module
description: "Adds Stripe Donation form for ThinkShout vetting exercrise"
package: EmersonThis
core: 8.x
# configure: stripedonation.settings

In case it matters...

# stripedonation.settings.yml
stripe_pub_key: ''
stripe_secret_key: ''

I'm expecting my menu link to show up here (but obviously it is not):

I've studied the following documentation:

https://www.drupal.org/docs/8/creating-custom-modules/defining-and-using-your-own-configuration-in-drupal-8
https://www.drupal.org/docs/8/api/configuration-api/working-with-configuration-forms

I've also studied every "how-to" I could find:

http://befused.com/drupal/menu-links-custom-module-d8
https://www.thirdandgrove.com/creating-a-simple-configuration-form-Drupal-8
http://valuebound.com/resources/blog/step-by-step-method-to-create-a-custom-form-in-drupal-8

Still no menu in the admin UI. What am I doing wrong?

Well it turned out to be a stupid mistake!

All of my filenames and syntax were correct, but my *.links.menu.yml accidentally was saved into the src/ directory of my module instead of at the root of it. I moved it where it should be and cleared the cache and it works fine.


Unlimited values for 2 combined fields I want to add 3 fields to my articles:

repeatable (boolean)

unlimited values for repeat_date and repeat_comment

I created the fields and with fields dependency I made the it possible that repeat_date and repeat_comment only appear if repeatable is checked. I can also create an unlimited number of values for repeat_date and repeat_comment.
But these 2 fields are independet of another. I could create 2 values of repeat_date entries and 4 values of repeat_comment. Also those fields appear separate when editing articles.
How can I combine those 2 fields and have unlimited values for this combined fields?

You can wrap the fields in a Paragraph with the paragraphs module. I.e. create a new paragraph type, repeatable_date, with two fields: date and comment. Then add a new paragraphs reference field to your article and set cardinality to unlimited. This will allow you to add unlimited repeatable date items, each with date and comment.
Or you can create a new custom field type that has a date field and a comment field. This is more difficult to do, but may be preferable if the paragraphs route doesn't suit you. See How to create a new field type for details.


Main_menu Google Analytics Event Tracking I have been asked to insert a google tracking code to all of my main_menu Links

link-name

I try to found a module but i couldn't found how to use it to accomplish this task.
https://drupal.org/project/google_analytics_et

I thought i can use a hook_menu but i need some help..

Drupal 7

To do that I was using Menu attributes module with Onclick Event patch. Simply install it, apply patch, enable module and you will be able to add onclick code to menu elements via GUI.


How to build a reusable configurable form How could I build a reusable form that can be reconfigured for each location in which it is used? It would have the same fields, however select list values would be different depending on what the user thinks it should contain based on its location in the site.

Locations include blocks and panels across many pages and sites, and potentially
multiple locations on the same page.

In a custom module, use the FormAPI to build your form and create variables to store your #options for example (in the case you mentioned of select lists that change). Set the variable according to the context and you should be good to go.

/**
 * Implements hook_form();
 */
function mymodule_form($form, &$form_state) {

  // For inspecting information about entity and id:
  kpr(arg(0));
  kpr(arg(1));

  $form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Selected'),
    '#options' => $variable_according_to_context,
    '#default_value' => $category['selected'],
    '#description' => t('Varies according to context.'),
  return $form;
}

The $variable_according_to_context will hold the options of your select list. You can set this variable to different options according to the context you are in. You can use arg(0) or arg(1) to get the node or entity type the form is in. I hope that was clear enough on how I would approach this.


How do I add a Commerce product type to a feature? I have a custom product type that I created in my local dev environment and I'm trying to export it into a feature.

However, I can't seem to find where the product type is stored in the Features module UI.  I found the permissions (Product: View Own Custom Products) and the field instances (commerce_product-custom-commerce_license_role) but I don't see the product type itself.

Instead, when I enable the feature on production, I get the following error message:

  Warning in features rebuild of custom_module. No module defines permission
  "view any commerce_product entity of bundle custom_product_type_machinename".

When I export to production, the product type is not created.  Where are the Commerce product types in the Features UI?

As it turns out, product type export is not supported in the core Commerce module.  Instead, you need to install the Commerce Features module.


Is it possible to add a CiviCRM API to the Webform CiviCRM integration module and how would I do that? If I have created a specific CiviCRM API entity/action for a project, can I then add that API to the Webform CiviCRM integration module so that I can use the API in the Webform? And how would I do that?

I found this old link for plans to add arbitrary api calls to the module, but it doesn't appear to have ever been implemented:
http://forum.civicrm.org/index.php?topic=22304.0

But it appears that I could use hook _webform_submission_presave to execute the api call when the webform is submitted.


Drupal 7 Views, paths, node associations via taxonomy After many hours I still cannot wrap my head around what is needed to make my situation work. Here it is:

I current am using clean URLS like so /artists/name-of-artist routes content type Artist. I have content types: Arists, Album Releases, Tour Dates, and Media. I would like to tie everything together using vocabulary Artist Tags (yes, even Artist content type would get tagged). So, say for example I have "Test Artist" in Artist content. I tag it with "Test Artist" Artist Tag. I also create an Album Release tagged "Test Artist". My question now is when visiting /artist/test-artist how do I have a view that shows not only the dat from that artist node but also from the Album Release node tagged "Test Artist".

I have already tried Node Reference. This is not an ideal solution for me as I want the flexibility of library categorization via taxonomy. I just can't understand how I can pull in another node's content based on  /artist/test-artist Artist Tag field.

I forgot to mention that I am using the latest version of Drupal 7, and Views 3.

Sorry for a general answer, but it may get you in the right direction anyway.

What you seem to need is to establish relationships in views. By adding a relationship, you just add an object you would like to refer to. Once you add a relationship (on the right hand side, in Advanced panel), additional fields appear in the Add Field and Filter dialogs. Note the dropdown list that appears in field-related dialogs that contains relevant relationships that you have defined. You may also have a cascaded relationship (a relationship that uses another relationship).

All that translates later into the WHERE clause of the final query which filters what you want to show/hide.

To use the elements of the path, you want to use Contextual filter where you specify which part of the URL means what.

One thing to remember is that, even though you have clean URLs turned on, there is an "unclean" URL query behind the scenes which contains stuff like term IDs or node IDs. Perhaps it'd be useful for you to turn the clean URLs off for a moment, and play for a while just to see what kind of URLs will be used by views contextual filter. Or put <?php print $_GET['q'] ?> somewhere in the page.tpl.php for testing convenience.


drupalLogin in functional JavaScript tests passes locally but fails on Drupal.org? During functional JavaScript testing one can create and login a user by using the following code:
$this->testUser = $this->drupalCreateUser(['permission']);
$this->drupalLogin($this->testUser);

This works fine when testing locally with PhantomJS. However after uploading this code to drupal.org it keeps failing randomly (sometimes 1 test, sometimes 2) with the following error:

User dOGIV5Iu successfully logged in.
Failed asserting that false is true.

This appears to be coming from the assertion in BrowserTestBase::drupalLogin, which should normally check that the user is logged in correctly.
$this->drupalGet('user/login');
$this->submitForm([
  'name' => $account->getUsername(),
  'pass' => $account->passRaw,
], t('Log in'));

// @see BrowserTestBase::drupalUserIsLoggedIn()
$account->sessionId = $this->getSession()->getCookie($this->getSessionName());
$this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));

How come that a test function does work locally, but not on Drupal.org? Even stranger is that this function is used throughout multiple core tests without issues. And why is this assertion failing randomly?

After reading through the Jenkins results for the nth time, it finally occurred to me that during Drupal core (and other contrib) tests all JavaScript tests always run separately from the other tests. All my tests however were in the same list.

This happened because all test classes started originally as functional tests, but as I went ahead some of them were changed into functional javascript tests. Class extending was changed into JavascriptTestBase and the tests were working perfectly fine. At least, when running individually. Running multiple tests at the same time made them somehow interfere with one another.

The problem was that I had never changed the namespace from Functional into FunctionalJavascript. The Drupal testrunner makes sure that all FunctionalJavascript tests are ran one by one, but performs other tests in parallel.

After changing the namespace, the tests were listed separate from the rest, ran after each other and finally showed up green on Drupal.org


When using the Batch API should I create an operation per node? I am using the Batch API in Drupal 7 and I just realized that the reason why my count and totals are not showing correctly is because the initial total is based on a count of the operations given to it.

The thing is I set it up so that each operation processes 100 nodes. I have to update information in nodes that meet certain criteria and there are almost 7,000 nodes that have to be updated. So I thought it would be more efficient to fix multiple nodes per operation call.

Instead it seems like I should put in an operation per node or an operation per 100 nodes (even though my current setup seems to keep calling the same operation with no problems). So what should it be? I guess I could use the context variable to force it to count properly, but I don't like hacking around issues if I don't have to.

Below is the code I am using:

/**
 * Load the nodes with the broken language bodies and fix them.
 */
function my_fixes_broken_bodies() {
  $brokenBodyCnt = my_fixes_count_broken_bodies();
  $operations = array();
  $limit = 100;
  $count = ceil($brokenBodyCnt / $limit);

  // Give helpful information about how many nodes are being operated on.
  drupal_set_message(t('There are @brokenBodyCnt nodes to fix. And we are fixing @limit nodes per call. So the operation will require @count HTTP requests.', array('@brokenBodyCnt' => $brokenBodyCnt, '@limit' => $limit, '@count' => $count)));

  //Setup the operations for the fixes
  $operations[] = array('my_fixes_broken_bodies_op', array('broken body fix'));

  $batch = array(
    'operations' => $operations,
    'finished' => 'my_fixes_finished',
    'title' => t('Fixing broken node body language settings.'),
    'init_message' => t('The broken body fix is starting...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('The broken body fix has encountered an error.'),
  );

  return $batch;
}

/**
 * Batch operation for fixing the broken bodies.
 */
function my_fixes_broken_bodies_op($operation_details, &$context) {
  if (empty($context['sandbox'])) {
    $context['sandbox'] = array();
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;

    // Save node count for the termination message.
    $context['sandbox']['max'] = my_fixes_count_broken_bodies();
  }

  // Process nodes by groups of 100
  $limit = 100;

  // Retrieve the next group of nids.
  $result = db_query("SELECT n.nid, FROM_UNIXTIME(n.created) AS created, n.title, n.type, n.language AS 'Node Language', b.language AS 'Body Language'
  FROM node n INNER JOIN field_data_body b ON nid = entity_id
  WHERE n.language != b.language AND status = 1
  ORDER BY nid ASC LIMIT $limit");
  $results = $result->fetchAll();

  foreach ($results as $row) {
    $node = node_load($row->nid);

    if (isset($node->body['en']) && !isset($node->body[$node->language])) {
      $node->body[$node->language] = $node->body['en'];
      $node->body['en'] = NULL;
      node_save($node);
    }

    $context['results'][] = $node->nid . ' : ' . check_plain($node->title) . ' ' . $operation_details;

    // Update our progress information.
    $context['sandbox']['progress']++;
    $context['sandbox']['current_node'] = $node->nid;
    $context['message'] = check_plain($node->title);
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
  }

  _my_fixes_update_http_requests();
}

Ok, so I figured out a better approach. Below I have listed my new code. The gist of it is that I decided to break it out in such a way that I will have one operation per 100 nodes that need to be fixed. I have 6,581 nodes that need to be fixed. So that means I need 66 operations to fix all of the nodes.

I created some calculations that determine how many operations I need to run. Then I set each operation to only process 10 nodes at a time (to save memory). Once an operation has hit it's max of 100 nodes it then tells the Batch API it is finished. This is part of what I was getting hung up on. I thought that max and finished referred to the entire batch process, not the current operation.

Theoretically I could create an operation for every single node that needs to be fixed. But this seems highly excessive, and a bit inefficient. It would increase the db calls quite a bit and the HTTP calls.

Another improvement I made to my code is to only return the node id field in the query instead of all those extra fields that I didn't need. This changed the query run time from about 7.5 seconds to about 0.24 seconds.

All in all I am much happier with the results.

function my_fixes_broken_body_nodes() {
  $results = db_query("SELECT n.nid
  FROM node n INNER JOIN field_data_body b ON nid = entity_id
  WHERE n.language != b.language AND status = 1
  ORDER BY created DESC");

  $count = $results->rowCount();
  $results = $results->fetchAll();

  return array('node_ids' => $results, 'count' => $count);
}

/**
 * Load the nodes with the broken language bodies and fix them.
 */
function my_fixes_broken_bodies() {
  $brokenBodies = my_fixes_broken_body_nodes();
  $brokenBodyCnt = $brokenBodies['count'];
  $operations = array();
  $limit = 10;
  $nodesFixedPerOp = 100;
  $count = ceil($brokenBodyCnt / $limit);
  $opCount = ceil($brokenBodyCnt / $nodesFixedPerOp);

  // Give helpful information about how many nodes are being operated on.
  drupal_set_message(t('There are @brokenBodyCnt nodes to fix. And we are fixing @limit nodes per call. So the operation will require @count HTTP requests.', array('@brokenBodyCnt' => $brokenBodyCnt, '@limit' => $limit, '@count' => $count)));

  //Setup the operations for the fixes
  for ($i = 0; $i < $opCount; $i++) {
    $operations[] = array('my_fixes_broken_bodies_op', array(t('(Operation @operation)', array('@operation' => $i))));
  }

  $batch = array(
    'operations' => $operations,
    'finished' => 'my_fixes_finished',
    'title' => t('Fixing broken node body language settings.'),
    'init_message' => t('The broken body fix is starting...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('The broken body fix has encountered an error.'),
  );

  return $batch;
}

/**
 * Batch operation for fixing the broken bodies.
 */
function my_fixes_broken_bodies_op($operation_details, &$context) {
  // Process nodes by groups of 10
  $limit = 10;

  if (empty($context['sandbox'])) {
    $context['sandbox'] = array();
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;
    $brokenBodies = my_fixes_broken_body_nodes();

    // Save node count for the termination message.
    $context['sandbox']['max'] = 100;
    $context['sandbox']['node_ids'] = $brokenBodies['node_ids'];
  }

  // Retrieve the next group of nids.
  for ($i = 0; $i < $limit; $i++) {
    $row = array_shift($context['sandbox']['node_ids']);
    $node = NULL;

    //Load the node
    if (isset($row->nid) && !empty($row->nid)) {
      $node = node_load($row->nid);
    }

    //Make sure it loaded alright and then run operations on it.
    if (!empty($node) && is_object($node)) {
      if (isset($node->body['en']) && !isset($node->body[$node->language])) {
        $node->body[$node->language] = $node->body['en'];
        $node->body['en'] = NULL;
        node_save($node);
      }

      $context['results'][] = $node->nid . ' : ' . check_plain($node->title) . ' ' . $operation_details;

      // Update our progress information.
      $context['sandbox']['progress']++;
      $context['sandbox']['current_node'] = $node->nid;
      $context['message'] = check_plain($node->title);
    }
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
  }

  _my_fixes_update_http_requests();
}


how see left or right sidebar in search result page? I'm sorry if it sounds like obvious question, but I cannot solve this... I'm using D7.15, customized Fusion subtheme and Display Suite to style the search result appearance. But all the times I get the search results page in fullscreen (no left or right sidebars) and I can't find the solution for this. No costomizations on search-results.tpl.php.

please help! :/

UPDATE: I'm using drupal core search, I have tried Search by page module too.

Create one template file: page--search.tpl.php.

Write the following code:

//to print the main content
print render($page['content']);

//to print your right side-bar
print render($page['name_of_the_region_with_right_sidebar']);

and other customization as needed.


Ajax enabled form stopped working - Ajax callback never called I have the weird problem that an Ajax enabled form that just worked stopped working - and I have not a clue what is causing this and when it stopped to work. The form itself has no changes for months now and I did not find any code updates which may interfere with this form.
The form is defined in its own form class which extends FormBase. The Ajax functionality is added with the following code in buildForm() method:
$form['form_container']['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => [
    'callback' => '::ajaxResponse'
  ],
  '#attributes' => [
    'class' => ['js-show-throbber']
  ],
  '#weight' => -45,
];

In the form class the method is defined:
public function ajaxResponse(array $form, FormStateInterface $form_state)

When I set a breakpoint within this method for XDebug the script never stops, the process within this methods are not running.
There is no info in browser's console, it is not working in any browser and in watchdog of Drupal are no entries. For me it seems that somehow the bridge between browser / JavaScript world and the form PHP class is broken. I use the exact same PHP code for many other forms without any problem.
My question: can anybody give me a hint how exactly the bridge between browser and form class is created when the form gets rendered? How can I find out if there is a problem in the PHP form class or somewhere in JavaScript?

Ok, this was just a stupid mistake in a another javascript. There the jQuery method .off() was used to remove event listeners which had the effect to remove the Ajax event listener.


proper way to edit drupal_page_header() I can't find a hook for overrideing drupal_page_header() in bootstrap.inc and it doesn't feel right to make changes in bootstrap.inc.

Is there another other way that I'm missing?

If you goal is only to change the Cache-Control you can use drupal_add_http_header(). According the documentation this function allow you override an existing header. If you add it in you template.php you'll able to change the header without patch the core function.


Using clientside javascript with Rules I would like to implement a client side javascript action using the Rules module. Has anybody been able to do this?

Rules is not designed to work with client side events. They way Rules is designed, it won't make any sense to try to make it aware of client side events.

Your best course of action would be to write some custom JavaScript.

If you want to add some javascript code to a page using rules, that would be possible if you created a custom action that added the JavaSript you wanted to the site.


How to make DrupalChat more stable, to have it recognise online users? Never had any luck with the DrupalChat module. It is always flickering on and off, saying other users are currently offline when they are on.

Does anyone have any tips or tricks for making DrupalChat stable?

In the module config page admin/config/drupalchat/configuration see Chat List Latency says

  The delay, in seconds, after which the user will be shown offline in
  the chat list(i.e. removed from the chat list) from the time he/she
  goes offline. Increase this value if you find the chat list is
  unstable and keeps on changing a lot (for example - when a user
  navigates from one page to another he/she goes offline and then comes
  back online again). Decrease it if you find that the users are shown
  in the chat list for too long after they have left your website.


Commerce Product with diffrent prices for different shops Working with Drupal 7 on a comparison site where a product is sold at different price rates at different physical shops. Now there about 300 of these shops. Going by Commerce default setup, I would have to create 300 product types or products and also create 300 product display nodes, which will be insane.

Since the product name, image, (and other attribute is going to be the same, I thought to create a single product display content type that has a price field and create a single product type with all the default fields except price. So with the content type, several product display nodes can be created that then references the single product type. Great right? But the price field in the product type is locked (you cannot delete it).

What other more civilized process is available to achieve my goal, as I need the Add to cart button on each product so as to be able to add to cart and compare the prices onwards.

I have seen a similar question (Drupal Commerce: How to handle billions of product combinations?) go unanswered, hopefully commerce has matured these past three years. Thank you.

To resolve the product display <-> product issue, I'd be using Inline Entity Form to embed the product form right into the product display node form. However, that doesn't address your need to have hundreds of unique prices corresponding to different physical locations. That's another issue entirely that we would typically refer to as pricelist functionality.

We do have a Commerce Pricelist module, but since "Store" wasn't a core entity type in Drupal 7, there is no pricelist variant correlating to a store. You'll likely need to enhance that module yourself to make it "simple" for end users. Other options would be dependent on your greater site IA ... and it's worth noting that store based product availability and pricing would be better suited to Drupal 8 if there's any chance at all at upgrading.


How do I pre-populate the login/sign up form? I'm working on a project that let any user (anonymous) register for an event. An event is a content type that has duration, name and price and possibly a date. So, when a user browse through different events, they can register for an event by simply clicking on the "Register for this Event" What needs to happen when they click on Register.. is: the info related to that event needs to pre populate to the member login form so that they don't have to fill the event info again.

The user must be a member before they can register for the event but I am trying to give a nice user experience to the user so that he/she can simply click on the Register link and then they will be redirected to the user login/sign up form the event info pre-loaded and they provide the rest of the info.
I have already extended the standard Drupal login form to my need and also created the event content type. Thinking to use flag module to make Register link but have NO idea how to pre populate that event info into the login form. Any help or guide will be highly appreciated. Thanks in advance.

I have already extended the standard Drupal login form

Sounds like you're already using hook_form_alter(), so all you have to do is add the #default_value attribute to your form array.

Ex:

$form['my_field_name'] = array(
    '#type' => 'textfield',
    '#title' => t('something'),
    '#default_value' => t('Hello World'),
);

OR Use the Profile2 module suggested by @Kevin

  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)


Setting anonymous user timezone on page load I'm developing a radio site where show times are displayed. Since it's an Internet radio station, I need to be able to display times in the user's timezone.

I'm able to detect which timezone a user is using (eg. Europe/London), but I don't know how to make Drupal use that timezone.

Is there any way to programmatically override Drupal's default timezone to instead use the timezone I detected?

I've looked through the documentation, but I have not been able to find a way for achieving this.

drupal_get_user_timezone() is the main function that retrieves the user's zone (based on a configured user setting, site setting, or PHP's date_default_timezone_get() depending on site/user settings).

This function's implementation is based off of retrieving configuration settings and native PHP function. There's no way to override that short of
trying to redefine to this function (if you don't mind a solution that is a bit of hack).

An alternative to that would provide some wrapper function in a custom module. For example:

function mymodule_get_timezone() {
  // @TODO: At timezone lookup retrieval based on IP/Whatever
}

function mymodule_get_user_timezone() {
  // Or \Drupal::currentUser()->isAnonymous() in D8
  return user_is_anonymous() ? mymodule_get_timezone() : drupal_get_user_timezone();
}

Then reference mymodule_get_user_timezone() wherever you need to insert your own discovered timezone.


How to print a block in node.tpl.php only for admin? What is the simplest code that checks if user is admin and then prints a block to that user in node.tpl.php? I have seen different examples, but they are all either complicated and deal with other problems at the same time or they include editing template.php, which I want to avoid. I have tried with this, but it doesn't work:

<?php if ($is_admin->true): ?>
<?php print views_embed_view('myview','block'); ?>
<?php endif; ?>

Is there such a simple way to achieve this?

You can do something like this:

global $user;
if (in_array('admin', $user->roles)) {  //if not "admin", maybe "administrator"?

}

Or you can use the built-in block access control, under your block's configuration you'll see "Visibility Settings" and in there is a way to restrict by user role.

Edit: what the hell, it's friday and I'm bored.

Take this in small steps before you conclude it's "not working".

Step 1)

global $user;
if (in_array('admin', $user->roles)) {  //if not "admin", maybe "administrator"?
    echo "
admin user!
";
}

If that works, then start making it more complex.  This is the best way to learn how to do new things, especially with PHP since you get to see your stuff immediately!


How to access to form field in views-exposed-form.html.twig (exposed filters) I am trying to customize the template for the exposed filters of a view.

I have created the views-exposed-form.html.twig and Drupal loads it fine, following How do I theme exposed filters?.

For now, I have the standard code:

/**
 * @file
 * Theme override of a views exposed form.
 *
 * Available variables:
 * - form: A render element representing the form.
 *
 * @see template_preprocess_views_exposed_form()
 */
#}
{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
{{ q }}
{% endif %}
{{ form }}

and that works fine. Nevertheless, if I try to show only one field of the form (e.g., {{ form.field_city }}) nothing is shown in the filter block, though the page loads fine and there are no apparent errors.

I am working with Drupal 8.7.7 and PHP 7.3.9.

Any help will be more than welcome.

Thank you in advance.

Solved. The problem seems to be an incompatibility with Better Exposed Filters module.

Thanks!


How to add custom "pay now" button and after submit, redirect to the checkout/orderId page In the Deal details page I want to add a new button Pay Now and then user clicks it, then redirects to the checkout/orderId page. How is it possible ? Please help.

Use a rule. Example:

{ "rules_forward_user_directly_to_checkout" : {
    "LABEL" : "Forward user directly to checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [],
    "REQUIRES" : [ "commerce_order", "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [],
    "DO" : [ { "redirect" : { "url" : "checkout" } } ]
  }
}

Note that you don't need to redirect to checkout/%order_id, you just need to redirect to checkout and Commerce will take care of the rest.


Views keeps crashing when I change setting I have created a Latest News view which I'm displaying in my sidebar as a block. When I then go back to change anything such as the Title of the View or the number of items that can be displayed, it crashes. can anyone help? I have attached a screen print which shows the error.

It is jquery version issue. Views is not crashing, It is returning json response which  Drupal is not handling properly due to jquery version issue. If you are using jquery_update module. Change the jquery version to 1.5 or older. If not; use this module. Latest jquery_update module allow you to set different jquery version for administrator pages and actual site nodes. Set the jquery version 1.5 or older for administrator pages and higher for actual site nodes if needed.


Get raw value of a block content I have created several views. These views have a block display. If I use these blocks in my template, the views are rendered with all the wrappers / divs.
In my block template, can I alter the output of the "content" variable to get only the values?
I tried to use different twig filters (striptags, trim, raw), without success. With these filters I get nothing.

Thanks.

A lot of templates are used to output a single Views display. It depends on your particular case which level you want to override. These templates are probably the best way to control the output of the views where ever you want to print them.

One template outputs the outer views divs, another is for particular format options, others are for controlling rows output. So you have to investigate and override the templates where you want to change the HTML for that particular view.

You can strip each individual Field of its wrapper and even field HTML in its Style settings directly in Views.

You can see the template suggestions under Theme: information in D7 Views, and in D8 you have to turn on the debugging mode to see the suggestions in page output.


How can I programmatically get various common user profile related URLs? I'd like to get the following URLs in Drupal 8:

/user/register
/user/login
/logout
/user

I already know I can use \Drupal::service('path.current')->getPath() to get the current path. I want to build links to redirect users.
How do I get these paths programatically?

The user URLs (or routes to be more "Drupal correct") are defined by the core user module (core/modules/user/user.routing.yml)
E.g.
user.register:
  path: '/user/register'
  ...

user.login:
  path: '/user/login'
  ...

user.logout:
  path: '/user/logout'
  ...

user.page:
  path: '/user'
  ...

So you can programmatically build links to these routes like so:
<?php

use Drupal\Core\Link;

// Replace user.login with other routes such as user.page
$user_login_link = Link::createFromRoute(
  t('User log in link'), // The link text
  'user.login', // The link URL generated from the route
);


How to set up a trial-based account for users on an ubercart site? I want to set up a trial based account for an user who will sell his products. After he paid the payment, i will upgrade him to role seller.

Until his role is upgraded to role seller, i don't want to show add to cart button for the added products.

First of all how can i differentiate it to be a trail site for example. 30days until he pays, if not i want the role to be expired. How can i do it. Any suggestions will be helpful?

Create 2 user roles: Trial Seller and Seller.
Create a Rule.

Event: "Drupal is initializing"
Condition: User has role -> "Trial seller"
Action: php that will hide (disable) the add to cart button. You have to use the hook_form_alter function (or similar) like described here: https://drupal.org/node/773312#comment-7425408

The second question is another seperate task.

Create a Rule:

Event: "Drupal is initializing"
Conditions: User is of role "Trial Seller" AND not "Seller" AND php "(Current_date_time - Account_Created_Date) > 30*24*60*60" (to see if the time from the user account date until now is more than 30 days, time in seconds) AND he has paid
Action: Remove user role -> "Trial Seller"

There is also the module Role_Expire that may help you.


What HTML tags for image with style? In below codes, there is style="float: left;" that make the image float.

Ut scelerisque pulvinar nisi eget ultricies. Fusce iaculis risus vel nunc aliquam hendrerit. Fusce et bibendum justo. In ultricies quam at libero dapibus eu fermentum ipsum eleifend. Proin at libero nulla. Mauris adipiscing, odio vel tempus dapibus, odio dolor pellentesque neque, ac adipiscing enim purus tincidunt mauris. Nunc elementum euismod tellus ut commodo. Aliquam nec felis nunc. Suspendisse et turpis nec purus auctor ultrices sed ut arcu. Mauris suscipit scelerisque tortor, id feugiat sapien lacinia vel. Phasellus congue tellus sed est blandit eu gravida ipsum ultrices. Vestibulum orci leo, condimentum at adipiscing in, scelerisque et odio.

Without HTML filtering, it works. But if using HTML, what tag should I add to make the picture float?

Currently, below is my tags:

  <map> <area>

            <quote>

 <address>   <embed> <object> <param>
 <s> <textarea>

You can use class="left" in your HTML, and .left {float:left;} in you CSS.


How to pass field value to referenced node template? I have content type A. It has field reference to content type B.

I'm rendering referenced node B from content type A twig template like:

{{ content.field_referenced_object }}

And that works well.

I also render some type A filed inside it's template like:

{{ content.field_some }}

which also works.

Problem is that I need that field_some value to be displayed from referenced object B template instead of object A template, to optimize page markup. How can I pass value from content type A twig template to content type B twig template?

It twig it can be done when including template like:

{% include 'template.html' with {'foo': 'bar'} %}

But is there some analogy for Drupal 8 theming?

TL,DR: No.

Long version:

Conceptionally entity render arrays are self-contained, cachable units. The Drupal way would be either preprocessing and a custom cache context based on the referencing node, or a views block with a contextual filter.

But IMHO both ways are terrible workarounds, your Twig snippet {% include ... with ... %} is the better technique.


Drupal 7 & jQuery -- the $ dollar sign If I'm not planning on using any JS libraries other than jQuery, is there any reason to need Drupal's call to jQuery.noConflict() which removes $ as an alias for jQuery?

Assuming there is no need for removing the $ alias, is there a way I can get it back universally without always having to wrap my jQuery code in (function($){...})?

The solution I came up with is this:

At the top of the first JS file I include in my custom theme, I simply put the following line:

$ = jQuery;

Done :)


Update hook batch stops halfway through I rarely ask questions on SE but now the teacher has become the student because this is driving me mad. I am doing a simple batch through an update hook and publishing some unpublished nodes. I am aware I could do this with a flat query, but I am preferring to use the batch system.

For whatever reason it arbitrarily stops at 50% no matter what I do. I have tried modifying the nodes per pass, etc. No errors. It just stop at the halfway point. When I debug the hook, I can see the counter variable increments right up to halfway and then stops. This is the hook. Am I crazy?

function mymodule_update_7200(&$sandbox) {
// Initialize the batch
  if (!isset($sandbox['total'])) {
    $result = db_query('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0', array(':type' => 'event'));
    $sandbox['total'] = $result->rowCount();
    $sandbox['current'] = 0;

    // Disable Scheduler
    module_disable(array('scheduler'));
    drupal_set_message(t('The scheduler module was disabled'));
  }

  $nodes_per_pass = 20;

  // Get the nodes to process during this pass.
  $result = db_query_range('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0', $sandbox['current'], $nodes_per_pass, array(':type' => 'event'));
  foreach($result as $row){

    $node = node_load($row->nid);

    // Run a database update directly so we don't trigger any API calls through node_save
    db_query("UPDATE {node} n SET n.status = 1 WHERE n.nid = :nid", array(':nid' => $row->nid));

    // Log the event being published
    watchdog(
      'events',
      'Event was published: %title',
      array('%title' => $node->title),
      WATCHDOG_NOTICE,
      l('View', "node/$node->nid")
    );

    // Increment "current" by 1.
    $sandbox['current']++;
  }

  // Set the value for finished. If current == total then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);

  if ($sandbox['#finished'] === 1) {
    drupal_set_message(t('@nodes events were published. View the log for details.', array('@nodes' => $sandbox['total'])));
  }
}

The problem in this case is caused because results query differs between iterations.

You should replace:

$result = db_query_range('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0', $sandbox['current'], $nodes_per_pass, array(':type' => 'event'));

with

$result = db_query_range('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0 ORDER BY n.nid ASC', 0, $nodes_per_pass, array(':type' => 'event'));


Drupal 8 - Taxonomy Menu with Hierarchy I have been looking searching for a while and couldn't find anything related to Drupal 8. There are Modules like Taxonomy Menu but unfortunately not for Drupal 8 which works accordingly.

Is there already any solution to build-up a menu out of the taxonomy terms for Drupal 8 without an individual development (php etc.)?

Further, I have realized when I create a taxonomy term and create a reference from a content I don't get the overview of contents linked to the term.

Hope my point is clear.

I needed the same thing. Unfortunately there is nothing for it yet so I had to create something for time being. It is not pretty but it works so I don't care.

/**
 * Returns renderable array of taxonomy terms from Categories vocabulary in
 * hierarchical structure ready to be rendered as html list.
 *
 * @param int $parent
 *   The ID of the parent taxonomy term.
 *
 * @param int $max_depth
 *   The max depth up to which to look up children.
 *
 * @param string $route_name
 *   The name of the route to be used for link generation.
 *   Taxonomy term(ID) will be provided as route parameter.
 *
 * @return array
 */
function mymodule_categories_tree($parent = 0, $max_depth = NULL, $route_name = 'mymodule.category.view') {
  // Load terms
  $tree = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('categories', $parent, $max_depth);

  // Make sure there are terms to work with.
  if (empty($tree)) {
    return [];
  }

  // Sort tree by depth so we can easily find out the deepest level
  uasort($tree, function($a, $b) {
    // Change objects to array
    return \Drupal\Component\Utility\SortArray::sortByKeyInt((array) $a, (array) $b, 'depth');
  });

  // Get the value of the deepest term
  $deepest = end($tree);
  $deepest = $deepest->depth;

  // Create a structured array
  $list = [
    $parent => [
      'items' => [],
      'depth' => -1
    ]
  ];
  foreach ($tree AS $term) {
    $list[$term->tid] = (array) $term;
  }

  // See if we're on a node page and if so open the menu
  // on the proper position.
  $node = \Drupal::request()->attributes->get('node');
  if ($node) {
    $categories = $node->get('categories')->getValue();
    // Go through each category to find out the least deep one.
    // That one will be the one we'll open.
    $open_category = $parent;
    foreach ($categories AS $target) {
      $tid = $target['target_id'];
      if ($list[$tid]['depth'] > $list[$open_category]['depth']) {
        $open_category = $tid;
      }
    }
  } else {
    // See if we're on a term page and set the corresponding item
    // as active so we don't have to rely on JS.
    $term = \Drupal::request()->attributes->get('taxonomy_term');
    if ($term) {
      $open_term = $term->id();
    }
  }

  for ($i = $deepest; $i >= 0; $i--) {
    foreach ($list AS $term) {
      if ($term['depth'] == $i) {
        $item = [
          '#type' => 'link',
          '#weight' => $term['weight'],
          '#title' => $term['name'],
          '#url' => Url::fromRoute($route_name, ['taxonomy_term' => $term['tid']]),
          '#options' => [
            'set_active_class' => TRUE
          ]
        ];
        // If we're on a node page and this category was chosen
        // as active, set the link's class.
        if (isset($open_category) && $open_category == $term['tid']) {
          $item['#attributes']['class'][] = 'active';
        }
        // If we're on term page, set the link's class to 'active'
        // and if this item is a parent, open it.
        if (isset($open_term) && $open_term == $term['tid']) {
          $item['#attributes']['class'][] = 'active';
          if (!empty($term['items'])) {
            $item['#wrapper_attributes']['class'][] = 'open';
          }
        }
        // If this item has children
        if (!empty($term['items'])) {
          $item['items'] = $term['items'];
          $item['#wrapper_attributes']['class'][] = 'parent';
          $item['#prefix'] = '';
          // If any of the child items has 'active' class,
          // or is also a parent and has 'open' class
          // add the 'open' class to this wrapper too.
          foreach ($item['items'] AS $child) {
            if (
              isset($child['#attributes']['class']) && in_array('active', $child['#attributes']['class'])
              || isset($child['#wrapper_attributes']['class']) && in_array('open', $child['#wrapper_attributes']['class'])
            ) {
              $item['#wrapper_attributes']['class'][] = 'open';
              break;
            }
          }
        }
        foreach ($term['parents'] AS $pid) {
          $list[$pid]['items'][$term['tid']] = $item;
        }
        unset($list[$term['tid']]);
      }
    }
  }

  return [
    '#theme' => 'item_list',
    '#items' => $list[$parent]['items'],
    '#attributes' => [
      'class' => ['categories-tree']
    ],
    '#attached' => [
      'library' => [
        'mymodule/categories_tree'
      ]
    ]
  ];
}


Views Grouped by *each* value of a content field (multivalue). I am pretty new to drupal, so some terms I describe may not be accurate. Anyways, I know how to group things in views using single values (i.e. Group faculty members by their departments: engineering, biology, medicine, social science, etc).

I want to create a view that groups items by a field which accepts multiple value (i.e. research areas). Suppose we have the Research Areas A, B, C, and D. Then, I want to group it such that each faculty member is displayed under each value of the multi-value field. Let's also suppose there are Faculty Members John, Josh, Jack, Jasmine, and their respective research areas are as follow (Note: omitted departments):

John { research area: A, B }
Josh { research area: B, D }
Jack { research area: A, D }
Jasmine { research area: B, C }
Joyanne { research area: A, B }

Then, the view should display as follows (desired output):

Research Area A:
 John  Jack  Joyanne
Research Area B:
 John  Josh  Jasmine  Joyanne
Research Area C:
 Jasmine
Research Area D:
 Josh  Jack

---------------------------------------------------------------
I have been using fields inside each faculty member to represent the research areas they fall under (check boxes for different research areas they focus on). And I have some how grouped them using the Research Area field; however, they are grouping as such:

Research Area A, B:
 John  Joyanne

Research Area B, D:
 Josh

Research Area A, D:
 Jack

Research Area B, C:
 Jasmine

I have also used Taxonomy Vocabularies, but to no avail.

Help SVP. Thanks for your time in advance.

Grouping is done by the information you have in your results.

Fields with multiple values return results differently, depending on the Multiple field settings you set on them.

If you choose to Display all values in the same row then each node will show all "Research Areas" related to it, and if you enable grouping groups will reflect the option combinations from results. This is your current behavior.

If you untick the option Display all values in the same row each node will be displayed in a separate row showing only one "Research area" it belongs to, but it will be listed as many times as it has "Research areas" attached to it. When you enable grouping in this scenario each "Research area" option will behave "independently".

So to achieve your desired behavior you need to untick the option Display all values in the same row on your "Research Areas" Field (mind you this is under Fields, and not under Format where Grouping options are).


How do I use views to override a taxonomy term page for only terms with a single vocabulary? How do I configure a view to allow me override only term pages within a specific vocabulary without overriding all other term pages?

Edit: Due to the requirements of the project, this must be done with a view and not overridden with a custom tpl.

I ended up using the Taxonomy Views Integrator module.

The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabulary.


How to list subpages on separate menu per page Say I have a structure like this:

Mammals
  Rodents
     Mice
     Gerbils
  Felines
     Ocelots
Birds
   Songbirds
   Raptors
       Eagles
Reptiles
    Lizards

Etc

I would like for the main menu to display: Mammals, Birds, Reptiles.

But when you are on, for instance, Mammals, or any of it's children. I wish for there to be an additional menu that shows all of the main parent and children (so in this case mammals, rodents, mice, gerbils, felines, ocelots).

Is there any way to set this up or a module that would help? I guess that the first step would be page groups, but I don't see reference to this hierarchy other than creating automatic menus.

(using drupal 7)

Have a look at the Menu Block Split module.

  With this module you can split any menu block into two different blocks: a first block with the first level menu entries only and a second block with any second level and sub level menu entries. You can have as many splitted blocks as you need.

There is a Drupal 7 development version, just posted this evening.


field update on field with no permission I have a field (selectbox) that is configured to not be shown (no 'view' permission) on a particular role, nor not to be edited (no 'edit' permission) by the same role. This role is only able to edit other fields. So normally, when this role edits the content, he should not see this particular field. But I want this field to automatically get updated via 'Triggered Rules'. I don't want anyone able to see this field in the first place. For example:

Price Range Field:

Lowest to 1M
Between 1M to 5M
Between 5M to 10M
Greater than 10M

This is my set up so I could use this in exposed filter views to filter price ranges.

When that role enters some price in 'field_price', a trigger updates the price range field.

I do not have a problem with creating a new content, the price range gets filled out properly. However, when editing this content, I get this error 'Price Range: Illegal value'. When I make this field permissible for this role, this field gets updated properly.

I'm quite sure there is a way to this without doing any complicated stuffs.

Thanks in advance!

I would use a Computed Field for this purpose, then you can define in PHP how to populate it.
Or you can populate it with a hook_nodeapi submit.


How to organise content using public, private and semi-private groups? I'm building a community website with Drupal Commons and I need to be able to create 3 kinds of groups:

public groups : anyone can view content, group members only can post/edit/delete content
private groups : group members only can view/post/edit/delete content
semi-private groups : authenticated users can view content, group members only can post/edit/delete content

How can I achieve this?

The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about the various types of roles used by the Group module, refer to my answer to "What are the various roles supported by the Group module?".

Resources

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