Is There a Generic Theme Duplication Module or Drush Command As I understand there are Drush commands for Adaptive Theme, Omega, Zen and maybe other themes for creating subthemes, but is there a more generic module/way to create/duplicate a theme?  It would be nice to give clients a way to mirror their theme within the interface.

No but you can copy the theme folder and then replace the name of the theme in all hooks and of course rename yourtheme.info to yourcopy.info. in order not to miss any hook you may use a prog like wingrep and search-replace the yourtheme string


Best way to make an EntityFieldQuery query be case sensitive? The case-sensitivity of queries created using EntityFieldQuery rely on the underlying database's collation [*]. So if the collation for a particular field is 'utf8_general_ci', then all the queries created with EntityFieldQuery are case insensitive.

Given that it's not always possible to change the schema (say, if you are developing a module that acts on third party fields) how can you ensure case sensitivity when using EntityFieldQuery ?

My solution so far consists of using a tag and a hook_query_TAG_alter hook to cast the value to a BINARY value (and EFQ allows us to create our own operator for this). Here is an example:

function mymodule_query_case_sensitive_alter($query) {
  foreach ($conditions as $index => $condition) {
    if (is_array($condition) && $condition['operator'] == '=c') {
      $placeholder = ':db_condition_placeholder_' . $query->nextPlaceHolder();
      $conditions[$index]['field'] = 'CAST(' . $conditions[$index]['field'] . ' AS BINARY) = ' . $placeholder;
      $conditions[$index]['value'] = array($placeholder => $conditions[$index]['value']);
      $conditions[$index]['operator'] = NULL;
    }
  }
}

Then one could run:

$r = (new EntityFieldQuery())
  ->fieldCondition('field_my_field', 'value', 'ExaMple', '=c')
  ->addTag('case_sensitive')
  ->execute();

Based on this, my questions are:

It is quite cumbersome. Is there really no simpler way ?
Does such a tag already exist ?
This is limited to MySql field storage backend - how could it be adapted to work on other field storage backends ?

[*] I am assuming a MySql field storage backend here.

MySQL documentation shows you can simply define collation at a query level:

SELECT k COLLATE latin1_german2_ci AS k1;

 SELECT *
 FROM t1
 WHERE _latin1 'Müller' COLLATE latin1_german2_ci = k;

 SELECT *
 FROM t1
 WHERE k LIKE _latin1 'Müller' COLLATE latin1_german2_ci;

If collation is only thing that affects case sensitivity for you, that's the way to go, no need to cast anything.

Based on this, you can set the operator in the EntityFieldQuery to be 'COLLATE utf8_general_cs ='. For instance the following will work:

$r = (new EntityFieldQuery())
  ->fieldCondition('field_my_field', 'value', 'eXample', 'COLLATE utf8_general_cs =')
  ->execute();

This remains limited to MySQL field storage backend however.


File module not updating field I have a File field for uploading pdfs. When editing the page, I remove the current pdf and upload a new pdf. The new pdf is uploaded to the server and add to the /sites/default/files folder and I can access the new pdf. However, the page still references the previous pdf that was uploaded.

I check the database and noticed that the new pdf was added to the files_managed and the files_usage tables but NOT the files table. Any idea why this would be and how I can get the File field to reference the latest uploaded pdf?

In a template, I have a db query for the file id, when I print the fid on the page, it shows the outdated file id instead of the new file id.

Are you clicking Save at the bottom of the edit page after uploading the new PDF?

You need to do this to save the file reference in the node field.


Making track of who has seen which content In a system with users number changing anytime, I need to make a system which shares content between them and makes track of who has seen which content.

Is there any module for doing it?

(I read about Flag module, but it is sharing one flag for all users, so it's not a good recommendation)

The solution is Seen module! Just read and use it


How to configure settings.php for Drupal site with Varnish and CDN? I am completely new to the back-end issues, so I would appreciate any detailed answers with explanation.

We need to configure our settings.php file so that it works with Varnish and CDN.  Currently, it's commented out by default.  I read the comments over and over in the settings.php, and it doesn't make much sense, or I don't know how to provide the information.

  In  the most simple scenario, the proxy server will add an
   X-Forwarded-For header to the request that contains the client IP
  address. However, HTTP headers are vulnerable to spoofing, where a
   malicious client could bypass restrictions by setting the
   X-Forwarded-For header directly. Therefore, Drupal's proxy configuration requires the IP addresses of all remote proxies to be specified in $conf['reverse_proxy_addresses'] to work correctly.

  ...

  In order for this setting to be used you must specify every possible
    reverse proxy IP address in $conf['reverse_proxy_addresses'].
   If a complete list of reverse proxies is not available in your
   environment (for example, if you use a CDN) you may set the
   $_SERVER['REMOTE_ADDR'] variable directly in settings.php.
   Be aware, however, that it is likely that this would allow IP
   address spoofing unless more advanced precautions are taken.

Several things that concern me:

What comments do I need to uncomment?
Since I'm using a CDN, I guess I'll have to use: $_SERVER['REMOTE_ADDR'].  But what are the "advanced precautions" available that I can take to prevent IP spoofing?

Thanks

If you don't know what you're doing (and to a certain extent even if you do) it's probably better to use modules to accomplish what you're trying to do:

Varnish
CDN

This is mainly due to the extra configuration and set-up help you get with the modules


How do I change the default height? 9 rows is just way too small by default. Is this a text-editor for ants?

I rolled a module for that now: https://www.drupal.org/project/ckeditorheight

  This module changes all ckeditor text fields to respect the "rows" setting of the field. How rows translate into pixels is a global setting, configured via a pixel factor and offset.


Warning: file_put_contents(temporary://): failed to open stream I get this message from Drupal:

Warning: file_put_contents(temporary://file8vyLsO): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (line 1900 of /home/donatelo/public_html/thenameofthesite.com/includes/file.inc).
The file could not be created.

I don't know what I did to cause this, can anyone help me?

Make sure your temporary folder exists and is writeable.

See the file system settings at:

admin/config/media/file-system


How to create a Webform pre-build option list via a query to an external database? I'm trying in Webform (version 4.9) to create a pre-build option list with data from an external database. A pre-build option list is an available list you get when creating a "select options" field in Webform (like list of countries, state, ...).

I didn't find an existing module that allows me to add such pre-build list to Webform.

So, first I added my external database information to the setting.php file.

To test it, I build a simple php page containing this:

db_set_active('external_db');
$query = db_query("SELECT id, name FROM TABLE")->fetchAllKeyed();
db_set_active();
Print_r($query);

And, it's working (= I got a correct result of my request).

So then I added this to my .module file:

function webform_pre_build_list_db_webform_select_options_info() {
    $items = array();
    $items['modeles_db'] = array(
        'title' => t('Modeles_db'),
        'options callback' => 'webform_pre_build_list_db'
    );

   return $items;
}

function webform_pre_build_list_db() {

db_set_active('external_db');

return db_query('SELECT id, name FROM table')->fetchAllKeyed();

db_set_active('default');

}

And, it's not working (= my list is empty).

If I try with a request to the Drupal DB, then, it's working. For example:

function webform_pre_build_list_db() {
return db_query('SELECT cid, recipients FROM contact')->fetchAllKeyed();
}

Is working well, I got recipients form drupal table "contact" in my list...

What am I missing?

Any help will be appreciated!

I changed this:

function webform_pre_build_list_db() {
db_set_active('external_db');
return db_query('SELECT id, name FROM table')->fetchAllKeyed();
db_set_active('default');
}

to this

function webform_pre_build_list_db() {
  db_set_active('external_db');
  $options = db_query('SELECT id, name FROM table')->fetchAllKeyed();
  db_set_active('default');
  return $options;
}

And it's working!

(Explanation: return immediately ends the execution of a function, in this case before db_set_active() could be called.)

Thanks to Nevets


Get book bid to display at search results page I'm trying to tweak my search results template to include the book root title at the bottom of every search results snippet. I have several books with very similar titles and content and i'd like to be able to print title of the book below each search result snippet so users know what they're going to get when they click search result.

I tried simply print $node->book['bid'] but it didn't print any result. I think it's because i have to somehow get the bid of a snippet and i'm getting bid of search results page which has no bid.

Am i right? And how i do that? I'm using Custom Search module to display my search results.

The book id bid is nothing more then the node id nid of the parent. Therefor if you have the bid, you still need to extract the title from the parent node.

$search_hit = $variables['result']['node']->nid; // The node id of the search result item
$node = node_load($search_hit); // Load the whole node whose search result we got
$parent_id = $node->book['bid']; // Extract the parent from the found node

$node2 = node_load($parent_id); // Load the parent node.
echo $node2->title; // This is the parent title.


Get nodes as options in a webform Any pointers gratefully received!

For Drupal 8.

I'm looking to use the image select webform element - but instead of the options being added when the webform element is created/edited we need to get the options from a content type.  This is partly because we need to have extra fields available to output from the content (so JS can show/hide) - but also the editors want to be able to control when various options are available - by using 'show after' dates etc.

So - we have a content type - called vehicle - with an image field and a car group field and a 'show after' date.  Ideally I'd like them to display in the same way as the current 'image select' webform element.  But any way of outputting the list of vehicles as options for a webform field would be great.  And I'm happy to output all the vehicles as there are not very many and the list will be further cut back by Javascript.

Thanks again!

This question is essentially asking the same thing as this previously answered question:
Programmatically change select field options in contact form

The accepted answer in the other thread describes how to set the select list from php code. You would alter the $options in the function provided to contain your vehicle list from SQL, a yaml file, or wherever.


How to programatically remove parent form taxonomy term? I try to remove programatically all parents form my taxonomy terms. But I can't get it working. I tried this code:

$vid = 18;
$tree = taxonomy_get_tree($vid);
foreach ($tree as $term) {
   $term->parents = null;  # Does not work
   $status = taxonomy_term_save($term);
}

But after saving (although the function returns 2) the parents are still there. What is wrong?

taxonomy_term_save() treats null as "do not change parent", and 0 means "this term does not have any parents". Also, property is named parent, not parents. Change

$term->parents = null;

to

$term->parent = 0;

and you're done.


Render all items of the main menu on one page i am building a overview page of my website.
My Main Menu has the following structure:

MenuItem1

submenuitem1
submenuitem2
submenuitemn

MenuItem2

submenuitem1
submenuitem2
submenuitemn

MenuItem3

submenuitem1
submenuitem2
submenuitemn

MenuItem4

submenuitem1
submenuitem2
submenuitemn

I want to render each Menuitem with his submenuitems in a different div and add an image to it.
I know i can work with the menu block module. But because we have the domain access module running and lots of domains, it has to be a coded solution. Each domain has his own main menu and should build dynamically the overview.

I managed to  output the whole main menu expandend with this code:

$main_menu_tree = menu_tree_all_data('main-menu');
$main_menu_expanded = menu_tree_output($main_menu_tree);
print render($main_menu_expanded);

How can i accomplish my mission ?

Thx

You can try with dhtml menu.

download dhtml module
http://drupal.org/project/dhtml_menu
Configure menu setting
admin/config/user-interface/dhtml_menu


Authorize.net Getting error "A valid amount is required." In our project we have used Commerce Authorize.Net module. We have not added any discount. No coupons are applied yet still when we proceed to checkout in testing mode we are always getting error as "A valid amount is required.". Our product price is $17.95 and when we get response from Authorize.net we are getting price as $-99.05 and hence payment is declined.

We have also used PayPal for payment method and it is working fine and giving proper amount for same product.

How can we solve this issue?

I got the solution of this issue.

When we were working in local we have removed orders from CMS before moving database to Dev site. But because of dependency some orders were not removed completely. When Authorize.net finds such orders it has treating them as pending order and was adding payment in new order as Unknown payment method.

Some how this was adding extra amounts to final payment of new orders and was creating negative amount.

To resolve this I have deleted all my dummy orders from CMS and also from Table "commerce_payment_transaction".

This has resolved my issue.
One of the Drupal's Stackexchange answer helped me to resolve this issue, Why would just adding a product to cart create a payment with method type "unknown" and credit card of "4111--------1111"


Drupal theme bare minimum I'm looking for the most absolute basic way to create a custom theme.  By this I mean, what are the absolute bare minimum requirements for Drupal to run my theme.  So, basically, I guess what files does Drupal need and what settings absolutely need to be specified?  I tried looking at the Theming Guide over at drupal.org but I didn't find it to be very helpful.

Cheers.

If you're using D7, it ships with the stark theme which is a pretty good example of how basic you can get.


Rules module not enabling via Drush in drupal 7 this may be a simple one however while downloading Rules through drush and getting the following error.

root@li:/var/www/drupal7/sites/default# drush en rules*

No release history was found for the requested project (i18n_string).[warning]
Module rules_i18n cannot be enabled because it depends on the        [error]
following modules which could not be found: i18n_string

I also tried doing drush dl il8n_rules but to no use.

What is wrong here?

You'll need the i18n module to install rules_i18n

drush dl i18n
drush en i18n_string
drush en rules*

Alternatively, enable the rules submodules individually, excluding rules_i18n


Inline entity form module fails when creating a new node and the reference method is Views I have a Drupal 8, core version:8.8.x project, i'm using inline entity form module(latest version) for entity reference fields. Also i have tried using entity connect module but it caused various issues. The problem is when creating a new node, using the inline entity form and the reference method of field is Views: Filter by an entity reference view this error is coming up:

This entity (node: newNode) cannot be referenced.

How to reproduce:

Install inline entity form module
Create an entity reference field in any content type with Views: Filter by an entity reference view as reference method.
To your content type manage form display choose inline entity form - complex for widget.
Add new node for your content type, press add new node to your reference field, fill the modal form, publish it and press create new node(referenced node).
Lastly publish and save your node.

I tried some patches published to project issues but most of them are not applying at all. I would appreciate any ideas for solving it or suggestions for using a similar module.

See patch located
Drupal core patch
#42 works with Drupal 8.9.2 give that a try, it should fix your problem.


How to create a component which has specific content on each page I'm a novice at drupal, so I'm still figuring things out. I'm looking for a way to accomplish the following the 'drupal way'.

I want to create a component, or a block, or something that allows the end user to enter a url to a page, a description, a title and an image. This component would be visible on the page as a clickable item.

I've tried using a custom content type, and used the views module to create a block out of these. This works, but it displays the same items as a block on each page. I need a way to make them different on each page. I'm not sure blocks is the way to go.

So, you need admin to be able to add one or two piece of content to a specific page.

Let's say you have content type Product content type.
For the custom content you can create a new content type, let's say Banner. Consists of these fields:

Title
Description
Image
Link
Reference to Product

Then you can simply create a Views which lists all Banners which have a reference to the current Product in the page. (Using contextual filters and the referenced field)

All Admin needs to do is to creates a Banner and indicate the Product to be displayed in.

You can also check Prepoulate module, for letting admin create the Banner straight from the Product edit page.


How do I set "Add to Cart form" css globally using Commerce Kickstart as basis? My goal is to borrow the Add to Cart form style from Commerce Kickstart on a site where:

Panels: Node Templates controls the Product Displays
Subtheme of Commerce Kickstart sets the CSS / template

Questions:

How do I find the CSS controlling the standard Commerce Kickstart Add to Cart form?
How do I use that CSS to control all "Add to Cart" widgets on the site?
Do I need to call out each Product Display type? Or is there a way to call it globally?
Related question: Why is the parent theme CSS being called? (There seems to be two levels of the Commerce Kickstart theme. One in .../themes/contrib and one in .../themes/commerce_kickstart_theme What's the difference? Are there two to share between the admin theme and site theme?

I am new to css, so am using "Inspect Element" to figure out how styles are applying to a given item. However, I can't figure out how to repurpose the css from Commerce Kickstart to apply to all "Add to Cart" widgets that are sprinkled throughout the site and control on a product-type basis through several Panels: Node Templates.

**These css callouts seem to be coming from the Kickstart theme, instead of the subtheme. I have enabled the subtheme and see changes I am making in the subtheme work, so I'm lost on why it is calling from the parent theme.
.../profiles/commerce_kickstart/themes/contrib/omega_kickstart/css/omega-kickstart-alpha-default-normal.css

From Inspect Element, I see that Commerce Kickstart shows:

For the attribute label:

.node-product-type .field-name-field-product form.commerce-add-to-cart label {
    float: left;
}

For the attribute drop-down:

element.style {
    width: 44.7778px;
    margin-right: 17px;
    text-align: right;
}

My solution is not elegant, but it got the job done:

Using inspect element, identified css that dictating styling of the "Add to Cart" form elements that I wanted to keep. This css was buried in the subtheme_style.css file associated with "Product" only: .node-product-type.
Copied css to start of subtheme_style.css file
Removed the references to .node-product-type. This set all the select widget fields and all the "Add to cart" buttons to the desired style/look.

This seems like an odd way to go, but also means that I don't have to differentiate among all product display types, as I build out panel displays that are unique to each one. What would you have done differently?

This is the css that I repurposed and generalized by deleting the reference to .node-product-type:

.field-name-field-product form.commerce-add-to-cart label {
  float: left;
  margin-right: 5px;
  width: 45%;}

.field-type-commerce-product-reference form.commerce-add-to-cart .form-submit {
      background-color: #9E4934; /*CG Add to Cart button*/
      background-image: url("../images/bg_add_to_cart.png");
      background-position: 90% 50%;
      /* LTR */
      background-repeat: no-repeat;
      border: 0;
      -moz-border-radius: 8px;
      -webkit-border-radius: 8px;
      -khtml-border-radius: 8px;
      border-radius: 8px;
      color: #ffffff;
      font-family: "Open Sans", sans-serif;
      font-size: 17px;
      font-weight: 400;
      float: right;
      margin-top: 40px;
      margin-left: 5px;
      /* LTR */
      padding: 5px 50px 5px 10px;
      /* LTR */ }

.field-type-commerce-product-reference form.commerce-add-to-cart .form-submit:hover {
        cursor: pointer; }


How to include most specific tpl files in a less specific tpl file? I created a view with fields. I want to print the values of the fields. So I use views-view-feilds.tpl.php . Also I created a views-view.tpl.php to show the outer html elements. I performed <?php
  include('views-view-fields.tpl.php');
?> in views-view.tpl.php file. I got the output as my requirement. But I need to know if its the right method according to drupal or any other method is available?

It can be difficult to track the way different template files are used. First, I recommend turning on theme debugging by putting this in your settings.php

$conf['theme_debug'] = TRUE;

See this documentation for more information about theme debugging: https://www.drupal.org/node/223440 The main thing to know about that option is that it will print out the file names of the templates being suggested.

For your specific question, php includes are not the mechanism by which themes reference other themes. Rather the variables in one template are often "render arrays" (arrays with a very particular structure that sets up certain template files to be called). Here is the documentation on Render arrays in Drupal 7: https://www.drupal.org/node/930760 Ultimately, changing the template file selected involves working with render arrays in one form or another.


How to to add a percent-based discount? Now during order edit it is possible to apply only a fixed discount. How to to add a percent-based discount?

You need to install (or perhaps just begin using) Commerce Discount.

Discounts are applied either to the individual product line items (product discounts) or the order total (order discounts).


Preprocess function trying to alter title I have used this code in template.php.

function mytemplate_preprocess_node(&$variables) {
  $variables['title'] = "trial" . check_plain($node->title);
}

I was trying to alter the page title, and wanted to make a test before. When I use that code, the title disappears from the teaser. Do you know why?

You shouldn't be using that to alter the page title, you can just use drupal_set_title();


How can I hide Delete option from Operations in Admin - Drupal 7 I have a user with a role with restricted permissions. The content type is restricted to "Edit" only. However, the Operations Select box still displays Delete.

Well, as I can check several checkboxes of different kind of content, that is correct. But the problem is that the user can continue to the next screen, where she is asked if she wants to delete the item. IMHO, this message should never display, because the user has no deletion permissions, so it is quite confusing.

Can I override this screen in a simple way, so it will not listed those nodes which have no deletion permission?

There is always more than one way to skin a drupal, but they are rarely of equal merit.

It sounds like you have a page that is using Views Bulk Operations?  If that is the case, find the view that generates the page and remove Delete from the operations selected.

If that is not the case, but you would like it to be, then see if the page in question is covered by Admin Views.  Enable the module, find the related view, and modify it to suit you.

If that also is not the case, then fortunately for you this interaction is a form of some type.  You can use a hook_form_ID_alter() function to change the $form['field']['#options'] array and remove Delete from it.  If php is not your language, I am sure there is a javascript method of doing the same thing ... but I don't like that, feels like too weak of a solution.  You can also have this same alter function check the global $user; $user->roles array so you retain the delete function for yourself.

If you want to let the user in question retain the Delete option, and just fail when they select that for a nodetype that is out of their permission range, then use drupal form validation.  This lets the form stay as it is, but if your check of the node types selected does not match up with the current user's roles then you can just fail their action before it reaches the next screen.

There is always more than one way, they may not all work for you but one of them should.  If none of these match your need then please update the question.


How to add js file in only 1 node? I made a custom js script for a little calculator. I want to use this in only 1 node (article or page) so I do not want to load it via tpl files etc because I do not need it sitewide. And also: if every custom script (that I use only in 1 node) has to be loaded sitewide I would get an immense head section after some time. Does anyone have experience with how to do this in a simple and safe way?

Thanks.
Frank

In the template.php you will write this small piece of code:

function MYTHEME_preprocess_node($vars) {
 if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'yournid') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/script/js");
 }
}

Replace foo with values related to your need.


image_style_url no longer creates images This started today on a website that has been running for over two months. I have a custom module that creates an image using the following code:

$image = image_style_url("catalogue_category_image_size", $product->field_product_image["und"][0]["uri"]);

This also did not work, but was the original code from earlier today:

$image = image_style_url("catalogue_category_image_size", $product->field_product_image["und"][0]["filename"]);

Here is the site, for reference: http://www.boudiccacollection.com/boudicca-catalog

I have no errors at all in the watchdog log or in apache logs. My status report page is green.

The only thing I would note is that the site was recently upgraded to drupal 7.23 from drupal 7.18

I have disabled clean url's to no avail.

EDIT I've added $conf['image_allow_insecure_derivatives'] = TRUE; to my settings.php and it did not correct the issue, however I now have error messages relating to 2 styles of one image (not all styles...)

Watchdog message:
     http://www.boudiccacollection.com/sites/default/files/styles/catalogue_category_image_size/public/BR004_WEB.jpg?itok=hetdMSsA
    http://www.boudiccacollection.com/boudicca-catalog
    Unable to generate the derived image located at public://styles/catalogue_category_image_size/public/BR004_WEB.jpg.

EDIT The same image is used in three places and works in one and not the other two.

Place 1 (broken):

URL: http://www.boudiccacollection.com/boudicca-catalog
Image: http://www.boudiccacollection.com/sites/default/files/styles/catalogue_category_image_size/public/BR004_WEB.jpg?itok=hetdMSsA

Place 2 (broken):

URL: http://www.boudiccacollection.com/boudicca-catalog
Image: http://www.boudiccacollection.com/sites/default/files/styles/catalogue_category_product_image_size/public/BR004_WEB.jpg?itok=SIXXe2Yq

Place 3 (works):

URL: http://www.boudiccacollection.com/br004-br004-four-corners-ring
Image: http://www.boudiccacollection.com/sites/default/files/styles/catalogue_product_image_size/public/BR004_WEB_0.jpg?itok=ZtLPZpD9

Place 3 has a different URL even though all of the code should be pulling the same image. Maybe this isn't an image_cache problem...

There was a change on the Image derivative URLs by the Drupal 7.20 update, as the 7.20 release notes also states:

The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)
As an example, links that previously pointed to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png will now point to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD_VaCaD.
In addition, any code which programmatically generates a link to an image derivative without using the standard image_style_url() API function will no longer work correctly if the image does not already exist in the file system, since the necessary token will not be present in the URL.


"Find Content" missing even though user has permission "Access the content overview page" Problem: User's "Add Content" menu item is available, but "Find Content" is not.

User has role Content Editor. Content Editor has permission for "Access the content overview page". User can access http://example.com/admin/content.

Clearing all caches does not fix the problem.

Problem: User's "Add Content" menu item is available, but "Find Content" is not.

Solution: Manually re-add the missing menu link.

How to add an item to the admin short menu...

Click Edit Shortcuts

Add a new shortcut

Enter a Title, A URL and then Save

You will now have the 'Find Content' shortcut in your admin shortcut bar as needed.

Side note:

If viewing admin/content you can also add the shortcut by simply clicking the + as noted in the graphic below:


Drupal 7 skip node in hook after node save In my custom module I am creating a node using node_save. I have also implemented hook_node_update to catch a user updated node. But every time I call node_save, it also calls my hook. Is there a way I can tell that this update was called using my node_save.
In Drupal 6, I used to add something like $node->skip_it = TRUE in before node_save, and this was available in the update hook. But not any more. Any pointers.

You can check using below condition while using node_save

  If $node->nid is omitted (or $node->is_new is TRUE), a new node will
  be added.

So, in your hook_node_update check for above condition before executing your code.


Use rules to assign role based off custom field on user registration I have a headless Drupal and I'm trying to figure out how to auto assign a role during registration based off of a custom field (field_is_student) in the registration form.

I am trying to use Rules but I don't know how to access the field to check whether it's true or false. My rule is set to "After saving a new user (rules_entity_insert:user)" and the only options I get in the condition Data Selector are User based.

Here's what I'm using to create my users:

{
    "name": {
        "value": "username"
    },
    "mail": {
        "value": "useremail@email.com"
    },
    "field_is_student":{
        "value": false
    }
}

The following Rule export does what you asked, for users created in the UI. In D8. I have tested it and it works. You will also need to use the (temporary) patch from https://www.drupal.org/project/rules/issues/2725525#comment-11438731 to work around the problem with in assigning roles.

The concept to understand is that Rules knows about the base fields for the entity type. But if you add fields, that's a new entity bundle, so you need to tell Rules that your data is of a certain bundle. To do that, you use the "Entity is of bundle" condition, as I show below. Then all the fields for that bundle will show up in the data selector.

langcode: en
status: true
dependencies: {  }
id: set_a_role_for_new_users
label: 'Set a role for new users.'
events:
  -
    event_name: 'rules_entity_insert:user'
description: 'Assign the ''student'' role to new users who identify themselves as students. Requires a boolean field ''field_is_student'' on the user object and requires an available role with machine id ''student''.'
tags: {  }
weight: 0
config_version: '3'
expression:
  id: rules_rule
  uuid: 36de9619-1401-4b21-a651-d3927c5b8dac
  weight: 0
  conditions:
    id: rules_and
    uuid: 416e90b0-d24c-4f37-8272-de0ecee5c375
    weight: 0
    conditions:
      -
        id: rules_condition
        uuid: bafe6fc4-f88f-4df2-af9b-2b3558257c2b
        weight: 0
        context_values:
          type: user
          bundle: user
        context_mapping:
          entity: user
        context_processors:
          type:
            rules_tokens: {  }
          bundle:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_bundle
        negate: false
      -
        id: rules_condition
        uuid: 28787d22-54ca-49cf-af42-6f1011ed6494
        weight: 0
        context_values:
          operation: '=='
          value: '1'
        context_mapping:
          data: user.field_is_student.value
        context_processors:
          operation:
            rules_tokens: {  }
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_data_comparison
        negate: false
  actions:
    id: rules_action_set
    uuid: 2933681a-a079-496d-bc79-f27ff53144eb
    weight: 0
    actions:
      -
        id: rules_action
        uuid: 38e8a3bb-0470-427f-80e1-53f6a703e8bf
        weight: 0
        context_values:
          roles:
            - student
        context_mapping:
          user: user
        context_processors:
          roles:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_user_role_add


Customizing the Access Denied Page I'm trying to modify the text that shows on the standard Access Denied page.  I created a module and tried to extend the core class but while module installs fine the page does not get modified.  My first question is can Access denied be customized?

Access Denied is an exception and if you want to have control over any aspect how this is handled the best place is an exception event subscriber, see How can we catch the acces denied exception in drupal 8 for the general aspects or Returning alternate HTTP codes for unpublished content in Drupal 8 for an example how to change a 403 to a 404 exception.

  I'm trying to modify the text that shows on the standard Access Denied
  page?

This question is specific for the text, see this answer for a 404 message, How to change page not found page error message in drupal 8?, replace it with 403 for an access denied message.

  My first question is can Access denied be customized?

The standard way is of course in the basic site settings admin/config/system/site-information.


Taxonomy and URL aliases I am developing a product catalog by means of taxonomy, and want to use URL aliases to better reflect the hierarchy. For example, I have a taxonomy product in the following branch:

category/subcategory/product

The thing I'm sort of surprised is that I have to paste the complete URL path instead of having it automatically glued up out of the aliases of the parent branches, ie. category + subcategory + product

Is there anything I'm doing/understanding wrong? Is that what you guys been through and accepted "as is"?

Artur

You will want to use the pathauto module. This will also required for you to install the token module.
Once you have those two modules install you will want to head over to the pathauto settings path at admin/build/path/pathauto.  You will see there's a field-set for Taxonomy. There is also replacements patterns which contains various different tokens you can use to generate your path.
In your case the pattern you want to use looks like this:
category/[catpath-raw]

This will automatically generate the path for those taxonomy terms based of these categories.
I assume most of this is for 6.x but the same concept applies for 7.x


How to send to redirect to a user after creating a node and display a message? I want to be able to re-direct a user after creating a node of a specific content type and then display a message.

How can I accomplish this? Is the best way by using rules modules or custom module ?

With a custom module, I do not know what hook I would have to use in order to trigger after content type is been publish.

I know that I can use the drupal_goto to redirect them + and used the  drupal_set_message to create a notification.

On the another hand, I know that using rules can be used to accomplish some of all this work.

The rules module can act on a "A new node has been created" event and has both "Page redirect" and "Display a message to a user" actions.


How do you make nodes automatically publish one by one after specific time? I'm going to do a comic site. I saw the MemeCenter. It automatically publish comics after 10 minutes. Is there a module to do this on Drupal?

You can use Rules module with rules scheduler, check this tutorial for better understanding on how to configure.

and also take a look at Scheduler module


Can Pressflow 7 be a drop-in replacement for Drupal 7? The Pressflow site mentions that it is used by many Drupal 6 sites, and in the FAQ, in answer to the question "What's the deal with Pressflow 7?" says

  Pressflow 6 made significant improvements to Drupal core in
  scalability and performance and most of these features have been
  contributed back to Drupal 7 core. Until well understood performance
  patches are created for Drupal 7 Pressflow development will be slow.
  Additionally, as Drupal 8 matures, significant enhancements will
  likely be backported to Pressflow 7.

That sounds to me like a very indirect way of implying that there are lots of problems with Pressflow 7 that cause people to avoid using it, but stated in a way that no one would understand unless they're already aware of the problems.  The answer seems like more of an explanation (indirect and implied) of why there are problems, than really an explanation of what the situation is with Pressflow 7.

So, can anyone tell me in plain English what the situation is?  Is there some reason I wouldn't want to replace a normal Drupal 7 site with Pressflow 7?  Or some reason it is simply impossible?  (Or is the problem simply that Pressflow 7 has not been optimized to the same degree that Pressflow 6 has?)

It's not that there are problems with Pressflow 7, but that there are no significant benefits to it at this time. This is stated in the lines above your quote:

  If your project is built on Drupal 7 you might not need to use
  Pressflow at this time because the key enhancements from Pressflow 6
  were added to Drupal 7.

You could use Pressflow 7 as a replacement, but why bother if there are no advantages? (I haven't actually used Pressflow 7 because of this).


Store custom messages displayed by \Drupal::messenger()->addMessage() in the database In a custom module, I have the following code:

\Drupal::messenger()->addMessage(t("Email changed to %email.", ['%email' => $new_email]));

I issue more than a dozen different messages in this way.

I want a way to store these messages in the database with a way to list them and edit them, assign an ID or keyword to each message, and then do the equivalent of

\Drupal::messenger()->addMessage(message_id, parameters);

I'm sure I can accomplish this by creating a "message" content type with keyword and message fields, adding a message node for each message, and then writing a function in my custom module that loads a node by keyword, inserts any variables, and then calls \Drupal::messenger()->addMessage() to display it. I could also create a View to list all messages for editing purposes. But it seems like there should be a better way that doesn't involve adding messages to the content of the site.

Is there a module or a built-in Drupal facility that does this?

My reading hasn't uncovered anything that looks like it will do these things. I realize Interface translation will support some of what I'm looking for, but don't know that it can be used with \Drupal::messenger()->addMessage().

The first thing to determine is whether you need your messages to be content or configuration. Content is (usually not) migrated between environments. It is created on an environment, and is unique to that environment. So your development environment may have one set of messages used for testing, and your production environment has another set of messages, used live.

Configuration on the other hand is migrated between environments. So you would create the messages on one environment, and when configuration is exported from that environment, the existing messages would be included in that export.

You probably want content entities.

How to create a new content entity type: https://www.drupal.org/docs/8/api/entity-api/creating-a-content-entity-type-in-drupal-8

How to create a new configuration entity type: https://www.drupal.org/docs/8/api/configuration-api/creating-a-configuration-entity-type-in-drupal-8

If you create a new content entity type, give the entity two fields, message_key and message_value. You will then load the entity as follows:

$entity = \Drupal::entityTypeManager()->getStorage('my_entity_type_id')->loadByProperties([
  'message_key' => $message_key,
]);

$message_value = NULL;
if ($entity) {
  $message_value = $entity->get('message_value')->value;
}

If you create a configuration entity, the ID of the entity will be the message key, and the entity only needs one more field for message value. The code above would be adjusted slightly:

$entity = \Drupal::entityTypeManager()->getStorage('my_entity_type_id')->loadByProperties([
  'id' => $message_key,
]);

$message_value = NULL;
if ($entity) {
  $message_value = $entity->get('message_value')->value;
}

The entity type you choose will become the storage mechanism for your messages, which you can then recover with the above methodology. Don't run $message_value through the t() function, as variables should not be run through that function, and translations of the message values are handled as translations of the entity, rather than the t() function.


Drupal 8.5 broken after simultaneously enabling many modules I installed D8 yesterday, and installed a bunch of modules today, then went into the "Extend" window and enabled a lot of them all at the same time (clearly not the best plan).  Now all I get on the site is

Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "devel.admin_settings" does not exist." at /path/to/drupal/core/lib/Drupal/Core/Routing/RouteProvider.php line 202

showing up in the error log.  I'm guessing I have to reset the database back to its initial condition.  Can I do that without reinstalling Drupal?

In the Drupal Slack channel, it was suggested I should try disabling modules using drush, starting with Devel since that appeared to be where the problem was coming from.  After

# drush pm-uninstall devel
The following extensions will be uninstalled: devel, ds_devel
Do you really want to continue? (y/n): y
devel was successfully uninstalled.                 [ok]
ds_devel was successfully uninstalled.              [ok]

the site's user interface came back to life, and I was able to install all of the modules I had previously selected, including Devel and Display Suite Devel.

I strongly suspect what happened is the error that terminated the initial attempt to enable modules

Maximum execution time of 30 seconds exceeded in /web/spacecolonists/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php on line 1005

occrured in the middle of processing the Devel installation, which broke it.

This tells me that module installations are not done as a transaction:  If they were, the timeout error would have caused the database transaction to fail, resulting in a rollback that left the database in a stable, working state.


Change add node select field to show data from 2 different fields of other content type I didn't know exactly how to ask this but the idea of what I need is very simple.

I have content type A with 2 fields: title and A2

Then I have another content type, B, with a node reference field (select box) that references title from node type A.

What I need is that the options in the select box are the concatenation of both title and A2 field.

Is this possible without coding my own module?

Install the Entity Reference module. It allows you to pull up information from one content type into another. Here is a super helpful tutorial of pretty much what you want to achieve so there is no need for me to provide detail explanation here.
https://atendesigngroup.com/blog/getting-started-references-drupal


How do I use query conditions? I want execute the query SELECT * FROM table WHERE type = 'AAA' AND id = 'BBB'.

The following code works.

$res = db_select('table', 's')
  ->fields('s')
  ->condition('type', $type)
  ->execute()
  ->fetch();

$res = db_select('table', 's')
  ->fields('s')
  ->condition('id', $id)
  ->execute()
  ->fetch();

The following code doesn't work.

$res = db_select('table', 's')
  ->fields('s')
  ->condition('type', $type)
  ->condition('id', $id)
  ->execute()
  ->fetch();

I get an error about the ID not being unique.

UPDATE:

Thanks and sorry. This code works well. I found error in another site.

The code:

$res = db_select('table', 's')
->fields('s')
->condition('type', $type)
->condition('id', $id)
->execute()
->fetch();

is not faulty in itself. The problem is probably that you don't have a record with matches both id and type. If you want to make an or query, you need to use db_or


How to view simpletest results? It looks like it's something obvious but I can't find the web interface to view simpletest results. Where should I view the errors besides the DB?

You can find the Simpletest interface at admin/config/development/testing

Be sure to clear your Drupal cache if you have enabled the Simpletest module and you cannot access admin/config/development/testing


How to hide a form element having a certain class in ajax callback in form? How can I hide the product using ajax callback . I am trying to implement that using ajax_commands_invoke but it does not work using below code

  $form['field_product_type_select']['und']['#ajax']= array('callback' => '_change_table_product_type','wrapper' => 'display-table-ajaxify');
 $header = array(
   'field_name' => t('Field Name'),
   'field_type' => t('Field Type'),
   'field_no_of_values' => t('Single/Multi Value'),
 );
 $options = array();

 foreach(commerce_product_types() as $product_type => $product_type_array){
   $field_info_instances = field_info_instances('commerce_product',$product_type);

   foreach($field_info_instances as $key => $value){
   $field_info_types = field_info_field_types($value['type']);
   $options[$key] = array(
     'field_name' => $value['label'],
     'field_type' => $field_info_types['label'],
     'field_no_of_values' => $value['cardinality'],
   );
  }

 $form['display_table'][$product_type] = array(
   '#type' => 'tableselect',
   '#options' => $options,
   '#header' => $header,
   '#multiple' => TRUE,
   '#prefix' => '
'.\
$product_type_array['name'].'',
   '#suffix' => '
',
 );
 }

function _change_table_product_type(&$form,&$form_state){
  $commands = array();
  $product_type = $form_state['values']['field_product_type_select']['und'][0]['value'];
  drupal_set_message($product_type);
  $commands[] = ajax_command_invoke('display-'.$product_type,'show');

  /* $product_type = $form_state['values']['field_product_type_select']['und'][0]['value']; */
  /* foreach ($form['display_table'] as $key => $value){ */
  /*   if ($key != $product_type) { */
  /*     unset($form['display_table'][$key]); */
  /*   } */

  /* } */
  //  return $form['display_table'][$product_type];
  //  return array('#type' => 'ajax', '#commands' => $commands);
  print ajax_render($commands);
}

AJAX Commands are supposed to be returned in the callback function, not printed. Also, you have to give a CSS valid selector.

Try this:

function _change_table_product_type(&$form,&$form_state){
  $commands = array();
  $product_type = $form_state['values']['field_product_type_select']['und'][0]['value'];
  drupal_set_message($product_type);
  $commands[] = ajax_command_invoke('.display-' . $product_type, 'show');

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

}

You can show the actual selector that code generates and test it in the JavaScript console. Just type:

 jQuery('CSS_SELECTOR').show();

If element is shown your CSS selector code is right.


Render a region e.g page.sidebar_first in views-view.html.twig Is it possible to render a region e.g sidebar_first in a views twig-file views-view.html.twig?

Not the region itself, but you can render the blocks with Twig Tweak, so simply add the blocks that are in that region to your template file.

  Twig Tweak module provides a Twig extension with some useful functions
  and filters that can improve development experience.

{# The block with this ID should be configured on "admin/structure/block" page. #}

Block:

{{ drupal_block('bartik_powered') }}


Tokens to change a block's visibility I am trying to make a block visible only to pages whose URL matches user/[current-user:uid]/downloads, but I don't get anywhere.

Do you have any idea on how to achieve this?

Fairly sure you can't do this from within the Blocks interface, but would be delighted learn otherwise.

A strategy to try would be to create a Views block that will display or not as required. A View over Users with a Contextual Filter that takes the Raw Value from URL, picking out a given path component, would be a start. You can then filter the view by User: Active.

If that all works out then your View will show. You can then get the content you want for your block by using a Rewrite of User: name field and, perhaps also, using Global: Text area in the header. (Well, you might be able to get the content this way. Depends on what's needed in the block.)

When you add the View block, you'll do something such as user/*/downloads, but the block will show depending on current user matching the contextual filter.


Cannot access Administration > People page I cannot access the People page.  There is no error message.  If I click on People in the menu bar, the Administration home page is shown.

The other Administration pages are accessible.

Similarly, if I click on Permissions for any module, I get the Administration home page; not the Administration > People page.

The User module is enabled.  I am logged-in as user #1.

I have checked the .htaccess file and do not see anything that would cause a problem.

I have tried disabling the handful of modules I have added.

What should I do next?

I'm not sure 100% if my solution will solve your issue or not but give it a try

first set base url in settings.php

$base_url = 'http://baseurl.com/Drupal/htdocs';

then check if clean urls enabled from

/?q=admin/config/search/clean-urls

just in case try to clear Drupal cache from

/?q=admin/config/development/performance


Import multilingual node in Drupal6 Suppose I have 100 nodes in language of English, I am going to import another 100 nodes with different language but same content.

I want to ask is there any module can establish the relationship between two node(with different language), as a result I can change to another language of the existing node by clicking the language switch button?

Thanks

Found a article at drupal.org and trying to implement it

http://drupal.org/node/907542


How do I get an array of user roles to use in #options? Trying to convert my module to D8 and running into a problem using the D7: user_roles() function. Here's my D7 module code:

$form['role_vis_settings']['tynt_roles'] = array(
  '#type'          => 'checkboxes',
  '#title'         => t('Add tracking for specific roles'),
  '#default_value' => variable_get('tynt_roles', array()),
  '#options'       => user_roles(),
  '#description'   => t('Add tracking only for the selected role(s). If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked.'),
);

And what I've got so far for D8:

$form['role_vis_settings']['tynt_roles'] = array(
  '#type'          => 'checkboxes',
  '#title'         => $this->t('Add tracking for specific roles'),
  '#default_value' => $settings['tynt_roles'],
  '#options'       => user_roles(),
  '#description'   => $this->t('Add tracking only for the selected role(s). If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked.'),
);

But get:

The website encountered an unexpected error. Please try again later.

I've looked at:

https://api.drupal.org/api/drupal/core!modules!user!src!Entity!User.php/function/User%3A%3AgetRoles/8
https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user_roles/8

The second was closet but not a format the #options array would allow (https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/8#options).

Anyone have any ideas?

The correct function name is:

user_role_names()


Redirect unauthorized user to login page I need to show only home page and some inner pages (which i will create using a common content type) to the anonymous user. I need to redirect all other access to home page where i added a login box. Is there a way to do it.

In the permissions, make sure anonymous users don't have access. Then go to Configuration -> System -> Site information (admin/config/system/site-information). At the bottom, put your home page in 'Default 403 (access denied) page'.

All traffic going to an unaccessible page, will be redirected here.


Override a single JavaScript file from a module In my theme's libraries.yml file, after the global-styling section, i'm trying to replace one JavaScript file from the core Toolbar module (it's addition of padding-top to body interferes with our theme, so just changing that to margin-top).

libraries-override:
  toolbar/toolbar:
    js:
      js/views/BodyVisualView.js: js/views/BodyVisualView.js

I repeatedly get the error:

  Drupal\Core\Asset\Exception\IncompleteLibraryDefinitionException:
  Incomplete library definition for definition 'libraries-override' in
  extension 'mythemename' in
  Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension() (line 93
  of
  /vagrant/web/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php).

The answer is simply that the libraries-override definition must go in the .info.yml not .libraries.yml:

So in mythemename.info.yml:

libraries:
  - mythemename/global-styling
libraries-override:
  toolbar/toolbar:
    js:
      js/views/BodyVisualView.js: js/views/BodyVisualView.js

If placed logically there, alongside the libraries definition, it works perfectly.

Note that the second 'toolbar' is the library name from toolbar.libraries.yml, other library names in there include toolbar.menu, so if overriding a file from there it would be "toolbar/toolbar.menu:" instead of "toolbar/toolbar:".


Rated user interests I would like to create rated inteterests for each user.
Until now what I have is a taxonomy term vocabulary defined and a field in the user account attached to this vocabulary.
Until here what a user can do is to check or not each term of the vocabulary, using the widget options_list.
What I would like to do is to let the user select the level (0-10) of preference for each term.

I've tried to create a custom field with two columns, tid and value, then linking each tid with taxonomy term in hook_field_widget_form, but no luck as I'm not an expert in fields, so I'm confused about how to implement:

/**
 * Implements hook_field_widget_form().
 */
function taxonomy_value_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $tids = isset($items[$delta]['tid']) ? $items[$delta]['tid'] : array();
  $values = isset($items[$delta]['value']) ? $items[$delta]['value'] : array();
  $element += array(
    '#delta' => $delta,
  );

  switch ($instance['widget']['type']) {

    case 'taxonomy_value_widget':
      if ($vocabulary = taxonomy_vocabulary_machine_name_load('tags')) {
        if ($terms = taxonomy_get_tree($vocabulary->vid)) {
          foreach ($terms as $term) {
            if ($term->depth == 0) {
              $element[$term->tid] = array(
                '#markup'  => '
' . $term->name . '',
              );
            } else {
              $element[$term->tid]['term'] = array(
                '#markup'  => '
' . $term->name,
              );

              $element[$term->tid]['tid'] = array(
                '#type'          => 'value',
                '#value'         => $term->tid,
              );

              $element[$term->tid]['value'] = array(
                '#type'          => 'textfield',
                '#value'         => in_array($term->tid, $values) ? $values[$term->tid] : 5,
              );

            }
          }
        }
      }

      break;
  }

  return $element;
}


Show breadcrumb on forum only I want to show the breadcrumb on the forum only. I am using the advanced forum module. How can I do this in Drupal 7?

I recommend you try the Disable Breadcrumbs module.

  Disable breadcrumbs on a per node, per content type, or by path (any path) basis; Omitting the need to write additional code in the theme layer (template.php file etc..) to determine the visibilty of breadcrumbs on specific pages. This can be administered on node edit forms and from the content administration page (node operations) to select/unselect multiple nodes for enabled types.


Creating the custom url aliases for nodes? I had a problem with making custom url aliases for drupal node pages.Basically my website have two articles types parent articles and child articles. Each parent article contains many child articles. So the each parent articles shows all  it's child articles in pagination.
current format
parent article : http://example.com/parent-title
child  article : http://example.com/parent-title?page=1, http://example.com/parent-title?page=2 go to each child artilces of parent article.

however I want to insert title of the child article as url alias so expected format is
http://example.com/parent-title/child-title?page=1

How can i insert that child article title as url alias? I need this because this is very good for SEO purposes.

You can use the Path Auto module for this purpose. It has many patterns options for each content type.

You can generate alises pattern for child articles and parent article separately.
I have added a screenshot that how it looks in the back end.

If it does not fulfill your requirement then we can customize the urls on saving with hook_url_inbound_alter() function in our custom module.


Ajax button doesn't work I followed this tutorial:
https://rapiddg.com/blog/creating-ajax-callback-user-reference-fields

to create a button to fill some field in a form with the values of the current user.

Here the cose I added to my hoo_form_alter:

if ($form_id == 'datore_node_form')
{
global $user;
  $form['title']['#type'] = 'hidden';
  $form['title']['#value'] = 'test';

$form['user_replace'] = array(
    '#title' => t("User Information"),
    '#prefix' => '
',
    //name of the node form (already existing, if you're modifying an existing node form)
    '#suffix' =>'
',

    $form['user_replace']['user_copy'] = array(
      '#type' => 'button',
      '#value' => 'Sono io il datore!',
      '#ajax' => array(
        'event'=>'click',
        'callback' =>'user_replace_ajax_callback',
        'wrapper' => 'datore_node_form_group_cs',
      ),
    ),
  );

 $form['user_replace']['field_cognome'] = $form['field_cognome'];
  unset($form['field_cognome']);

  $user = user_load($user->uid);
  dpm($user);
  dpm($user->field_cognome['und'][0]['value']);
  dpm($form);
  dpm($form_state);

  if (!empty($form_state['values']['field_cognome']))
  {
    unset($form_state['input']['field_cognome']['und'][0]['value']);
    $form_state['input']['field_cognome']['und'][0]['value'] = $user->field_cognome['und'][0]['value'];
    return $form;
  }

  function user_replace_ajax_callback($form, &$form_state)
  {
    ajax_command_alert("hello"); // doesn't work
    return $form['user_replace'];
  }

but if I click the button nothing happen.
Any advise?

The only thing you are doing with your code is replacing the button that you are clicking. It's probably getting replaced, but visually will look exactly the same as it did before, which is why it appears nothing is happening.


When I try to browse to a site I get the localhost default page (WampServer) I use WampServer, and just installed a theme drupal (Jollyany) on localhost, but when I click to explore the site, this sends me to localhost default page:

I try to see what happens when i get on the hosting. ... get me the following error:

Please help

Do you have properly configured /sites/defaults/settings.php? Looks like somthing in your connection is wrong, it can be database name, username or/and password.


How to Port customField PHP from Drupal 6 Views 2 to Drupal 7 Views 3 I have this piece of code that was in a Drupal 6 Views 2 customField PHP that I need to port to Drupal 7 Views 3 in a Global: PHP field but I can't figure why I get an empty ajax error upon building this code in the Global: PHP field value code.

Did the accessibles variables changed?

<?php
//var_dump($data);
if ($data->node_type=="project") {
echo "node/".$data->nid;
}
else
{
echo $data->node_data_field_slider_include_field_slider_link_value;
}
?>

ANSWER

You need to remove the <?php ?> tags.


How do i implement symmetric relationship with node reference module in drupal 7? i have a content type with one node reference field to same content type and so i related that content type as like  A->B,B->C,C->D,D->E and so on.But i want to relate E to C,B and A along with D automatically and so i can list out all A,B,C & D in E node page as referenced nodes.Can you tell me how can i implement this type of references in Drupal 7?

I suggest you to look at the relation module. It allows creations of symmetric associations which involve more than to entities. Haven't tried it myself, though.


How do I embed a node creation form inside a view I have a View with some fields and a couple of link items.

What I want to do is when I click on the link items, a node creation form associated with link should appear inside the view (the AJAX way).

The solution that I can think of is to embed the forms inside the view, but have no idea how to do that?

What is the best way to implement this?

Hope this will help you,

In Drupal 7 you can achieve by the following steps

You can embed a node creation form inside a VIEW

Either in VIEW Header or you can created a new VIEW and attach it to your VIEW

For this example I am embedding inside Views Header. Embedding inside Views Header will be the better options. Click to Add Views Header

Select Global: Text area

Add the PHP code and don't forget to change the Text Format to PHP

PHP code

<?php
    module_load_include('inc', 'node', 'node.pages');
    $node_form = node_add('node_type');
    print drupal_render($node_form);
?>

Note :

Don't forget to replace node_type in the PHP code.
Use hook_form_alter for node form redirection, as after the node creation the form will redirect to node detail page. If you want to redirect to your page then use $form_state['redirect'] = 'mycustompage'; reference
Enable PHP Filter module using admin/modules

Set the Permissions for this module by enabling "Administrator" for Execute PHP Code as follows:

If any one has better solution, please share it.


How do I set a cookie? I need to save a cookie for anonymous users in Drupal 8 when users visit the site for the first time, which will be used to display a message.

I can successfully save one using setcookie("FirstTimer", 1, strtotime('+1 year')); but I am sure Drupal 8 should have some alternatives.

I can also use the following code.

$user_is_first_timer = !isset($_COOKIE["Drupal_visitor_FirstTimer"]);

When I open it in Google Chrome, this works, but when I open it in incognito or in Firefox, there is no message. Somehow cached pages are being served.

The code is used in an implementation of hook_page_attachments().

With Drupal 7, Drupal 8, and Drupal 9 you can use user_cookie_save() to store a cookie.
function user_cookie_save(array $values) {
  foreach ($values as $field => $value) {
    // Set cookie for 365 days.
    setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  }
}

The first function parameter is an array. Its keys are the names of the cookies to set; its values are the values to set for those cookies.
user_cookie_save() doesn't allow to set when a cookie expires; cookies created with this function expires after 365 days.
There is just a method in Drupal 8 core class that uses user_cookie_save(): SystemController::compactPage().
public function compactPage($mode) {
  user_cookie_save(['admin_compact_mode' => $mode == 'on']);
  return $this->redirect('<front>');
}

Unfortunately, there isn't an equivalent function to read a cookie. Drupal 8 and Drupal 9, to read the cookie saved from SystemController::compactPage() uses system_admin_compact_mode().
function system_admin_compact_mode() {
  // PHP converts dots into underscores in cookie names to avoid problems with
  // its parser, so we use a converted cookie name.
  return \Drupal::request()->cookies->get('Drupal_visitor_admin_compact_mode', \Drupal::config('system.site')->get('admin_compact_mode'));
}

The other function/method I found that stores cookies in Drupal 8 and Drupal 9 is BigPipeController::setNoJsCookie() (implemented since Drupal 8.1.x) which uses the following code.
if ($request->cookies->has(BigPipeStrategy::NOJS_COOKIE) || !$request->hasSession()) {
  throw new AccessDeniedHttpException();
}
if (!$request->query->has('destination')) {
  throw new HttpException(400, 'The original location is missing.');
}
$response = new LocalRedirectResponse($request->query->get('destination'));

// Set cookie without httpOnly, so that JavaScript can delete it.
$response->headers->setCookie(new Cookie(BigPipeStrategy::NOJS_COOKIE, TRUE, 0, '/', NULL, FALSE, FALSE, FALSE, NULL));
$response->addCacheableDependency((new CacheableMetadata())
  ->addCacheContexts([
    'cookies:' . BigPipeStrategy::NOJS_COOKIE,
    'session.exists',
  ]));
return $response;

Using $response->headers->setCookie() gives more control over the cookie parameters (the parameters Cookie::__construct() accepts).


Include custom Product Fields in an email I have added a new "Courses" Product Type that has a field called "Course Link". The store admin can add a url to this field and we want to email the value to the customer after they purchase.

I have a Rule to fire on "Completing the checkout process" with action "Send HTML e-mail" and the email includes the token [commerce-order:commerce_line_items]  This is all working except my "Course Link" field is not included in the email. I do not have a token for "Course Link" field listed to include in the email.

I do have the "Course Link" field included under "Product Types > Courses > Manage Display > Line Item". Not sure what that even does.

My question is what should I be looking at to do this.

Try to bring it into scope in my current emailing Rule? Possibly through a Component that loops through line items and provides a value back?
Add it in the View that drives the [commerce-order:commerce_line_items] token?
A module like Commerce Messages or Commerce Invoice Receipt?
Some other approach?

The solution here (Drupal Commerce - Add Product Fields to Cart Form through Line Items) for adding Product Fields to the Cart View answered my question.

I edited the "Line Item" View to include my custom Product Field.  This is the View that drives the [commerce-order:commerce_line_items] token but per the answer linked above:

For that you'll need to add I believe the "Commerce Line Item: Referenced Products" relationship in the view.

You also need to give anonymous users the Permission "View own orders of any type" (I also gave them "View own Order Orders" but probably not needed) or the email says "No Line Items Found" for anonymous checkouts.


Create user accounts from a content type I have Drupal 7 website. Initial requirement was to accept membership from public (anonymous users) without creating a user account. So the plan was to create a content type called ‘membership’ that has the fields Name, email address, mobile number, a unique alphanumeric ID and other fields for personal/professional details.

Now the requirement is changed and need to create a user account for each of this ‘membership’ type of content.

Is there any way to create user accounts from each of existing content of the type ‘Membership’ by fetching email id from the ‘email field’ and password from the ‘unique alphanumeric ID’ field (or some other means)?

One solution is using VBO module, create a view with what content type you want ("membership") then perform a run a PHP code operation on them, and put something like this in Php code

$name = $entity->title; //fill it with what field you want
$email = $entity->YOUR_EMAIL_FIELD_MACHINE_NAME['und'][0]['value'];
$pass = $entity->YOUR_PASS_FIELD_MACHINE_NAME['und'][0]['value'];
$new_user = array(
  'name' => $name,
  'pass' => $pass, // note: do not use md5
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);

and another solution is create your custom Batch operation   and try some thing like up snippet.


Update user when node is created I'm new in Drupal 8 and I need to update the user when a node of a specific content type is created or updated.
I did some searching and I find hook_entity_create but this hook Act when creating a new entity

/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function MYMODULE_node_insert(Drupal\node\NodeInterface $node) {

  if($node->bundle() == 'article') { //check for a content type, ex: article
    $user = \Drupal\user\Entity\User::load($uid); // load the user
    $user->set('field_name', $some_value); // set a value for a particular field
    $user->save();
  }

}

Originally I wrote:

MYMODULE_node_create(Drupal\node\NodeInterface $node) {

Changed it as per the comment below.


Send Email when node has been updated with specific term/selection I am looking for a way to configure a Drupal site to automatically send an email when a certain selection is made. Specifically, I have a content type with a field that presents the option 'In Progress' or 'Complete', and I would like to trigger an email when someone marks an instance of the content type as 'Complete.'

Not sure how to do this. Any help is appreciated!

In rules Add Condition >> Data Comparison >> node:field-[name of your field goes here]

Add Action >> Send Mail


How do you style an individual webform? How to style individual webforms with  different css class and html elements?I have a few webforms and I need different html elements like divs, spans etc and css class for each webforms

If you just need to apply CSS styling, then if you view the source of the webforms you will see they have container divs with classes that contain an ID number. This ID will allow you to directly target a specific webform.

If you mean you want to add your own divs etc. and template different webforms, then the best way to do this is by creating a specific template file for it.

In your theme folder you can add a template file such as:
webform-form-[nid].tpl.php you can get the ID by viewing the source of your form, it displays in one of the forms parent divs.

As your base you can use the default template from the webforms module. Goto (or other location where you have installed the webforms module):

/sites/all/modules/webform/templates/webform-form.tpl.php

and make a copy of this.

I have themed webforms that appear in blocks in the following way too:

block--webform--client-block-112.tpl.php


Plupload widget type not appearing This is what I've done so far:

Installed & enabled the Plupload integration module in my drupal website (version 7.x-1.7)
Added Plupload library to my libraries directory (version 1.5.8)

In my status report I see that he can find the plupload library:

Now when I want to add an Image I only get the widget type Image and not the Pupload option. What could be the problem of this?

You need a combination of modules:

https://www.drupal.org/project/filefield_sources_plupload
https://www.drupal.org/project/filefield_sources
https://www.drupal.org/project/plupload

I have intentionally left these as URLs as these module are often confused between each other.

In the content type which you wish to use the plupload widget: manage fields > images > edit.
Scroll down until you see "File Sources", expand and select "Advanced Upload Widget (Plupload).

These basic steps should give you the option to use plupload when uploading images. You can further change the setting to allow a specific number of images etc.


How to get a count of groups that user has joined? I have used OG module to implement the Groups functionality. I want to get:

Count of all groups that are there on the website
Count of groups that a user has joined

How can I do this?

Note:
My preference would be to use an existing function (if there is any).

To get Count of all groups....

$groups = og_get_all_group($group_type = 'node');
$count = count($groups);

To get User Groups Count

$user_groups = og_get_groups_by_user();
$user_count = count($user_groups);


EntityQuery condition "is not equal to..." Problem :

I need filtering entities based on the value of a multiple-choice field.
I want my query returns all entities except those who have a given value ('doe' for this example).

Actual :

multiple-choice values

foo|Choice 1
bar|Choice 2
doe|Choice 3

MyController.php

$query = \Drupal::entityQuery('node')
       ->condition('type', 'order');
$nids = $query->execute();
$entities = \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);

Need :

So I need something like below :

$query = \Drupal::entityQuery('node')
       ->condition('type', 'order')
       ->condition('field_multiple_choice', '!=', 'doe');
$nids = $query->execute();
$entities = \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);

How can I do ?
Thank you in advance.

I found it !

I was not far away, I've just to reverse the last two parameters of the condition.

$query = \Drupal::entityQuery('node')
       ->condition('type', 'order')
       ->condition('field_multiple_choice', 'doe', '!=');
$nids = $query->execute();
$entities = \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);

  As the doc says, public function
  QueryInterface::condition
  take following arguments :

condition( $field , $value = NULL , $operator = NULL , $langcode = NULL )


Same secondary menu bar on different pages and lead to different content not sure if I can describe the situation clearly, here is the thing:

I am using D7. I have this site: there are three menu items in the main menu will lead to three product pages, their layout will be identical: start with a product image, then a secondary menu bar and the according content according to the secondary selected menu item. I intend to use a same custom node template for the three pages, and put different content into the fields I determined.

the secondary menu bar should be identical on all three pages, which may contains these menu items: Features, Technical Specs, Sales, Support.

When someone clicks on the main menu items, they will go to the product with the right image on the top and the url like mysite.com/PRODUCT_A. When someone then clicks the secondary menu items, the product image and the layout on the page remain the same, but the according content will show up in the content area. And the url will be mysite.com/PRODUCT_A#feature

A layout like this:

PRODUCT A | PRODUCT B | PRODUCT C

[PRODUCT B IMAGE]

features|technical specs|sales|support

[these are the features about PRODUCT B...]

Any I probably will use View for the content blocks, but I cannot get my head around how exactly I can make the whole thing dynamic enough for the administrator to add content comfortable. Also to get the right url dynamically.  Any thoughts please? Thanks a lot!

If you are just using hashes to flip between hidden divs on the page, then the submenu needs to just be relative to the current location like | sales | and your main menu would just have the paths to the nodes like | PRODUCT A |

This might seem like a pointless answer, but if my assumption about you using the hashes to switch the tabs, then the solution is super simple. You just need to create the submenu in code in the template since the admin-based custom menu system won't let you do relative hashes (I don't think so anyway)


Obtaining SUM('field') in PHP code Can't figure out how to construct a query to obtain a sum of a field programmatically. The folowing code works fine for counts:

$count = Drupal::entityQuery('node')
  ->condition('type', 'artefacts')
  ->condition('status', '1')
  ->condition('default_langcode', 1)
  ->condition('field_city', $id)
  ->count()
  ->execute();

but no matter how I try I can't figure out how to obtain the sum. There is a lot of examples for Drupal 7 but can't find a single one for Drupal 8.

$sum = Drupal::entityQuery('node')
  ->condition('type', 'cities')
  ->condition('status', '1')
  ->condition('default_langcode', 1)
  ->condition('field_country', $id)
  ->aggregate('sum(field_artefact_count)', 'total')
  ->execute();

seems to return '1' in any circumstances. The documentation on Query class is terse to put it mildly. Apparently execute() is supposed to return an array of entity id's but what's the entity id of a single total of a table of a 1000 records?

Use QueryAggregateInterface::execute:

$result = \Drupal::entityQueryAggregate('node')
  ->aggregate('nid', 'sum')
  ->condition('status', NodeInterface::PUBLISHED)
  ->execute();

The result returned is keyed by fieldname and aggregate function:

$sum = $result['0']['nid_sum'];


Why responsive panels are not one beside another by default? I am using the adaptive theme with panels, mini panels, panels everywhere, and AT Panels Everywhere. My site default template is of at panels everywhere.

I built a 5 column mini panel for the footer. I assigned for each column only one thing: menu, or a logo, or "powered by drupal".

When I am using the builder layout for the mini panel, and build 5 column - every thing works fine, and I have 5 column one beside another, in only one row. (although, I am trying to avoid the builder and use only AT layouts).

But, If I am using the "AT responsive panel - 4,5,6 column" for the mini panel layout, the result is that my footer has two rows: top row is with 2 panels and bottom row is with 3 panels. it  looks like the blocks or something are too big, and the AT layout is just being responsive.

I tried to solve that and make it one row, and add to each panel a class, and made them very narrow. but that didn't work, and I still have 2 rows, even though the panels are very narrow and can feat perfectly in one row (5 columns).

How can I make sure that every panel will use 20% of it's layout (when possible), and all will be presented in one row, 5 columns side by side?

Here is the problem:

Here is the footer code:

The footer is still in two rows, and looks like that:

What causing the AT mini panel to think it has no room, and need to change the layout?

This can be done CSS only:

Apply a width and float to all panels in the footer:

#footer .region {
  float:left;
  width:20%;
}

Or make them a little smaller so you can apply margins to 'm.


Why drush fails with undefined function conf_path() error? Here's a weird one: I've got two nearly identical server setups, both running Drush 5.9. Both have been happy for a while. Went to use one today, and got the error:

Drush 5.9 does not support Drupal . Use Drush 4 instead.
PHP Fatal error: Call to undefined function conf_path() in /var/opt/drush/includes/bootstrap.inc, line 786

The other site runs Drush 5.9 just fine.  Any ideas?

Without knowing what command you're trying to run or your file structure, it's difficult to say.

Most commonly this happens when your drush has trouble bootstraping your Drupal root, either by corrupted Drupal core files or different loading the wrong files.

In example if you run drush inside Panels module directory it fails, because it contains includes/common.inc file and drush is confused that it's Drupal core version of common.inc so it's loading it and expects that conf_path() should be defined. The same with core/includes/common.inc. Check the _drush_bootstrap_drupal_site_validate() function at drush API site.

I believe this has been fixed in the recent drush (see #60 at GitHub and original issue), so please upgrade it to the recent version (see the instructions).

However in some other circumstances the problem is still happening (#937) for some reason.


Create a simple quiz for each video I have a "video" content type, and I want from users watching my videos to answer some questions related to each single video.

Can you advice me, how can I create a quiz for each single video content ?
Is there a module (I tried the quiz module but it's very complicated) to do that, or any other way will be apprecited.

thanks in advance.

You can use the Webform module to create a quiz.
Here is a quote about it (from the module's project page):

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.
Some good examples could be contests, personalized contact forms, or petitions. Each of these could have a customized form for end-users to fill out. If you need to build a lot of customized, one-off forms, Webform is a more suitable solution than creating content types and using CCK or Field module.


Product View does not show for Anonymous user I would like to use a view to display products in front page. So, in the view 'Products (Commerce Product)' i created separate block view 'My Products Block'. This view is added to the region in Block section and then rendered in the front page:

print render($page['region_containing_product_view']);

This displays products fine if logged in as admin but not for anonymous users. For anonymous users it shows:

No products have been created yet. Add a product.

I have updated the permissions for my custom view to 'Access:Role | anonymous user' but it still doesn't show the products. How come? what am i doing wrong?

Thank You
p.s. Drupal 7, Commerce module

It turns out for every product type created there is permissions that need to be enabled for every user roles including anonymous users

'people-permissions-roles'


Change icon class in "Add to cart" button I am using Drupal 7, Ubercart, and Bootstrap. The default Add to cart button looks like this:

<button id="edit-submit-270" class="node-add-to-cart btn btn-success form-submit" value="Add to cart" name="op" type="submit">

  Add to cart
</button>

How can I change the  class  from glyphicon-plus to glyphicon-shopping-cart?

Simple Solution is achieving it with simple Jquery line

$('span.icon.glyphicon.glyphicon-plus').removeClass('glyphicon-plus').addClass('glyphicon-shopping-cart');


Change the output of the search results I'd like to change the output of the search result page.

For example, I've got 3 different content types: foo, bar, etc. I'd like to group my search results by these content types, so that for every content type the first three or so results are shown followed by a link: "View more results for content-type foo" which will lead you to a page where all results of this specific content type are shown.

I've done some researching and couldn't find a module which does something like this. I guess i have to write my own module, but I don't know where to begin. Do you have any tips for me (whick hooks to implement, etc...)

If you only have 3 types and you don't plan on changing often, the easiest way to do that might be to create views of those three content types and use views_embed_view.

You could potentially override the search results in your theme using search-results.tpl.php. A more complex, and possibly better way would be to write a custom module that implements hook_menu_alter and redirects the default search callback to a custom view in your module.

I have done something like that before and it's not a trivial undertaking (take a look at the apachesolr_search module if you want a complete example).

Something like (untested)...

function mymodule_menu_alter(&$menu) {
  if (isset($menu['search/mymodulesearch/%menu_tail'])) {
    // redirect default search to this module's view
    $menu['search']['page callback'] = 'mymodule_search_view';
    // create a menu linkspecifically for this view
    $menu['search/mymodulesearch/%menu_tail']['page callback'] = 'mymodule_search_view';
    $menu['search/mymodulesearch/%menu_tail']['weight'] = -20;
  }
}

function mymodule_search_view() {
  $keys = search_get_keys();

  // do something with views_embed_view here
}


Advanced Forum permissions I have installed the Advanced Forum module for Drupal 7.10.

How can I set permissions for each forum I make? I want only administrators to have the "admin forum" permission, and not authenticated users.

Is that possible?

The Forum Access module works in Drupal 7, so I'll stick to this for now.

  This module changes your forum administration page to allow you to set forums private. You can control what user roles can view, edit, delete, and post to each forum. You can also give each forum a list of users who have administrative access on that forum (AKA moderators).

  This module requires the ACL module in order to function. The D7 version also requires the Chain Menu Access API module.


How to build a dynamic menu structure I'm building a module for which I want to create two dynamic menus: one main menu with each menu item being a group name that the user belongs to (the groups come from a different database) and a secondary menu with a fixed set of menu items that manipulate specific properties of the group selected in the main menu (for example show group members).

What would be a good approach to do this? I found this question that shows how to create a menu within a module, but I'm not sure how to tackle the dynamic part of the menu items. Each user can have a different main menu, depending on the groups the user is part of, and the secondary menu items need to pass the group id of the selected main menu item. Next to hook_menu, I suppose I need to do something with wildcards, but I've never worked with those in menus so I'm not sure.

I would like to be able to use the menus as a source for primary and secondary menus in different themes, so I'm flexible with changing the site appearance by selecting another theme. I'm using Drupal  7.

I found a way to do this, but I'm still interested to know if this is the right approach (and if bad things will happen with a very large number of groups and users).

Both menus are created using hook_enable in the install file of the module (the development module is an excellent example on how to do this).

Like I say in my comment, I don't think you can create dynamic menu items so I'm creating a menu item for each group (when a group is added, I need to do a menu_rebuild). To determine if the menu item should be visible for a user, I created an access callback that checks if a user is part of that group. This callback will be called with every page request, so it will always work.

The secondary menu works with a wildcard and a to_arg function. For example, a menu item is set as $items['pmenu/%get_groupid/grouppage'] and in the function get_groupid_to_arg($arg) I'm extracting the groupid from the path with arg(1), which is returned (for details see hook_menu and the Menu example). The secondary menu items also use the same access callback to check if the user may see the menu item.

Finally I had to apply a fix for the theme, because the corresponding primary or parent menu item (group) would not be set as active if a secondary menu item was selected. I'm using Marinelli and applied the patch in comment 14 of this issue. That didn't quite work, so I changed it a bit to only look at the path when checking for a parent as described in comment 16.


webform submitted by the user the email that is sent is wrapped after around 75 characters I am using a Drupal 7 webform and when the webform is submitted by the user the email that is sent is wrapped after around 75 characters.  The confirmation page which is displayed and uses the same elements as the webform does not wrap after 75 but instead continue on the same line.
How can I get the webform email that is sent to not wrap after 75 characters.

DefaultMailSystem::format uses drupal_wrap_mail() to wrap the body text on sending. There is no option to send unwrapped text.


How to change Stars in Webform-star module? I have just implemented the Fivestar option in one of the evaluation form created by webform, I used the Fivestar module and Webform-fivestar module. But now I want to change the stars with different layout or design. In some of the article i read that we can change in manage display tab of the contentype but that option is not applicable for webform components. So that changing option is not available in the webform configurations. So please help me how to achieve this.

The webform-fivestar module currently doesn't have the option to select which star widget to use, however there is a patch you can apply at https://www.drupal.org/project/webform_fivestar/issues/2071161

There is information regarding how to apply patches at https://www.drupal.org/patch/apply

You can then select the widget per component, when editing the component, in the display settings (see screenshot).


How to remove search on Site and leave only search on Content? How to remove search on Site and leave only search on Content? When I use search on Site it says "Search is temporarily unavailable. If the problem persists, please contact the site administrator". When I search on Contents, it is OK.

So you are trying to make sure that the core Search only searches for content? if so you can tweak the core Search module at /admin/config/search/settings.


Hook for bulk node modifications I'm trying to unpublish nodes where a field = 'Closed'. This field can change so I need to run this bulk operation automatically. I've tried these hooks:

hook_update_N
hook_flush_caches
hook_cron

The only hook I've had success with is a view hook (hook_view_pre_render) and sure enough my bulk operation worked. Here's my code for the operation:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'custom_type')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_status', 'value', array( 'Closed' ), '=' );

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);

 foreach ($nids as $nid) {
    $node = node_load($nid, NULL, TRUE);
    // do something awesome
    $node->status = 0;
    node_save($node);
  }
}

Where you place the code depends on when you want it to run. Usually these things goes best in hook_cron(), but cron needs to be set up to run for that to work.

Instead of doing bulk update you might want to consider changing the published value in hook_node_presave() instead, i.e. when saving the node. Example (untested):

function mymodule_node_presave() {
  $w = entity_metadata_wrapper('node', $node->original);
  $var = $w->field_status->value();
  if ($var == 'Closed') {
    $w->status = 0;
    $w->save();
  }
}

Concerning your code otherwise it should work afaik, but it would be better to load all nodes at ones. Something like this:

$nodes = node_load_multiple(array_keys($result['node']));
foreach ($nodes as $node) {
  $w = entity_metadata_wrapper('node', $node);
  $w->status = 0;
  $w->save();
}

Cheers,


Article page url in chinese language Drupal 7 When i am visiting my site individual article page url in chinese language got below error, even this URL working fine in my localhost.

Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE7:titl...' for column 'location' at row 1' in /var/www/includes/database/database.inc:2204     cloud-server-01     /zh-hans/articles/%E5%9D%90%E6%8B%A5%E5%95%

This error might appear when the MySQL database is encoded as UTF8. In that case, Unicode characters represented with 4 bytes are not accepted. The accepted reply to the following StackOverflow question explains that the database needs to be encoded using the utf8mb4 encoding and the utf8mb4_unicode_ci collation:

https://stackoverflow.com/questions/10957238/incorrect-string-value-when-trying-to-insert-utf-8-into-mysql-via-jdbc

A more complete explanation about the utf8mb4 encoding on MySQL can be found here:

https://mathiasbynens.be/notes/mysql-utf8mb4

In case you need to re-encode your existing Drupal database, there is an experimental Drush command for it at UTF8MB4 Convert.


How do I use dpm() or kint() to debug a block plugin I created? I created a custom module which implements a block plugin. The code was generated with Drupal Console. When I try to debug the code within the build function, I get a function not found error.

Why doesn't my code print the value of $build?

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("test block"),
 * )
 */
class DefaultBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $build['default_block']['#markup'] = '1:Implement DefaultBlock.';
    dpm($build);
    //kint($build);
    return $build;
  }

}

dpm() definitely works within a custom block; I just tested. Since it calls a service, you may need to clear your cache before it shows up, for example with the command line with drupal cache:rebuild all or drush cr.

To test if the service is available, you could use this code.

dump( \Drupal::service('devel.dumper')); die();

Another thing to consider is that blocks are cached in Drupal 8 by default.  Make sure your build() is actually executing. You may want to turn off the rendering cache while developing, in settings.php or settings.local.php.

$settings['cache']['bins']['render'] = 'cache.backend.null';


Menu Block won't display when a page has a View Block on it I have Menu Block installed to provide some contextual menus for certain areas of a site. These generally work great. But I have a few pages where I'm adding a Views generated block to the bottom of the page, and on these pages the menu block seems to ignore the fact that these pages exist in the menu system and will not show anything.

If you have experienced this before and have a solution that's fantastic. Otherwise I'm hoping for some pointers as to where to look around for potential issues?

Update 1 - Seems to be related to the View block using the row style 'node', vs. using 'fields'. If I change it from node to fields, then menu_block works as expected, otherwise menu_block disappears.

Update 2 - Ended up just converting all offending Views elements to the field row style in order to continue on. So that worked around the problem, be curious if anyone else ever encounters the issue though.

Well, it's an old question but I'll post what worked for me in D7 (since my views were already 'fields' as the OPs, but that didn't solve my problem).

I used the menu position module, and set rules for the content types that were being displayed via Views, I set their parent menu item and that's it. This makes the menu block treat any page with views as a normal page, and the menu block finally appeared correctly configured.