How do you build a query to get a series of nodes and their field values filtered by field values? Hopefully someone with Drupal 7 experience can point me in the right direction.

I'm creating a custom module to query some nodes and group and sort them by their field values.

I tried to use Views but it seems that it's not possible to get the results in the format I need so I've decide to query the database directly and build my own output.

What's the easiest way to query nodes in Drupal 7 as I notice there is a table for every field now which would seem to make any query that I have to write extremely complex?

Are there any methods to query node data and filter/group the results or can it only be done using raw SQL.

If the latter can you show me an example query that includes Drupal 7 Field values?

I second Jeremy's suggestion of trying harder with views. However, if you absolutely must write your query directly in code, you'll want to use EntityFieldQuery.

For example, to get a count of all nodes with a text field value of 'foo':

// Get field information
$field = field_info_field('field_name');
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'NODE TYPE')
  ->fieldCondition($field, 'value', 'foo')
  ->count();

$count = $query->execute();

If you don't want a count, but results instead, you would leave off the count part, and fetch results:

foreach ($query->execute() as $entity_type => $entities) {
  foreach ($entities as $entity_id => $entity) {
  ...
  }
}

The Commerce Guys also have a good blog post detailing a simple use case.


How can I track how embedded media is used across my site? My site uses the core Media module, Entity Embed, and LinkIt to reference media and other entities in various ways.

I want to keep track of which media is embedded on which nodes.

I tried adding an entity reference field to media on my content types, but this means that I have to add the media twice: to the field where I actually embed the media and to the entity reference field to track it.

Is there a better way?

First, there is a core issue to eventually get this into core.

Now, the best way is to use the Entity Usage module, which can handle tracking of media and many other cases.

Hats off to the module maintainers-- this is all I needed to do to implement my use case:

Download the module with composer.
Enable the module.
Go to /admin/config/entity-usage/settings and check Media under Enabled local tasks.


How can I make URL Alias required when creating new content When a user creates a new article they often forget to put in the URL path alias for the article. How can I make that field required before they can save the content?

The easiest solution is to use the pathauto module. If the user does not touch the URL path alias field, pathauto will automatically generate a URL for the node based on the node title.  Other configuration options are available.  The user may still uncheck the pathauto checkbox and type in a specific URL for their new node.

Update:

If the URL format is built from fields or metadata in the node that is created, pathauto can do that for you automatically through its pattern configuration page. For example, I have one content type with a pattern [node:field-gender:name]/[node:field-era:name]/[node:field-genre:name]/[node:field-item-type:name]/[node:title] to create four levels of nesting in the URL based on field values entered. If the user does not have the permission to create and edit url aliases, they will be stuck with the pattern pathauto provides.

If you want to allow users to also edit the URL, you could validate the field from hook_node_validate. I don't know if there is a way to do node validation with rules.

Update 2:

If you have a field called "tag" that is a taxonomy term, then [node:tag] will return all of the terms in this field, concatenated together, and [node:tag:1] will return just the first taxonomy term.  In both cases, spaces are converted to dashes.


Override default page.tpl.php I'm trying to override the default page template for a specific page I created. I created a new page and then created a new template file called page--node--1.tpl.php and added the following code:

<?php
echo 'test?';
exit;
?>

I'm using 'garland' as a theme and it's still showing garland's template.

Adding a template file to an enabled theme is like adding a hook to an enabled module: In both the cases, Drupal will not notice there is a new template file, or a new hook, as Drupal keeps that information cached.
After you add a new template file, you need to clear the Drupal cache, or disable the theme for then re-enable it. In the latter case, you forces Drupal to clear the relevant caches.

As side note, exit should be never used in a template file, not even for debugging. Doing so, you would interrupt Drupal when it calls theme_render_template(), with the effect that the template file would not be rendered.

function theme_render_template($template_file, $variables) {
  extract($variables, EXTR_SKIP); // Extract the variables to a local namespace
  ob_start(); // Start output buffering
  include DRUPAL_ROOT . '/' . $template_file; // Include the template file
  // The code after this comment is never executed, if the template file executes exit().
  return ob_get_clean(); // End buffering and return its contents
}

For debugging purposes, it's enough to print a specific string that allows you to know if the template file is loaded.


How do I per-variation add to cart button In Views with no selection? I have a table that displays rows of products with there attributes, the last item on each row has the variation add to cart form.
The view's self sorts on the product id to display all the variations for the product.

The issue is it can't select the variation for each row automatically, it always expects the user to choose the right variation from a dropdown.

Any changes that do not have the drop-down displayed defaults to only the first product item in the table.
I have tried the relationship to the product and product id and variation cart form modules but these also failed to deliver.

I there a way in views to add a per-variation add to cart button with no selection in views table?

I finally found the answer from help on this post. here  Although, I still had a few issues and mine ended up being slightly different, so I will lay out what I did to achieve this.

I am using a view table but really any sort of display using fields with grids should work the same.

Install the module Add to cart link
Create a new display on your product variation called what you like I am using 'view' with only the add to cart link field.
In your view add the display type you require.
Add Relationship: variations (Relate each Product with a variations set to the product variation.)
Add Relationship: Product
Add contextual filter: Product: ID - Provide default value Product ID from URL
Add Field Rendered entity - Product variation
Select your display from the view mode.
Save, add your view and output your view to your product page.

Now you will see all the Add to cart buttons displayed for each variation on the product with the right token add to cart link for each.


How do I make the nodes referenced by organic group content also be OG content? I have an organic group called 'newsletter'.
I have two content types - 'issue' and 'article' - in 'issue' (which is set to be a group content type), there is a node reference field to articles, and many articles in a single issue, using an inline entity reference form.

I want to put an issue inside an organic group, for access control. I also want the articles that the issue references inherit that group content relationship without having to explicitly set the group for every single piece of content.

The group is public, but the content is private. I don't want anyone to access group content until they go though a process and purchase access via the commerce_licence_og module.

The article (content referenced in entity reference field) isn't added to the group content, though the issue itself is. I felt that a group reference for every article is redundant, and I would rather the article inherit the issue's access and status as group content rather than have a bunch of redundant fields and is automatic, not requiring additional admin steps.

Is there an easy way to do this?
Do I HAVE TO make the articles group content in the UI?

Here is the solution I've come up with.

It works, but might not be the most elegant solution. I didn't think that this would matter too much, since it's only being called on node save, but I'm open for comments and suggestions.

/**
 * Ensure that referenced nodes belong to the same organic group
 *
 */
function MODULE_node_presave($node) {

  if ($node->type == NODE_TYPE) {

    $og = og_get_entity_groups('node', $node);
    $nids = get_referenced_nodes($node);

    foreach($nids as $nid){

      $child_node = node_load($nid);

      //Set the values
      $values = array(
        'entity_type' => 'node',
        'entity' => $child_node,
        'state' => OG_STATE_ACTIVE,
      );

      //Add this node to the group
      $gid = array_values($og['node']);
      $result = og_group('node', $gid[0], $values);

    }
  }
}

/**
 * Helper function - get all node reference fields of a node
 * @param $master_nid - the node id of the referencing node
 */
function get_referenced_nodes($master_node) {

  $fields = field_info_instances('node', $master_node->type);

  $items = array();

  foreach($fields as $field){

    if($field['widget']['module'] == 'inline_entity_form'){
      // Get the node reference items for this field
      $items[] = field_get_items('node', $master_node, $field['field_name']);

    }

  }

  // Loop through and grab the nids
  foreach ($items as $field) {
    foreach($field as $target){
      $nids[] = $target['target_id'];
    }
  }

  return $nids;

}


delete a specific element within field collection programmatically This is driving me crazy it just sounds simple, but I cannot find the answer.

I have a field collection in a content type called field_collection_mine how you now while creating the node you can add elements to the field collection.

I have tried this:

$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->field_collection_mine = array();
entity_save('field_collection_item',$wrapper);

The code above delete all the elements within the field collection, but that is now what I want!! I just want to delete for example the last element. E.g:

Field Collection mine
Element1
Element2
Element3

How can I for example delete just the element 3? The above code deletes all the elements, so field_collection_mine is left empty.

You need to grab the id of the field collection and wrap itself in an entity wrapper. Use the save method in the wrapper to do this instead of the entity_save function. E.g.

 $wrapper = entity_metadata_wrapper('field_collection_item', $entity);
 $wrapper->field_specific_field_collection_item->set("");

or:

$wrapper->field_specific_field_collection_item = array();
$wrapper->save();


How to increase the maximum upload size? I'd like to increase the maximum upload size from 2MB to 5MB on my website (I'm using WAMP). My first attempt to do this was to set Content types > MY CONTENT TYPE > Manage fields > MY IMAGE FIELD > Maximum upload size to 5 MB, but that didn't work. Next, (after reading this question and this article) I added

ini_set('post_max_size', '5M');
ini_set('upload_max_filesize', '5M');

to my sites/default/settings.php file, but that didn't solve the problem either.

What am I doing wrong? Why didn't my first approach work?

You need to make some changes in your php.ini file for Post max size and upload max size

Just follow this link for reference , Click here


How to setup a Drush Alias? I want to setup Drush aliases for a Drupal site on WAMP. I tried, however I had no luck.

All my installations for Drupal sites are located in c:\wamp\www

Drush is located in c:\drush

I would not say I have multi site up!!

The URL I use in the browser is caribbean.localhost

I'm really not sure, or I have trouble setting up my Drush alias. So I wonder if anyone can advise me or offer direction help to me!

It's difficult to answer your question without some concrete specifics. But i went ahead and provided you some common troubleshooting tips when i was in your shoes a moons ago:

Visit the latest readme.txt: It's named that for a reason. I've never read a more helpful readme.txt in terms of contributed modules. Of the best. There's a section relating to site aliases as well. What you have to do for it to work etc.
Review Documentation: First off, please review the Drush documentation which provides great examples of how to create a site aliases.
Copy an example: Also, the maintainers created some awesome examples for a example.aliases.drushrc.php file. In fact, theres a whole folder regarding this that you can copy and paste examples.

Debugging Drush

Additionally, here are some cheap tests to confirm that your site alias is working:

Try running drush status a drush status will show which you which alias file is being read in.
If that's not enough review the drushrc.php file. I would turn on verbose output to figure out how drush is failing.


How To add user name and profile picture to Superfish menu I am using Superfish module to obtain drop down menus. I would like to have one parent menu link as a username and user image, then child menu links will be under it when hovered over.

Example of this is airbnb.com when logged in.

I do not know much PHP and do most of my work with CSS and already created modules.

I found a somewhat unnecessarily complex, but working, answer.

Install Menu Views module.
Create a View User List Block and add a relationship User:Profile.
Add a contextual filter user:uid and set Provide default value as User ID from logged in user.
Add 2 fields, User: Picture and User: Name
Change Access to Role and choose all roles that should see this View.
Add CSS classes and style

Note: At this time a issue exists with Menu Views and requires a fix found here.


How to use cck time field in rules? I'm using a cck_time field (field_check_in) in my content type.
I want create a notify when this field is changed but when I try to set Data comparition in Rules Conditions I not find the entity of the field ([node:field-check-in]).
How I can do it?

Below is a sample of a rule (in Rules export format) that will send an eMail similar to what is asked in the question:

{ "rules_notify_author_of_selected_field_updates" : {
    "LABEL" : "Notify author of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_check_in" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-check-in" ],
          "value" : [ "node:field-check-in" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:current-user:mail]",
          "subject" : "Notification about a node with an update field_check_in value",
          "message" : "Go checkout the node with nid [node:nid] and title [node:title]: it has a field with an updated value (which is [node:field-check-in]) you wanted to be informed about ..."
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event I'm using is "After updating existing content".
It's about updates to the field field_check_in.
The Rules Condition checks if the "The value changed".
If the Rules Condition is true, then (as Rules Action), an eMail will be triggered to the editing user.

Adapt the actual eMail details (subject, etc) to fit your needs. Then import it in your own site (using the Rules UI). That's it.

Note: I'm assuming this is about D7.


How do I add custom theme settings? In my theme I have link to social network. So, I would like to have field in theme settings where administrator can put link what would be use in all place where is {{link-social-network}}.

I also read that theme settings default values can not be set in a theme's info.yml files.

The theme's config/install/THEME.settings.yml file should have that information.

You can create new file and call it as theme-settings.php and add the following to it or even add this to THEME_NAME.theme file.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Theme\ThemeSettings;
use Drupal\system\Form\ThemeSettingsForm;
use Drupal\Core\Form;

function THEME_NAME_form_system_theme_settings_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  $form['THEME_NAME_settings']['social_icon']['social_url'] = array(
    '#type' => 'textfield',
    '#title' => t('Social Link'),
    '#default_value' => theme_get_setting('social_url', 'THEME_NAME'),
  );
}

Then you need to add the following to THEME_NAME.theme file.

function THEME_NAME_preprocess_page(&$variables) {
  $variables['social_url'] = theme_get_setting('social_url','THEME_NAME');
}

Then you can use it in the twig file.

To have a default value for the social url, you can include it in your  config/install/THEME.settings.yml

Hope it helps!


Underscore is added to links in view I'm writing a workaround to fix the breaking changes introduced to our XML feed when we updated from Drupal 8.4 to 8.5. Since PATH is no longer available but has been replaced with LINK, I've had to craft the Rewrite Results to be /news/{{ view_node }}, which displays a properly formatted URL in the preview:

<link>http://sitename.com/news/article-title</link>

However, in the actual XML feed, it comes out like this:

<link>http://sitename.com/news/article-title_</link>

arbitrarily adding an underscore and breaking the URL. Is there a way to make this not happen?

After much work I came up with a workaround. My first thought was to add a Twig filter to views-view-row-rss.html.twig like so <link>{{ link | replace('_', '') }}</link> but the underscore was still being displayed, which told me that either 1. the Twig filter wasn't working or 2. the underscore was being applied later in the render process.

The Twig template's documenation made reference to a template_preprocess_views_view_row_rss() hook I found implemented in /core/modules/views/views.theme.inc so I added the following hook to my custom.theme PHP file:

function ncei_preprocess_views_view_row_rss(&$variables) {
  $item = $variables['row'];
   $variables['title'] = $item->title;

   //$variables['link'] = $item->link;
   $variables['link'] = str_replace("_", "", $item->link);

   if (isset($item->description) && is_array($item->description)) {
     $variables['description'] = (string) \Drupal::service('renderer')-
       >render($item->description);
   }

 $variables['item_elements'] = [];
 foreach ($item->elements as $element) {
   if (isset($element['attributes']) && is_array($element['attributes'])) {
     $element['attributes'] = new Attribute($element['attributes']);
   }
   $variables['item_elements'][] = $element;
 }
}

I commented out the original line above for reference, but I'm setting the link variable to the item's link, stripped of all undertscores. This isn't the best solution, and will break if the link actually contains underscores, but it worked as a temporary workaround in the meantime.


How can I make teasers refresh when they are flagged? I have several flags like "Sold" "Withdraw" etc which appear in Contextual links.  Flagged nodes are checked through node--type.tpl.php and this allows me to add text strings like "Sold" or "Withdrawn", which I theme with CSS to show as large labels.

The problem is that when the end-user flags an item with a Flag toggle, it's not very clear what this flag does. I need that teaser to auto-refresh, so that my labels ("Sold" or "Withdrawn") become visible immediately without the end-user having to reload that page.

I have found this js code , but what it does is slide the node teaser up, which is okey for the "Withdrawn" flag in some views), but is not the correct behaviour for the "Sold" flag.  For the "Sold" I need that teaser to refresh itself.

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
      $('#'+data.contentId).hide('');
       // $.growl('Flag', 'The article '+data.contentId + ' has been flagged and hidden.');
    });

Drupal.behaviors.moduleName = function()
{
  $(".flag-action").each(function()
  {
    $(this).click(function()
    {
      $(this).parents(".node").slideUp();
    });
  });
};

Step 1 (PHP part):

You need to implement, hook_flag_javascript_info_alter() function, and pass in the refreshed teaset html, so that you can use this in js file.

function yourmodulename_flag_javascript_info_alter(&$info) {
  $content_id = $info['contentId'];
  $node = node_load($content_id);
  $view = node_view($node, 'teaser');
  $rendered = drupal_render($view);
  $info['rendered_node'] = $rendered;
}

Step 2 (JS) Part:

Now upon flagging, you will have the refreshed node html as data.rendered_node. So employing your js code you wrote above:

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  var node_id = data.contentId;
  var rendered_teaser = data.rendered_node;
  //here you have to check the logic, find the selector that is to be
  //replaced, and then replace that with the 'rendered_node' variable we declared above.

});

Please note that my intention here was to give you a direction and the general logic and not the exact code, so most probably you have to modify the above code to make it work.

UPDATE:

In the step 2 code, you see I got a variable node_id. That is the nid of the content that was flagged. In the html,  you must be having some class using that nid, may be "node-765"..where this 765 is the id. look for such a class. Once you have the class name, and say that class is of the form "node-nid-765". So we will check for that like this:

$('node-nid'+node_id).replace(rendered_teaser);

Again please note the class names are not exact and have been provided to give you an example.


How can I get row field in hook_preprocess_views_view_unformatted(&$variables)? Is there a way to get a field from the view in the hook_preprocess_views_view_unformatted(&$variables)?

$rows = $variables['rows'];
foreach ($rows as $id => $row) {
   // $row['field_name'] or something?
}

You find the field handlers you have configured in the Fields list in $view->field. A field handler has methods like getValue(), render() and advancedRender(), which accept as argument the row variable:

Example:

$view = $variables['view'];
$rows = $variables['rows'];
foreach ($rows as $id => $row) {
  $field_value = $view->field['field_name']->getValue($row);
}

See also Get result view with formatter programmattically


Two different versions of the same base theme in the same site I'm wondering if it's possible to get two different branches of the same theme into the same site, both to be used as base themes.

Specifically I'm talking about Omega 7.x-3 and Omega 7.x-4 in the same site, but I guess the question applies to any theme.

Rationale: We're using Omega 4.x for the main theme (because of the nice front end stack), but for commerce sites (which this is), we also like to include Omega Kickstart as the admin theme. It's an improvement over Seven for very little work and clients seem to like it.

However, Omega Kickstart uses Omega 3.x as its base theme, and so conflicts with the newer version that's installed.

Short of taking a copy of one of the Omega versions, renaming it and all its internal functions, and then building a sub-theme from that, is there any way to get this sort of workflow?

UPDATE

Ok, er, so I made a bit of a mistake. I actually want to use the Shiny theme, not Omega Kickstart. Whoops.

But let's say I didn't, and definitely wanted to use Omega 3.x and 4.x in the same site...how might that go?

Themes, like modules, are identified by their names. The version number is never really used (except for updates obviously).

Anyway, i found myself facing a similar problem sometimes, and running a find&replace on the theme directory to change every occurrence of the name with another inside the files never lead to unexpected behaviors.

well, i also had to manually rename the .info file, so it's not a completely automatic procedure, but still nothing that caused problems of any sort.


How do I use field_view_field inside a custom views .tpl? I have a view set up that uses an image from a node, I have customized the views-view-field.tpl to change the url the image links to dependent on the content type. I am trying to print out the picture using field_view_field in the .tpl, but its just printing out "array". Here is what I'm working with.

<?php if ($row->node_type =='article'): ?>
<?php print field_view_field('node', $row, 'field_field_image');?>

What am I doing wrong?
Thanks.

Ok, so I figured it out. First I did a node load:

<?php $node = node_load($row->nid);?>

Then I had to wrap my field_view_field in a drupal_render, finally I added my image style name in the display parameter, like this:

<?php print drupal_render(field_view_field('node', $node, 'field_image', 'image_style'));?>


#block-system-main with no content interrupting my layout I have a drupal page with three blocks beeing rendered and floated besides each other in a content area. In the middle of these, Drupal renders out a block called #block-system-main with an empty content div. It breaks my floats, and I have no idea where this div is coming from or how to remove it.

Any ideas as to what could cause this and how I can remove it?

I dont know where it comes from. Probably best would be if you can find that. But if you want to quick fix it. You could unset it in page preprocess

function YOURTHEME_preprocess_page (&$variables, $hook) {
  unset($variables['page']['some_region']['block_id']);


How to give to the creator of a node the option to hide the name of the author? I need to provide a way for hiding the name of the user who created a node, if the creator of a node wants to do so. In such cases, it should show Anonymous as the author of the node.

Any suggestions about how to implement this?

There are a few things in the original version of this question that really need review ...

  Content may add only authorized users on my site.

In Drupal you cannot have content that adds users, so I'm going to assume it's rather the opposite you're looking for, ie: "Content may only be added by authorized users on my site".

  I need to implement the functionality (option) of hiding a user name (author of сontent) if user wishes it.

Unless you have special customizations in place in your site, Drupal allows for multiple (authorized) users to author (change) content. So your "if user wish it" is a not clear enough: maybe you mean "the original author" (who first created the node), or maybe you mean "the user who last edited (changed) the content". For the sake of simplicity, I'm going to assume "the original author".

  That is, to make him/her "the anonymous author of" сontent.

If you agree with my above assumptions, here is a blueprint of how you could implement this:

Add a custom field to your content type, which is a boolean (true/false, yes/no, 0/1, whatever fits) that can be used when creating a node to have the original node author indicate if author should be shown (yes) or marked as "anonymous" (no).
Use the Rules module to ensure that the "Authored by" value always remains the "original node author" (who created the node). This basically ensures that attempts to change the node author (similar to what is suggested in codenext's answer) will be rejected. Only using Rules should be sufficient to implement this (rather basic) validation. But if needed (to further enhance these validations), add the Rules Forms Support module.
Use a preprocess function in your theme (similar to what is suggested in Zuzuesque's answer) to actually display the node author as requested by ... the original node author.

Note that if the original node author ever want to change his/her mind, that's still possible with this approach: just change the value of the custom field value as desired (after doing so, the logic in step 3. will ensure it's processed accordingly).


What hook for triggering an action after saving a new node? I'm running Drupal 7 and I want to re-save the user account of the node author after deleting a node of content type picture. I want to do this because I have some code called in hook_user_presave() that counts the number of pictures a user has added and saves it in an integer field in the user.

I looked at hook_node_submit() and hook_node_update(), but when then are invoked, the node is not yet saved, so if I save the user at that point, the int value is one less than it should be (because the added node has not actually been saved yet).

Is there a hook for reacting after a node has been added?

Related question: Hook for reacting after deleting node

You can use Hook Post Action module which will provide you hooks like:

hook_entity_postsave

hook_entity_postinsert

hook_entity_postupdate

hook_entity_postdelete

hook_node_postsave

hook_node_postinsert

hook_node_postupdate

hook_node_postdelete
These hooks are fired after node is saved to the database. So the process you want to do after node save can be done using these hooks which comes with Hook Post action module.


How do I get the content type of a node entity from the $entity object? I'm using hook_ENTITY_TYPE_presave() to alter the values of nodes upon saving, but I only want to do this for a specific content type.

How do I check the content type of the $entity object?  I looked at the documentation for class node and working with Entity API, but all I found was how to get the entity type, not the content type.

Given a node $entity object, how can I check the content type?

If you know that you have a node, then you can use getType(). If you don't know that, you can use he generic method ->bundle(). Note that the second will return the entity type in case of an entity type that doesn't have bundles, like users.

Again, my standard reference to http://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf, it contains both methods.


Jump to navigation link I would like to add a "Jump to navigation link" to the Utility menu at the top.

Setting the path to "#main-content" doesn't seem to work.

The path '' is either invalid or you do not have access to it.

If I view the source of my page the anchor is there:

Jump to navigation

Why can't I link to #main-content?

You would need to use the Menu token module in order to get the path to the current page as you first need a valid path, and then add your anchor to the path.

The tokenized path for the menu item should be something like:

[current-page:url:path]#footer


How to remove link of username in comment submission form How can I remove the username link which is displayed in the comment submission form?

Simple solution is to use CSS. Just add a css rule to your theme's stylesheet.

#some .rule {display: none;}

Alternatively you can use hook_form_alter to modify the form and remove the link or change it to something else.

How to do it depends on your Drupal verion, see the API docs for reference or see altering form with hook_form_FORM_ID_Alter for usage on hook_form_FORM_ID_alter which is a specialized version of hook_form_alter.


Contest with unique vote My users can submit Recipes (a custom content type). I want to create a contest to let my users vote for their unique favorite recipe.

To vote, users (anonymous users) have to go to the page of the recipe they want to vote for and clic on "I vote for this one" to vote for it. If they go to another recipe page, they won't be able to vote for it because they would have already voted for another recipe.

Do you have any idea about how to do it ?

I know how to do it with a poll inside a block but I want to have a vote button inside each recipe page.

I didn't find a way to do it with Rate or Five Stars.

My solution is pretty simple : webforms. You can allow only one "vote" per ip with this module and you can create a view / block to display it on each node.

It does everything I needed !


It says "No Solr instance available when trying to clear the cache", should I reinstall that module? In admin/reports/apachesolr/solr  "No Solr instance available when trying to clear the cache", should I reinstall that module? I can`t cope with setting up the search block to return the search result.

First check whether your solr instance working properly or not. Goto http://localhost:8080(your port)/solr/admin/.
And in your site goto admin/config/search/apachesolr/settings/solr/edit page and enter SOLR SERVER URL and click on test connection whether your solr instance working or not. If not try to re-install solr if there is not indexing.


Is there a suggested approach to altering the field schema for already populated fields? I specifically wish to solve this problem http://drupal.org/node/1514826#comment-5866494.

Currently the fivestar module's field schema looks like this:

<?php
 function fivestar_field_schema() {
  return array(
    'columns' => array(
      'rating' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
        'sortable' => TRUE,
      ),
      'target' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
      ),
    ),
  );
}
?>

I would like to change it to:

<?php
 function fivestar_field_schema() {
  return array(
    'columns' => array(
      'rating' => array(
        'type' => 'float', // Change to float from int
        'unsigned' => TRUE,
        'not null' => FALSE,
        'sortable' => TRUE,
      ),
      'target' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
      ),
    ),
  );
}
?>

This would work for new Fivestar fields. However, those that contain data cannot be updated. Since the field storage can be in SQL or Mongo or Solr, I would like to create a generic update to this. However, the most commonly used sql storage does not allow column changes if it has data (see field_sql_storage_field_storage_update_field()).

Is there a suggested way out? Thanks.

I have no idea if this is a "suggested way out," I'm tending to think not, but, with your site offline, you should be able to use phpmyadmin and:

Add a field to the database table (your float field),
copy all of the data from the original column/field to this new one (something as simple as UPDATE "tablename" SET "newfield" = "oldfield" would probably do it),
drop the original integer field from the table,
rename the new field with the old field's name, and

then take drupal online with the new schema and code that is expecting a float in there instead of an integer.

You could also just rename instead of dropping the original field so you could quickly go back if this screwed up, but I would definitely back things up before trying this in any case :)


Action attribute in forms is not a url. Why? When I check the action attribute of a drupal form, I never see a valid URL. What I see in the html code is a simple string, which usually matches the node title of the form. Given that the action attribute should contain a valid URL pointing to a server-side script, I am really confused! What are the mechanics behind the form's submission? Thanks in advance for your answers!

If you look again, I would hazard a guess that you are using pathauto, and that the default pattern for Webform paths is [node:title]. If you set it to form/[node:title] then the action attribute would look more like a path. eg. My Form would have an action attribute of action="/form/my-form".

In Drupal everything goes through the Drupal bootstrap. There are no calls to cgi-bin or the equivalent. Rendering a form or processing a form are done by calling the same url, which tells Drupal where to look for the form. What Drupal does depends upon the op associated with the call, and the rendering, validation, processing and storage are all defined by the modules underlying the form.


How do I break my query result into smaller chunks Background

I have a query that returns 140000+ results and I need to perform more calculations on the result before displaying them to the user. This has caused a huge wait time (left it to run for 1hr and 30 mins and it still wasn't finished).

Problem

The wait time is huge and needs to be reduced. I can happily load all the data (140000+ results) and run a lesser calculation. This is no use if I can't run the full calculation.

Possible Solution

I've thought about this and I think if I was able to limit the results returned (say 1000 results) I would be able to run the full calculation with no problems.

Question

Can I limit the amount of results back (say results 0-999) run my calculation on them and then load the next bit (results 1000-1999) and run the calc again?

According to https://www.drupal.org/node/1848368

  Queries may also be restricted to a certain subset of the records
  found. In general this is known as a "range query". In MySQL, this is
  implemented using the LIMIT clause. To limit the range of a query, use
  the range() method, which takes two arguments: the first specifies
  offset and the second specifies limit

  In most cases we want "the first n records". To do that, pass 0 as the
  first argument and n as the second.

<?php
// Limit the result to 10 records
// where 0 is offset and 10 is limit
$query->range(0, 10);
?>

  The following example will instruct the result set to start at the 6th
  record found (the count starts at 0) rather than the first, and to
  return only 10 records.

<?php
$query->range(5, 10);
?>

  Calling the range() method a second time will overwrite previous
  values. Calling it with no parameters will remove all range
  restrictions on the query.


How to do multiple conditions for db_update by using OR condition? I would like to convert the following UpdateQuery statement to work with multiple conditions by using OR instead of the default AND condition.
db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition('name', 'seven') // OR
  ->condition('name', 'rubik')
  ->execute();

Is it possible?

Drupal 7
Yes, it is possible by using db_or() as in the following example.
db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition(db_or()
    ->condition('name', 'seven')
    ->condition('name', 'rubik')
  )
  ->execute();

For db_select(), see the answers given in  "OR" condition in db_select() and Nested OR and AND condition with db_select.
Drupal 8
You can still use db_or() as in Drupal 7, but it's deprecated in Drupal 8.0.x and removed in Drupal 9.0.0. Instead, a \Drupal\Core\Database\Query\Condition object should be created as in the following code, taken from BooleanOperator::queryOpBoolean().
if ($this->accept_null) {
  if ($query_operator === self::EQUAL) {
    $condition = (new Condition('OR'))
      ->condition($field, 0, $query_operator)
      ->isNull($field);
  }
  else {
    $condition = (new Condition('AND'))
      ->condition($field, 0, $query_operator)
      ->isNotNull($field);
  }
  $this->query->addWhere($this->options['group'], $condition);
}


How to modify the link titles shown in /node/add page? I can modify the menu item title implementing the hook_menu_links_discovered_alter() hook, as illustrated in this screenprint:

I changed the menu item title to "Article (Only One Article can be created and edited)".

But the problem is that the same item is shown also in the /node/add page but the title of that link is not changed because it is shown by a controller. As illustrated in the above image also, the menu links are changed but the link in the /node/add page remains without changes, which is still just "Article".

How I can change that value also, i.e from "Article" to "Article (Only One Article can be created and edited)", so that it matches with the menu item title?

You should copy template_preprocess_node_add_list() into your module or theme and customize.  I would advise against trying to change the value in the node type because it's the name of the bundle type across the site.  It will show many places you don't want to update.

For example, to update the article link:

function mytheme_preprocess_node_add_list(&$variables) {
  foreach ($variables['content'] as $type) {
    if ($type->id() == 'article') {
      $variables['types'][$type->id()] = array(
        'label' => $type->label() . ' (Only one article can be created and edited)',
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label() . ' (Only one article can be created and edited)', new Url('node.add', array('node_type' => $type->id()))),
        'description' => array(
          '#markup' => $type->getDescription(),
        ),
      );
    }
  }
}

Another alternative to the preprocess function is just to copy /core/modules/node/templates/node-add-list.html.twig into your theme and add your custom rules there.

UPDATE:

Due to the question's particular requirements, I'm adding another solution that works without altering the seven theme (that conflicts with my solution above).  In the solution below, we alter the output of $node_type->label() conditionally:

function mymodule_entity_type_alter(array &$entity_types) {
  $entity_types['node_type']->set('label_callback', 'mymodule_node_type_label');
}

function mymodule_node_type_label(NodeType $type) {

  if (\Drupal::routeMatch()->getRouteName() == 'node.add_page' && $type->id() == 'article') {
    return $type->get("name") . ' (You can only add one of these)';
  }
  return $type->get("name");
}

UPDATE:

Here's another solution that works with the seven theme.  You can alter the particular node types you like in the preprocess function in your custom module.  This will only alter their labels within this context.

function mymodule_preprocess_node_add_list(&$variables) {
  $article_type = $variables['content']['article'];
  $variables['content']['article']->set('name', $article_type->get('name') . ' (Only one article can be created and edited)');
}


Views throw an Ajax error in the admin page When I go to a View edit page in the admin of Drupal 7, two of them (one that's called front page and was already there, and one that's a jcarousel) throw an error:

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /admin/structure/views/view/frontpagecarousel/preview/page/ajax
StatusText: error
ResponseText:

"ResponseText" is followed by a huge load of unformatted text (not even a newline character). But I believe that it must have something to do with the "Path", which I don't believe exists. I'm not certain, but I think this is interfering with jCarousel's options, as it expects something to appear in the Fields section, but the Fields section says "The selected style or row format does not utilize fields."

So, what's going wrong, and how can I fix it?

I've had this problem many times before. For me, it was because I had the theme developer module enabled. I think the firebug module has the same effect. Basically, they are both adding extra markup to the response text and it isn't able to parse it then.


Redirect users function of role I need to redirect users function of his role using external authenticate.

In my form_alter() I have:

$form['#validate'] = array(
  'user_login_name_validate',
  'beneficiaire_authenticate',
  'user_login_final_validate'
);
$form['#submit'][] = 'beneficiaire_user_login_dispatch';

My function to authenticate:

function beneficiaire_authenticate($form, &$form_state){
  module_load_include('inc', 'beneficiaire', 'ws');

    if('admin' == $form_state['values']['name']){
        user_login_authenticate_validate($form, $form_state);
    }else{
    $authResponse = beneficiaire_ws_authenticate($form_state['values']['name'], $form_state['values']['pass']);
        if($authResponse)   {
            user_external_login_register($form_state['values']['name'], 'beneficiaire');
            $account = user_external_load($form_state['values']['name']);
            //var_dump($account);exit();
            $form_state['uid'] = $account->uid;
            $account->roles[4]= 'beneficiaire';
            user_save($account);
      $_SESSION['account'] = $authResponse;
        }
    }
}

And finally my dispatch function where the aim is to redirect users function of their account status / type:

function beneficiaire_user_login_dispatch($form, &$form_state){
  if($_SESSION['account']->temporaire){
    drupal_goto('update-password');
  }else{
    drupal_goto('order');
  }
}

My point is, each user is always redirected to /node. How can I redirect them function of account status ?

Thanks

I've found a solution:

function beneficiaire_user_login($form, &$form_state){
  if($_SESSION['account']->temporaire){
    $_GET['destination'] = 'update-password';
  }else{
    $_GET['destination'] = 'order';
  }
}


Open a view getting nid from previous view I have two view. One is a Gallery view and the other is a
view with exposed filter with which i choose field_gallery[nid] to make operations into some editable fields.What i wish to Know  is if i can add a link in the first view with which open second view calling the [nid] of the first.
Do you think is possible?

Yes it is possible.

You can do the following

In the first view add nid field
In the field settings go to rewrite result
In rewrite result give something like Link Text

[nid] will work as a place holder for the current content nid. You can see all the replacement patterns with in the view itself.


How to handle cache metadata in a cacheable response? I have a custom controller action that returns the HTML for a search result. The action is invoked via AJAX on the search page and the results are inserted into the page body.

The problem is that a dynamic page cache entry is created for this controller action and it's not "busted" when the query string changes, so old results are always returned:

  public function basicPeopleSearch(Request $request) {
    $search = $request->query->get('search');
    $build = [];
    if (!empty($search)) {
      // Get search results and add them to the render array.
      $results = \Drupal::getContainer()->get('pu_search.people_search')->basicSearch($search);

      foreach ($results as $result) {
        $build[] = [
          '#theme' => 'pu_search_person',
          '#person' => $result,
        ];
      }
    }

    // The results will differ based on the "search" query string parameter.
    $build['#cache'] = [
      'contexts' => [
        'url.query_args:search',
      ],
    ];

    $rendered = \Drupal::service('renderer')->renderRoot($build);
    return new CacheableResponse($rendered);
  }

I suspect this has something to do with how I'm actually returning the response or rendering the output?

You have to add the cacheable metadata from the render array to the response:

use Drupal\Core\Cache\CacheableMetadata;

  $rendered = \Drupal::service('renderer')->renderRoot($build);
  $response = new CacheableResponse($rendered);
  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
  return $response;


Set trim_length of field through UI for blog entries I am using the Blog module, but don't like the 600 character trim length.  I want 2000 char.

But, I can't find out where to change this in the admin console.

I was able to update the trim length through the mysql console, but this seems less than ideal.

The code below was how I was able to complete the config change.  How can i do this without a SQL update?

mysql> select * from field_config_instance where id=9\G
*************************** 1. row ***************************
         id: 9
   field_id: 2
 field_name: body
entity_type: node
     bundle: blog
       data: a:6:{s:5:"label";s:4:"Body";s:6:"widget";a:4:{s:4:"type";s:26:"text_textarea_with_summary";s:8:"settings";a:2:{s:4:"rows";i:20;s:12:"summary_rows";i:5;}s:6:"weight";i:31;s:6:"module";s:4:"text";}s:8:"settings";a:3:{s:15:"display_summary";b:1;s:15:"text_processing";i:1;s:18:"user_register_form";b:0;}s:7:"display";a:2:{s:7:"default";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:12:"text_default";s:8:"settings";a:0:{}s:6:"module";s:4:"text";s:6:"weight";i:0;}s:6:"teaser";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:23:"text_summary_or_trimmed";s:8:"settings";a:1:{s:11:"trim_length";i:600;}s:6:"module";s:4:"text";s:6:"weight";i:0;}}s:8:"required";b:0;s:11:"description";s:0:"";}
    deleted: 0
1 row in set (0.00 sec)

mysql> update field_config_instance set data='a:6:{s:5:"label";s:4:"Body";s:6:"widget";a:4:{s:4:"type";s:26:"text_textarea_with_summary";s:8:"settings";a:2:{s:4:"rows";i:20;s:12:"summary_rows";i:5;}s:6:"weight";i:31;s:6:"module";s:4:"text";}s:8:"settings";a:3:{s:15:"display_summary";b:1;s:15:"text_processing";i:1;s:18:"user_register_form";b:0;}s:7:"display";a:2:{s:7:"default";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:12:"text_default";s:8:"settings";a:0:{}s:6:"module";s:4:"text";s:6:"weight";i:0;}s:6:"teaser";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:23:"text_summary_or_trimmed";s:8:"settings";a:1:{s:11:"trim_length";i:3000;}s:6:"module";s:4:"text";s:6:"weight";i:0;}}s:8:"required";b:0;s:11:"description";s:0:"";}'
    -> where id=9;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0`

You can go to admin/structure/types/manage/blog/display/teaser and on the right next to the format settings for Summary or trimmed you will see a button with a little star on it. Click on it and set your trim length.


subtheme preprocess functions inheritance I'm using Drupal 7 with Boostrap Theme.

I put the main theme inside sites/all/themes/
And as a recommanded I put sub-theme in sites/my-site.com/themes/

It's working fine but my question is about preprocess hook.

The main theme using bootstrap_preprocess_region() to add some attributes to regions.
In my subtheme, I want to alter attributes of a region already "hooked" by main theme.

So, in my sub-theme template.php file I did

<?php
mytheme_preprocess_region(&$variables){
$region = $variables['region'];
switch ($region) {
 case 'header':
 $variables['attributes_array']['id'] = 'main-header';
 break;
}
?>

But there is no effect in my output ; main theme preprocess function is called after my subtheme preprocess function :(
(I dumped string inside each preprocess to see which is called first)

Is that normal ? Is there a global workaround ?

EDIT : solution (can't answer myself before 8hours after posting)

Ok for those who're interested in the why :

It's a "side effect" of Twitter Bootstrap theme specific loader (_bootstrap_theme(), bootstrap_include ...)

To respect the correct order of hook processing, we have to keep the same filename as the main theme where hook is located in. (directories tree could change)

In my case, bootstrap_preprocess_region() was located in \sites\all\themes\bootstrap\theme\system\region.vars.php, so to overwrite it the mytheme_preprocess_region() should not be in my subtheme template.php file (=> breaking order of processing)

It should live in \sites\my-site.com\themes\mytheme\(opional folder)\(optional folder 2)\region.vars.php

Not explicitly written in TBS documentation I think ...

I hope this could help someone one day ! (:


Trying to make my entire site https I am trying to make an entire Drupal site https.

I tried enabling secure pages, and this seems to work for every authenticated user.

However any anonymous user either gets only http, or possibly an infinite redirect if I wildcard all possible paths.

How do I get https:// to work on every page, for all users, including anonymous?

This is what my current .htaccess has in the mod_rewrite.c section:

  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

It's usually easier to redirect at the Apache level if you're looking to make the entire Drupal HTTPS. You can place this in your .htaccess file:

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


How do I present the user login form from a callback, and redirect them after login? I need to present the user login form from a callback function that I have registered in hook_menu(), at that specific URL.  When the user logs in, I need to direct them back to that URL to present them with other options. Currently, I call:

if (!user_is_logged_in())
    drupal_goto('user/login');

Of course, that takes them to the login page.  I imagine I need to call drupal_get_form() to present the form from here, but how do I direct them back to this page after login?

You can render the user_login_block on your page. Once the user successfully log in, they will be redirected to the same page on which the user login block was generated (so the same page actually).

To render the user_login_block, you can make use of the drupal_get_form and passing the form name as an argument.

function YOURMODULE_page()
{
    $build = array();

    // construct your build with parts of the page
    // ...

    if (!user_is_logged_in()) {
        // user not logged in, add the login form
        $build['user_login'] = drupal_get_form('user_login_block');
    }

    return $build;
}


Responsive/Fluid Views for Responsive/Fluid Website I an creating a Responsive/Fluid website with Drupal. Everything is great, expect when I create a view with the view module, I cannot the view to become responsive/fluid like other images I have on the site.

What I have tried is to make the .views-field-field-images width 100%, which should make the image with in views responsive. However no luck!

Any help?

Are you using a responsive base theme? If not, try a responsive theme like Omega. It is also possible that the order in which your CSS files being loaded, was set in a way that the base theme (assuming non responsive), overwrote what you have written. Make user that when you do drupal_add_css, you use proper weight and group value, to manage their load order.


What's wrong with my code to overwrite a block template? I want to render a template from a custom block.

When I check the source with Twig debug enabled, I see the following output.

Moz: Graph

My module structure is the following.

wk_elastic
  Plugin
    Block
     MozGraphBlock.php
  templates
    block--wk-elastic.html.twig
  wk_elastic.info.yml
  wk_elastic.services.yml

The code I use to build the block is the following.

/**
 * @file
 * Contains \Drupal\wk_elastic\Plugin\Block\MozGraphBlock.
 */

/**
 * Provides a 'MOZ: Graph' block.
 *
 * @Block(
 *   id = "moz_graph",
 *   admin_label = @Translation("Moz: Graph")
 * )
 */
namespace Drupal\wk_elastic\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Elasticsearch;

class MozGraphBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $hosts = array(
      '192.168.10.10',
    );

    $client_builder = Elasticsearch\ClientBuilder::create();
    $client_builder->setHosts($hosts);
    $client = $client_builder->build();

    $query = array(
      'query' => array(
        'match_all' => array(),
      ),
    );

    $params = array(
      'index' => 'moz',
      'size' => 10000,
      'body' => $query,
    );

    $response = $client->search($params);

    return array(
      '#markup' => $this->t('Hello, World!'),
      '#theme' => 'block--wk-elastic',
    );
  }
}

What is wrong in my code?

You can create a directory called templates/ in your modules root. Place your template here.

Now let Drupal know you store the template in your module. in your_module.module add this function:

function YOUR_MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'block__my_module' => array(
      'render element' => 'elements',
      'template' => 'block--my-module',
      'base hook' => 'block'
    )
  );
}

Finally be careful about where you place your twig file and what you name it. Create a templates directory in your module directory, and replace the _ in the theme function name with -: mymodule-block.html.twig

Don´t forget to clear the cache.

According to answer written by Nicensin in this post: Drupal 8 custom block (module) create twig template file


Attach a simple custom handler to a Webform I'm trying to create a custom webform handler. I'd like to be able to attach my handler to any webform and have it display the message 'xyz' when the (multi step wizard) form is finally submitted. I have this file in my custom module at:  my_module/src/Plugin/WebformHandler/PostWebformHandler.php.

<?php

namespace Drupal\test_b\Plugin\WebformHandler;

use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform test b handler.
 *
 * @WebformHandler(
 *   id = "test_b",
 *   label = @Translation("Test B"),
 *   category = @Translation("Test B"),
 *   description = @Translation("Test B webform submission handler."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class TestBWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    \Drupal::messenger()->addMessage(t('xyz'));
  }

}

On navigating to my Webform settings, I see:

but when I click Add handler for Test B it does not attach to my form handlers?

The above code works. My mistake was in the naming of things. Name all files, classes etc. foo and it will attach.


Select any entity created today One of an entity properties is a timestamp, set when it was created.

I want to use the EntityFieldQuery class to load entities that were created today.

Normally, I would write a query using DATE_FORMAT(FROM_UNIXTIME(created_timestamp), "%Y-%m-%d") = "2014-03-17".

I'm not aware of any method to use any MySQL functions in EntityFieldQuery. I have tried with the following code.

$day_start = strtotime(date('Y-m-d 00:00:00', $created_ts));
$day_end = strtotime(date('Y-m-d 23:59:59', $created_ts));
$query->propertyCondition('created', $day_start, '>')
  ->propertyCondition('created', $day_end, '<');

Whilst this works, it doesn't seem as efficient and certainly less succinct. Is there a function that I can use with EntityFieldQuery similar to SelectQuery::where() that would allow to write code similar to the following one?

$query->propertyWhere('DATE_FORMAT(FROM_UNIXTIME(created), "%Y-%m-%d")', "2014-03-17");

You can use below code , PropertyCondition accepts range values using BETWEEN operator.. Since timestamp is stored as int in database node table created column with data and time together below code works to fetch records of a particular date..

<?php
$day_start = strtotime(date('Y-m-d 00:00:00', $created_ts));
$day_end = strtotime(date('Y-m-d 23:59:59', $created_ts));
$query
    ->propertyCondition('created', array($day_start, $day_end), 'BETWEEN');
?>

Find more about propertyCondition in D.O


Filter for taxonomy term view If I create a view for content types, then the filter allows me to display selected taxonomy terms on the view. Right now, I need to create a view for taxonomy terms and their related fields, but I only want to show some of them. When I select the filter of Taxonomy Term: Term, I do not get the option to select the terms I want displayed.

After I choose is one of, there is no option to choose is one of what. Is this a bug or am I doing this wrong?

When you create filter "Taxonomy term: term" there's first step you are choosing "vocabulary" and "selection type" of the filter. It looks like vocabulary you have chosen has no terms.


How to default checkboxes to checked while maintaining custom return value I'm working on a migration project. I have a form in a custom module that creates a series of checkboxes for URLs to scrape. The form logic looks like this:

foreach ( \Drupal\scrape\Api\Scraper::loadUrls() as $index => $url ) {
  $form['url_' . $index] = [
    '#type' => 'checkbox',
    '#title' => $url . ' &mdash; ' . \Drupal::l('(link)', Url::fromUri($url)),
    '#return_value' => $url,
  ];
}

This code does what I want it to do, but all the checkboxes default to 'unchecked'.

'url_0' => integer0
'url_1' => string(27) "https://myurl1.com"
'url_2' => integer0

I want these checkboxes to default to checked. I couldn't find documentation on how to do it in Drupal 8, so I tried several things, and finally hit upon '#checked' => TRUE, (or any value that evaluates truthily). Now the checkboxes are defaulting to checked.

However, even though I have #return_value specified, the value returned in the form submission is now TRUE (from kint):

'url_0' => boolTRUE
'url_1' => boolTRUE
'url_2' => boolTRUE

Since any truthy value defaults the checkbox to checked, I tried '#value' =>  $url, but then upon submission, the values don't indicate their checked status:

'url_0' => string(86) "https://myurl0.com"
'url_1' => string(27) "https://myurl1.com"
'url_2' => string(29) "https://myurl2.com"

I guess my final option is to have a separate, hidden value for each URL, and map checkbox values to see if the user wants that URL included.

Is there a way I can default my checkboxes to TRUE, while maintaining their #return_value?

Sorry for such a late response but it is possible, I ran into this same issue using 8.5.3 the below configuration worked for me.  You just have to use both together, i successfully passed numbers, text, bool (becomes 0 or 1), and arrays through #return_value.  The class was just for formatting, you can leave that out if you're not using it.

'checkbox_1' => [
    '#type' => 'checkbox',
    '#title' => t('Checkbox 1'),
    '#default_value' => 1,         // Default to checked
    '#return_value' => "checked",  // Return the value if checked
    '#attributes' => ['class'=>['check_group']],
],
'checkbox_2' => [
    '#type' => 'checkbox',
    '#title' => t('Checkbox 2'),
    '#default_value' => 0,         // Default to unchecked
    '#return_value' => "checked",  // Return the value if checked
    '#attributes' => ['class'=>['check_group']],
],

Output will look like this if you dpm($form_state->getValues()) in your submit or validate function.

Array
(
    [checkbox_1] => checked
    [checkbox_2] => 0
)


Handling data from form in modal dialog I'm building a tool that contains a few clickable regions. Each region has a link with class="use-ajax" data-dialog-type="modal" pointing at a custom form route.

Everything is working great and I'm able to get the data from the form and store it. I, however, need the user's selection in this modal form to be reflected in the region they initially clicked.

I'm at a loss aside from storing their selections in localStorage or something and populating that region when they close each modal. That seems a little hacky though. Is there a cleaner way of accomplishing this that I'm missing?

      Click to select

You can pass down your region's ID as parameters to your route. For example:

...

As explained here you can add arguments from the route to your form.

On the buildForm method you can have something like this

public function buildForm(array $form, FormStateInterface $form_state, $region = NULL) {
  // Your code...
  $form += [
    'button' => [
      '#type' => 'button',
      '#value' => $this->t('Submit this form),
      '#name' => 'ajax_trigger',
      '#ajax' => [
        'callback' => '::updateRegionAjaxCallback',
        'wrapper' => $region, // Assuming $region is the argument passed down.
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'click',
      ],
    ],
  ];
}

Later your callback method could look like.

public static function updateRegionAjaxCallback(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new AppendCommand(NULL, [
    // Your render array with the data to be displayed.
    '#cache' => [
      'max-age' => Cache::PERMANENT,
      'contexts' => ['url'],
    ],
  ]));

  return $response;
}

This should work but keep in mind that will be best capture the form submit and triggering a custom AJAX event.


How to create a new custom content type record when a user registers My client's Drupal 7 website has a custom content type which is currently being used as a user profile. Now we need to incorporate this custom content type with the Drupal registration process. That is to create a user profile(a new record in custom content type) when a user registers. The User profile content type has many fields which asks for personal details and there are many views that are based on this content type. Therefore, I need to have this content type as it is but to incorporate this somehow with the Drupal registration process.

Is this doable?

Since you are deeply in your project I see two possibilities right now:

Site builder

Add all the required fields to your user profile, and use something like complete_profile to force completion. Maybe profile2 might help as well. Once you gathered a complete profile use rules to create a node of the content type you strive to create. Upon creation, you might want to drop the profile field contents etc., I think profil2 might be the better solution, so you don't have the to use drupals core profile, and can drop that filled profile once you don't need it, or even disallow changes after creation / hide fields of it etc.

Developer

try to get the node fields of the node add form for your specific content type and merge them with the registration form.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
     dpm($form);
     module_load_include('inc', 'node', 'node.pages');
     $node_form = node_add('nodetype');
     // $output = drupal_render($form);

     // this copying probably has to be done in a better way, e.g. by only the fields you need.
     $form['node'] = $node_form;

     // register a submit handler, so you can create the node/ do validation whatsoever
     $form['#validate'][] = 'mymodule_user_register_validate';
     $form['#submit'][] = 'mymodule_user_register_create_node';
   }
}

If your node form has a file upload widget, you should add the following lines to the menu array:

'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

submit handler:

There are probably better ways to do this, e.g. reuse the existing node submit handler, instead of mimicking it's behavior.

// validation option 1: do it manually
function mymodule_user_register_validate($form, &$form_state) {
  // Extract the submitted data
  $name = $form_state['values']['node_title'];
  // Check it according to your own logic
  $is_valid_name = your_check_for_valid_name();
  // File error, when not valid
  if (!$is_valid) {
    form_set_error('name', t('Name already taken, please choose a different one'));
  }
}

// validation option2: forward it to node_submit
// this way you will have to mock a node object before though.
// node_validate($node, $form, &$form_state);

function mymodule_user_register_create_node($form, &$form_state) {
  $node = new stdClass();
  $node->type = 'nodetype';
  $node->title = $form_state['values']['node']['title'];
  $node->language = LANGUAGE_NONE;
  $node->uid = 0; // you probably have to somehow find out the created uid from the registration and link this here
  node_object_prepare($node);
  $node->field_something[LANG_NONE][0]['value'] = $form_state['values']['node']['sometextfield'];
  node_save($node);
}

This code is far from being ready to use (I just drafted it straight from my head, you will have to dpm() some values and see how it fits together, but the logic/ workflow is there.

extra:
look at how entity_form_submit_build_entity(); is used to see how core get's the form, form state values and creates an entity with the given input, instead of doing this by hand. Be aware that at that stage you probably have to make sure that everything required is available, which might be harder than doing that stuff in custom code in the first place.

extra2:
to link this created node with the user created, you might want to put the created node id in global space and retrieve it in a hook that is called after user save.

  // mymodule_user_register_create_node() ...
  node_save($node);
  $GLOBALS['user_register_linked_nid'] = $node->nid;
  // ...

  function mymodule_user_insert(&$edit, $account, $category) {
    //maybe the submitted values are in $edit as well, than we dont have to do the node creation stuff in the user submit handler and we could do it here.
    // else you can still fetch the global variable
    if (isset($GLOBALS['user_register_linked_nid'])) {
    $account['field_node_reference'][LANG_NONE][0]['target_id'] = GLOBALS['user_register_linked_nid'];
    field_attach_insert('user', $account);
    }
  }


Style a menu inside a specific block I've created one menu to be placed on the left column and with context it will be repeated on the footer too.
The difference is that the footer menu has to be already expanded and show all the child.

I can use  this code below to make it as expanded

function mytheme_menu_link_alter(&$item, $menu) {
    if($item['menu_name'] == 'menu-about-us')
    {
        $item['expanded'] = 1;
    }
}

How do I targer the menu in the footer?
How should I use the function mytheme_preprocess_block(&$variables) ?

Thanks in advance.

What your after is the following...

context_active_contexts()

http://api.drupalize.me/api/drupal/function/context_active_contexts/7

Example:

if (module_exists('context')) {
    $active_contexts = array_keys(context_active_contexts());
    if (in_array('SOMETHING', $active_contexts)) {
       //...
    }
}


Restrict access to a section of the site implemented by a custom module I have a site with two different type of users: clients and anonymous users.

I'm currently building custom modules to handle a "client administration" section of the site, where clients are able to change their profiles, modify custom settings, etc. There is a section of the site "client" users are able to access, but regular users are not.

How can I restrict access to that section to only a particular class of user?

If you implement hook_permission in your custom module, you can control the access of your client administration section.

Set up roles. You've done this already with the client role.
Implement hook_permission():

function MODULE_permission()
{
    return array(
        'access client administration' => array(
            'title'       => t('Access Client Administration'),
            'description' => t('Allow users to access client administration'),
        ),
    );
}

When you define hook_menu(), make sure you set the permissions accordingly:

function MODULE_menu()
{
    $items['client_administration'] = array(
        'title' => 'Client Administration Page',
...
        'access arguments' => array('access client administration'),
    );

    return $items;
}

Go to admin/people/permissions and set the permissions for 'Access Client Administration' to your client role.


Add widget to file field I am looking to write a field widget to extend the file field in Drupal 7. The reason is that I want to do some file parsing after it has been uploaded. Are there examples I would be able to look at? How should I got about writing this new module? Or is there a better way I can do this?

You can check the hook_field_widget_info()

function hook_field_widget_info() {
  return array(
    'text_textfield' => array(
      'label' => t('Text field'),
      'field types' => array('text'),
      'settings' => array('size' => 60),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    );

}


Deleted FAVICON from themes folder is showing up I have deleted the favicon.ico from the themes folder.

But its still showing up the same favicon. I totally confused.

Steps I have taken: But nothing works... :-(

Checked whether I am in the right directory.
Cleared browsers cache.
Cleared Drupal Cache.
Use the default shortcut icon is checked. (No custom favicon selected)
favicon is located in the sites/all/themes/theme_name/favicon.ico

Could you guys please advice me is there any other way to check or resolve.

Any help will be thankful and grateful...

Now Its corrected...

On Themes Global Settings I have mentioned the same favicon in differnet folder.

Thats why the deleted favicon dispalyed even after deleting it from the themes folder.

Thanks for your efforts friends...


How to make Expose filter of Author Id from autocomplete to select list? I added a exposed filter of Author and it showing me the autocomplete. How to change it in select list?

I found a solution here https://stackoverflow.com/a/3885759. Is there any other simple way to do it Because I have other filters also so I can't take a contextual filter?

Add a custom module with the help of https://stackoverflow.com/a/16517124 on the same post and solved my issue.


Database deadlock detected On Drupal 8 we're getting a few deadlock conditions - most connected with the cache. There are quite a few answers to this issue but not so much for D8 (which has very different caching mechanism). Is there any way to resolve/mitigate?

Drupal\Core\Entity\EntityStorageException: SQLSTATE[40P01]: Deadlock detected: 7 ERROR: deadlock detected DETAIL:
Process 9131 waits for ShareRowExclusiveLock on relation 8341492 of database 8341380; blocked by process 9130.
Process 9130 waits for ShareRowExclusiveLock on relation 8341562 of database 8341380; blocked by process 9131.
HINT: See server log for query details.: LOCK TABLE {cache_bootstrap} IN SHARE ROW EXCLUSIVE MODE;
Array ( ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save()
    (line 847 of /var/xxx/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

You can try and add the following lines to your settings.php file :
$databases['default']['default']['init_commands'] = array(
  'isolation' => "SET SESSION tx_isolation='READ-COMMITTED'"
);

https://support.acquia.com/hc/en-us/articles/360005253954-Fixing-database-deadlocks


How can I find user role based on user id? There are many user list.
My need is to find out user role based on their user id.

Use user_load() or global $user.

global $user;
$account = $user;
$role = $account->roles;// returns user role.

or

$user = user_load(uid);
$role = $user->roles;//return user role


Format for webform submission node tokens? I have a field on my webform node which is an entity reference to a taxonomy term. I'm printing it in the webform using the token [webform_submission:node:field_sports], which prints the field output, but formatted as a link to the term page, whereas what I want is plain text. For webform submission values, there is the :raw format, but trying to use this with the node field token results in the error "Computed value/markup is using the following invalid tokens: [webform_submission:node:field_sports:raw]."

This token does not seem to respect the display settings on the content type, either; removing the link there does nothing for the display on the webform.

If you use [webform_submission:node:field_sports:0:entity] you can get field values form the taxonomy term.

So to get the name, you can use:

[webform_submission:node:field_sports:0:entity:name]


How do I place super-fish or nice menus in Zen theme main menu? I have successfully downloaded the super fish module and jQuery and placed the jQuery in the libraries folder. I have also activated the module but am having problems placing the super fish blocks in the main menu of my zen theme. Under blocks, there main menu does not appear so am not sure where to place the blocks so that they appear in the main menu.

Once you have installed Superfish, you must define a number of superfish blocks to be available at /admin/config/user-interface/superfish
Then go to the block admin screen and select one of the superfish blocks /admin/structure/block/manage/superfish/1/configure
Define the "Menu Parent" under superfish settings to "Main Menu"
Define the region you wish to have the menu placed in "Region settings"


Redirect the anonymous users to the login page when they try to vote a node I am using Vote Up/Down for voting on nodes. I would like that anonymous users could be see the voting widget, but they should be first redirected to the login page, before they vote. I tried setting the permissions as follows:

use vote up/down on nodes - checked for anonymous user
When I try to vote as an anonymous user I get the following error.

  An error occurred at /vote/node/1470/-1/vote/helpful/59a7d98542754cb9fd01758fbbe95a3a.

  Error Description: 403: Forbidden

use vote up/down on nodes - checked for anonymous user; view up/down count on nodes -  checked for anonymous user
I still get the same error.

Does anyone know what to do to redirect anonymous user to the login page when they try to vote?

I have installed the module that you mentioned and got the same error. It seems that even though the Vote Up/Down module allows you to give anonymous users permission to vote, internally, it does not support it and throws the specific error. I suspect - I'm guessing here - that they are using the user id to "save" what the logged-in user voted and when the user id is 0 (which means anonymous) an error is thrown.

Anyway, the way I see it, there are 2 main paths that you can follow in order to get the functionality that you want:

1) Have someone (= a drupal developer) modify the module for you. This way, you will be able to add the functionality, and even submit the changes it to the module's repository.

Pros: you help the community, you get a clean solution (depending on the developer's skill)

Cons: costly (I suspect), takes time, you get bad code and patch the problem (depending on the developer's skill)

2) Get the functionality through theming. Instead of enabling the module for anonymous users, you can just disable it, and through the node-nodetype.tpl.php file you can just show the image of the voting arrows to the anonymous users (you will have to use an if conditional to check if the user is logged in or not) and make the image point to a link like this:

/user/login?destination=/node/$node->id

This way the user will be redirected to the login form and then back to the node, but he will have to press the vote button again.

Pros: easy to implement, theme based solution = minimal interaction with code

Cons: it's really a work-around, not a solution, the user is not actually voting but he thinks he is voting (not really honest :P)


How can I remove items from the allowed values list of a select field that has data for the values? I've created a content type that has a list / select option field, and I've entered the key|value pairs as necessary for the select list to function.

Data has been entred, and it's been decided that certain terms no longer apply and that they should be deleted.

However, when trying to remove said terms, I get the following error:

Allowed values list: some values are being removed while currently in use.

Obviously, in the life of a project, values are going to change. What's a practical way to remove items once nodes are associated with the listed terms?

This is about the closest thing that I could find:

https://drupal.org/node/1653012

It references a d6 plugin and some patch trickery I'd prefer not to have to resort to.  If I did have to ultimately resort to using the patch to remove the validation check on that field, is there any harm in leaving those items orphaned on the nodes they were associated with?

Update, I have come accross this issue again with a government client who, for the last 7 years of having a Drupal site has had 50 states and territories in a select list. Now, policy has changed and the territories no longer needed to be included. Being able to remove items from the select lists is important, and thus I'm offering a bounty.

I'm looking for a safe solution to be able to remove items from a select list. What I don't know is if that solution should update any of the nodes as I'm not sure how the field values are stored in relation to a node's total content.

I'm happy with a pure SQL solution to run in MySQL; or, I'm looking for a module.

I did something like this recently with the following approach.

Add the new allowed values.
Add a setting to configure "active" values.
Filter out the "inactive" values from display on the form.

e.g:

/**
 * Admin settings form
 */
function MODULE_admin_settings(){

  $form = array();

  // Select active preferences for display
  $field = field_info_field('field_preferences');
  $preferences = list_allowed_values($field);
  $form['field_preferences_active'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Active preferences'),
    '#options' => $preferences,
    '#description' => t('Select the preferences available for user selection.'),
    '#default_value' => variable_get('field_preferences_active', array()),
  );

  return system_settings_form($form);

}

/**
 * Implements hook_field_attach_form
 */
function MODULE_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {

  // Filter out inactive preferences
  if(isset($form['field_preferences'])){
    $preferences = variable_get('field_preferences_active', array());
    foreach($preferences as $key => $preference){
      // If this preference isn't checked, but is set in the field values, unset it.
      if(empty($preference) && isset($form['field_preferences'][LANGUAGE_NONE]['#options'][$key])){
        unset($form['field_preferences'][LANGUAGE_NONE]['#options'][$key]);
      }
    }
  }

}

This way the legacy data is preserved for reference, the form validates, and the data integrity is intact.


Export node to Ms Word file I would need to export nodes in Ms Word format.

I would need to mantain the node structure or to apply a template.

I don't want to export data in a table like "Views data export" module does.

In Drupal 6 it was done using "node to word" module (https://drupal.org/project/node_to_word), but the module doesn't exist for Drupal 7.

thank you in advance

The module Views data export claims to do it:

  Style plugins are included that support exporting in the following
  types:

CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML.

So you should be able to construct a view of fields or rendered entities and select the display for a doc file.

See a similar question here: Export node report base on Word and Excel template


Should the "install" button on admin/modules page say "enable"? (I'm still pretty green when it comes to drupal so I thought I'd ask here before putting in a bug report)

At the bottom of the "Extend" page (admin/modules) the button to apply the changes made to the check-boxes is labelled "install", but (to my understanding) it doesn't install anything, it merely enables (or possibly disables) the already installed modules.

I often find myself at this page after clicking the "Enable newly installed modules" link. I see the "install" button and think "but I just installed, now I want to enable".

So, would "Enable / Disable" or "Apply" be a less misleading label?

Or, am I misunderstanding the terminology, or the use of this page?

My understanding is that not all modules that are available in Drupal are installed. I am speaking for Drupal 7 as I am not sure about Drupal 8.

There are three phases:

Enabled: The code is downloaded to your server and the hooks in .module are being called.
Disabled: The code is downloaded to your server, but the hooks are being ignored.
Not-Installed: The code is downloaded to your server, but Drupal hasn't run the .install file for the module and/or hasn't been made aware to look for the hooks.

Also, it's worth noting that if you disable a module, all your data and configurations remain, while uninstalling a module invokes the uninstall hook and wipes both.

So as you can see, the label is relevant to whether or not the module needs to be installed or enabled. You can go from not-installed directly to enabled, but you must go from enabled to disabled to not installed especially before removing the module by deleting it's files.

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


Is there a way to clear the cache without dropping tables? I am new to Drupal and realized that when we clear cache in Drupal 'drush cr'. It executes drop db commands.

This is a very big security issue in our company because granting drop privileges to a mysql user on a production server would be dangerous

What would be an alternate solution?

  In Connection.php line 686:
  SQLSTATE[42000]: Syntax error or access violation: 1142 DROP command denied to user 'xxxxx'@'100.100.100.100' for table 'webprofiler': TRUNCATE {webprofiler}; Array()

  In Statement.php line 59:
  SQLSTATE[42000]: Syntax error or access violation: 1142 DROP command denied to user 'xxxxx'@'100.100.100.100' for table 'webprofiler'

Correction

drush cr is not dropping tables. MySQL Truncate requires the DROP privilege as of MySQL 5.1.16. (Before 5.1.16, it requires the DELETE privilege).
http://dev.mysql.com/doc/refman/5.1/en/truncate-table.htm

So this means when drush cr is run you need a user with drop privileges.

As Kevin correctly points out in the comments, the cache clear is issuing a TRUNCATE command rather than DROP, but TRUNCATE does require the DROP permission.

If you look at the manual installation method in the install guide, you'll see that DROP is one of the permissions that is granted as part of the setup process:

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES ON databasename.* TO 'username'@'localhost' IDENTIFIED BY 'password';

That's followed shortly after by:

  Note: Unless the database user/host combination for your Drupal installation has all of the privileges listed above (except possibly CREATE TEMPORARY TABLES, which is currently only used by Drupal core automated tests and some contributed modules), you will not be able to install or run Drupal.

So DROP is simply a required permission for Drupal to work.


Strategy to consolidate multiple fields across content types? I've got a handful of content types that all use different fields to hold the same type of data. For instance,

Content Type A --
Field Name: field_type_a_user,
Field type: Entity Reference

Content Type B --
Field Name: field_type_b_user,
Field type: Entity Reference

Content Type C --
Field Name: field_type_c_user,
Field type: Entity Reference

I'm building out a view displaying nodes that might reference any of the three of these content types, and the view needs to display information about the user referenced in the node's user field.

It seems inefficient to be using multiple different fields to be storing the exact same type of data. Is there an efficient way to go about creating a new field, field_user, and moving the data from all of these old fields into the new field? And then update all references throughout the site to use this new field?

Or would it be better to just add all three fields to my new view and call it a day?

I can't say which is better, because it depends on what customization you intend to do in the future.

That said, generally speaking, if you have different content types that use the same field for the same purpose, you should choose to re-use the field across content types in the design stage; doing so would've saved you the trouble you face now.

How to consolidate multiple fields

First, create a new field on one content type.

Next, re-use the field on all the other content types you want to use it on.

Then, see this question on renaming fields for information about how to use SQL to copy the data from the old fields to the new fields.  ALWAYS make a backup before doing this; if you make a mistake in this step, you can break your site.

Now, you will have to fix your views, twig templates, and anything else that might be broken.  You can go to your exported config folder and search for the field names of the old fields, but I wouldn't change the config directly; I would use the config folder as a hint of what to change, and then update the values in the UI.  I'd do this because sometimes one setting changes another, and if you do it in the UI, everything should get changed properly.


Context condition per menu (not menu item) I'm using Context module on Drupal 7 to show menu block on pages that's listed in that menu only.

Everything's good, I set 'Menu' condition and reaction is to show the block in some region, but the problem is that I must select menu items in condition and since items changes all the time I need to update Context all the time.

Is there some solution to select menu and not menu item, or to select menu item and automatically to include all submenu items?

There doesn't seem to be a way to select a menu itself in Context Conditions.

Maybe you have something else common among those menu items that you can combine in different Conditions to get the same result? Maybe paths are similar? Or Content types?

Alternatively you can use a module other than Context just for this particular need: Blocks per menu.


Need a price quote engine Folks, I need a module that will give me the ability to collect service requests from anonymous users and will return to them an estimated price, so a quoting engine basically.  I need the information they submit to also be summarized and sent in an email to a sales rep.

I know about Ubercart, but it seems to be overkill for what we need.  Does anyone have experience with it and can vouch for it as far as this problem goes?

EDIT: Further elaboration on collecting service requests.  The requestee selects a few services that they require, and in what quantity, and this request is forwarded to a sales rep who then prices out the request and contacts the requestee via email with a price quote.  Really I see this as a one way mechanism where requests are just submitted, and then the rest of the conversation is carried out either over the phone or via email.

Receiving requests

With webform, you can create forms that allow you, or your site-admins, to create and maintain the form that site-visitors will fill out. When the form gets submitted, you can use Rules to send this information on as an e-mail. The module Webform Rules, provides the bridge between the two modules, allowing Rules to react to webform events.

Answering requests

Just turn the whole process around. Again, use webform to create a form for the request reciever to fill out. When this form gets submitted, send a mail to the requestee with the reply.

Custom work

You will most likely need to do some amount of custom coding to make this whole thing work. For example, in the mail to the sales rep, a link must be autogenerated to a form that gets prefilled with the requestee's e-mail. Auto-filling the form is likely best done as a hook_form_alter. There is a lenghty Rules video series that you can view to learn more about how to work with Rules and how to extend it to do what you need.


Why is my $node always null in my custom block (using plugin contexts)? I am trying to make a block that gets the current node via Plugin Contexts.

But my $node is always null. Can anyone tell me why?

I am placing the block with the context module if that makes a difference?

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Header' block.
 *
 * @Block(
 *   id = "header",
 *   admin_label = @Translation("Header"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE)
 *   }
 * )
 */
class ProductStickyHeader extends BlockBase {

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

    $node = $this->getContextValue('node');
    // $node is always null!

    return $build;
  }
}

Many thanks!

Thanks everyone - turns out the answer was deceptively simple - I had to remove the block using context & then re-add it. When I re-added it there was an extra option in context to use the current node. Then the context plugin worked!


Read the content of a file I have added a content type in Drupal 7 which contains only a file field. Every file needs to contain an array like the following:

'rows' => array(
   array(0,0), //(x,y) values
   array(90,90),
   array(59,70),
   array(65,77),
   array(85,66),
 )

I want from the view module to read the content of the file and send the array to the selected graph type; for example, the user select a file and then a pieChart graph.

how can the content of the file be send to the pieChart library? Is that possible from the Views module? What function have to be added to the view plugin in order to send the content of the file to the selected library?

You will probably have to create a library, module, or simple a function Wick does the logic of this, and then call the function from where you want (views).

It's a pretty generic question, without more info is difficult to know what you are trying to achieve, but in similar situations what we use to do is create a separate library or module which is called from cron, for example.

This library will keep updated a second content type, with the contents of your files, RSS, XML, etc.

When views saves this content, you'll simply have to link both content types, probably making it faster simply reading contents and leaving the logic to a background process (managed by cron).

But again, maybe you are trying to achieve a different thing.


How do I get kint() to include the variable name in output? My understanding that normally kint will display the variable name in the output, e.g. $abc. But in my code kint($abc) never outputs the $abc label so when I have multiple kints it becomes very confusing. Any idea how to force this or label kint output?

Put the variables in an array. Then you see the variable names and you have the advantage, that if the first variable is a big array you can collapse it to see the second one:

kint(array(
  'abc' => $abc,
  'def' => $def,
));


URL patterns with entity reference Possible Duplicate:
  Path alias tokens and node references

I'm having some difficulties setting up url patterns for my drupal project.

The site has 3 different content types, Main category, sub category and products.
All of these are linked together by entity references.

So a sub category is linked to a main category, and a product is linked to a sub category.
But now I want my urls to look like: main_category/sub_category/product
Or for a sub category it should look like: main_category/product

How would I be able to achieve this? I've installed path auto, but can't seem to figure it out.

EDIT: And another question would be, what would be the easiest way to create a menu out of this?

It has been solved before. Have a look at https://drupal.stackexchange.com/a/36025/6286


Adding a view desktop link to mobile site I am using X-AH-Mobile-Redirect in the settings.php file to redirect visitors to the mobile site. I need to add a link so that visitors can switch to the desktop site.

Here is a snippet of the redirect code:

    if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
  switch ($_ENV['AH_SITE_ENVIRONMENT']) {
case 'dev':
   header('X-AH-Mobile-Redirect: http://m.mysite.com');
  break;
  }
};

I don't know about X-AH-Mobile-Redirect, but I did this a while ago by creating a link like http://example.com/?device=desktop and on page load I would check for $_GET['device'] and for a cookie

Then I could just check

if (isset($_GET['device']) && $_GET['device'] == 'desktop') {
    setcookie('mycookie', 'true', strtotime('+365 days'));
    $mobile_browser = 0; //This forces site into desktop mode
}

Then on desktop version you just go the other way around with a http://example.com/?device=mobile

if (isset($_GET['device']) && $_GET['device'] == 'mobile') {
    setcookie('mycookie', null, -1); //Unset cookie
}

Of course you have to add whatever you need to force your mobile detector to go into mobile/desktop version, but it's pretty much it, on page loads check for the cookie and for the query strings and act accordingly.


Can't uninstall module that depends on custom field type in use Drupal 8

Using Yoast, I've removed it from all my content types but I can't uninstall because it says --> The Yoast SEO status & focused keywords field type is used in the following field: taxonomy_term.field_yoast_seo, which I did not create nor is it visible via Structure > Taxonomy.

Looking into the DB, there's over 51 matches for 'field_yoast_seo', but I can see where it is created:

It's a table. I don't know if I can just go ahead and delete it without it backfiring on me. Has anyone tried it?

If a module define a field type, it can't be uninstalled if you have a field of this type. This is not related which tables are in the database, and deleting tables in the database wont resolve this.

What you need to do, is to delete the field yourself. Drupal doesn't want to this automatically, as it could mean data loss. From the message you get the field name taxonomy_term.field_yoast_seo. This machine name is structured as ENTITY_TYPE.FIELD_NAME, so the field you need to delete is on a taxonomy term. It doesn't tell which vocabulary it's located on, but hopefully you can find it manually and resolve it


How to remove all commerce coupon from database? Hi I have used commerce coupon module. I have lot of entries of used coupon. So, right now I want to delete all commerce coupon from database. I have 860000 coupon entries in database. How can I delete all entries using custom module functionality?

Since coupons are entities, you'll want to delete them using the entity functions. As an example, if I want to delete all disabled coupons, something like this should work:

$disabled_coupons = commerce_coupon_load_multiple(array(), array('status' => 0));
$disabled_coupon_ids = array_keys($disabled_coupons);
commerce_coupon_delete_multiple($disabled_coupon_ids);

If you need to batch them, you may want to try doing them in batches of 250-1000... not sure how many can be deleted successfully per batch. Then just let it run.