Programmatically create a term? I'm attempting to add a lot of terms (~200) to a vocabulary, but I can't find any import modules that are updated for Drupal 8, and it seems the functions for doing this in Drupal 7 don't exist in Drupal 8. So, can anyone point me in the right direction for doing this?

I attempted to do it with entity_create, as suggested in the comments, with this code:

$term_create = entity_create('taxonomy_term', array('name' => 'test', 'vocabulary_name' => 'client'));

but I got this error:

Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type taxonomy_term in Drupal\Core\Entity\FieldableEntityStorageControllerBase->create() (line 65 of core/lib/Drupal/Core/Entity/FieldableEntityStorageControllerBase.php).

Any ideas?

You know that you want something from taxonomy module so first you need to look in Drupal\taxonomy\Entity -- or the corresponding directory -- you will find the Term class there. Now look at the annotation, it says @ContentEntityType and in there:

*   entity_keys = {
*     "id" = "tid",
*     "bundle" = "vid",
*     "label" = "name",
*     "uuid" = "uuid"
*   },

So, what you want is

$term = Term::create([
  'name' => 'test',
  'vid' => 'client',
])->save();

because the label entity key is name and the bundle entity key is vid. I added a ->save() call as well as I presume you wanted to save it too.


How to retrieve all nodes for a taxonomy term using Services? I want to retrieve all the nodes associated with a given taxonomy term (field_term) using HTTP GET.

I have tried:

curl -v http://myserver/endpoint_path/node?parameters[field_term]=1

but I get an HTTP 406 Column not found.

Also later on I will need to use multiple taxonomy vocabularies to filter by more than one term.

I am using the Services 3 module in Drupal 7.

I found out how to do it, so I am posting it here in case it is helpful to somebody.
Feel free to post if you know a better way.

I assume you have created some content with fields corresponding to taxonomy vocabularies.

Create a Services View

Install the Services View module, as suggested in my previous comment.
Go to Structure / Views / Add new view
Give your view a name and uncheck 'create a page' because we just want a service.
Click 'Continue & Edit', you should then be in the 'Displays' screen.
Click on the '+Add' displays button, select 'Services'.
Under 'Service Settings' click on the path and change it. e.g my_view_path.

Create criteria for your view

Under 'Filter Criteria' click 'Add'. Do not use Advanced/Contextual Filters.
Search for your field, and click Apply'
'Autocomplete' in the Selection Type, 'Apply and Continue'. It should not matter because we are going to call this from a URL, not a web page.
The 'Configure filter criterion' popover is shown.
Check 'Expose this filter to visitors'. If you don't do this, you will not be able to pass as an argument.
Scroll down to the bottom and click on 'More'.
Take note of the 'filter identifier'. This is the name of the argument you need to pass in the URL, e.g: field_myterm_tid
Click on Apply filter
Repeat for other filter criteria as needed.
Click on Save View

Enable the Service Resource

One last step, go to Structure > Services
You should see a list of endpoints, click 'Edit resources'
Check to enable the resource you just created.

Finally, retrieve your info with HTTP GET

    http: //myserver/my_endpoint_path/my_view_path?field_myterm_tid=XX&field_myterm2_tid=YY

XX and YY are the textual names of the terms


Is there way to display thumbnail gallery using external links to images? Drupal 7, is there way to display thumbnail gallery using external links to images?(instead of uploading pictures)
Something like

https://wordpress.org/plugins/wp-gallery-custom-links/screenshots

I have Views, Imagecache External, Views Responsive Grid modules installed, but no one of them helps me to achieve this simple task. I want create responsive thumbnail gallery with external images.

It might be it is the Link Image Formatter module that you are after.

It is a image formatter for a Link field. The modules you mentioned can then be used to construct your gallery (Views, Imagecache External, Views Responsive Grid).

You could also rewrite the field output in Views by using the "token" and wrapping it in the needed HTML to display it as an image, something like:

<img src="[link]">

Make sure you get a plain version of the image URL, so you better check without rewriting first.

Note that using Imagecache External will result in images being stored on your own server. It doesn't free you from copyright issues as with embedded external images (hotlinking). That means you could alternatively use FileField Sources.

An extension module of the last one, Remote File Source, might avoid transfer of the image file on your server. I haven't tested that. You are likely to miss out on Image Styles in that case (e.g. to resize or cache images locally).


How can a field be rendered as a  element? The problem:

I would like to be able to manage custom <meta> elements, on a per-item basis in a custom theme. An example would be for adding open graph and schema tags, but I'm really looking for a generic solution.

I'm aware of custom modules, such as Meta Tags, but I'd rather avoid relying on other modules at this point.

What I've Tried:

After looking at them_field it looked as though I should create a custom theme function for my custom field (field_test being used for this example). The theme function could add a <meta> tag and not return any content to be rendered.

In template.php:

<?php
//I *did* actually use my theme name instead of THEMENAME
function THEMENAME_field__field_test($vars) {
    drupal_add_html_head(array(
        '#tag' => 'meta',
        '#attributes' => array(
            'content' => drupal_render($vars['items'][0]),
            'name' => 'test'
        )
    ), 'test');

    //I figured this would prevent the field from being rendered inline
    return '';
}

Using that code the custom <meta> element was correctly added to the <head>. Nevertheless, the field was still rendered on the page.

If I changed the output to:

return ' ';

The content was no longer rendered to the page, but an unnecessary space character would be output where the field was to be rendered.

Is there a better way to render a field as a <meta> element?
-or-
How can I prevent this themed field from rendering inline?

try to return drupal_add_html_head array directly

<?php

function THEMENAME_field__field_test($vars) {
    return drupal_add_html_head(array(
        '#tag' => 'meta',
        '#attributes' => array(
            'content' => drupal_render($vars['items'][0]),
            'name' => 'test'
        )
    ), 'test');
 }


Display an image in menu generated from taxonomy terms I am using Drupal 7 with Taxonomy and Taxonomy Field Menu to generate a menu based on taxonomy terms (Categories) - including node links (the terms themselves are not linked, just the nodes, in case this is important somehow). I am using this menu in Panels in two panes.

I need to display an image alongside the nodelinks (just one per taxonomy term) and this image needs to be easily replaceable from the backend. The menu is supposed to look like this:

- Home
- Taxonomy Term 1
    - Node
    - Node
    - Node
    [Image for Term 1]
- Taxonomy Term 2
    - Node
    - Node
    - Node
    [Image for Term 2]
- Taxonomy Term 3
    - Node
    - Node
    - Node
    [Image for Term 3]

The views module is not really an option, as I don't have enough time to work through and understand 30 chapters of "Taming the Beast". It may pay off in the long run, but there simply isn't enough time for views at the moment. Any alternative approaches are welcome.

Try the Taxonomy Image module

The taxonomy_image module allows site administrators to associate images with taxonomy terms. With the association created, an admin can then make a call to 'taxonomy_image_display()' from their theme or other PHP code to display the appropriate image.


Server Deployment of Economist.com As documented here, it seems the Economist is using Drupal for most of it's site.  I am just curious if anyone has information on the number of servers and their config.  Any idea?

They have 2 Varnish servers, 10 web servers and 4 database nodes (2 master, 2 slave)

Their workflow is Trunk -> Stage -> Live, from bzr.

They are fully Drupal for a month or so, now.

See The Economist: An Informal Technical Case Study session video from DrupalCon London for more information on their processes.


How to check if View is empty with PHP I'm using Simplenews Scheduler to automatically send a digest of new nodes, by inserting a views token into Body field of the newsletter.

I need to prevent sending the newsletter if the View in question is empty (triggers No results).

Simplenews Scheduler allows for PHP evaluation (see at the bottom of the screenshot):

What do I need to enter there to ensure no new newsletter is created and sent if a certain view (with certain exposed filter or contextual filters options) has no results?

I believe this will do:

!empty(views_get_view_result('your_views_machine_name','your_display_id'));

If you need to pass arguments, you can pass them as individual strings after the display id. See the API documentation. I'm not sure if you can pass exposed filter arguments, though (the above would work fine for contextual filter arguments).


What might cause duplicate user registrations? We have a site with about 16,000 registered users. I've just discovered there are over 100 duplicate user registrations.

These users have all the same details (username email etc) and have been created at about the same time and have a uid that is just one more than the original.

We are using Email Registration module 7.x-1.3. I've tried duplicating the problem by hitting the submission button multiple times and be creating an identical submission. However, I always get the validation error.

Any suggestions?

Note: we also use Rules and there is a rule triggered by a "After updating an existing user account" event. The rule runs some simple PHP code that adds the users details to a CSV file.

I think that this part of your question is crucial:

  ... there is a rule triggered by a "After updating an existing user account" event. The rule runs some simple PHP code that adds the users details to a CSV file.

I.e. to (a) understand what's happening and (b) to come up with some type of workaround. Read on for more details ...

Understanding what's happening

Your question seems like a variation of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

  some other module code is calling a user_save on hook_user_update triggering the rules event a second time.

If I was to debug this, I'd disable all contributed modules (except "Rules" and "Entity API") to check if it's indeed a contributed module (I don't expect it to be core). And then re-enable the contributed modules one by one until the issue comes back. As soon as it comes back, you pinpointed the contributed module causing the issue, and you can start working on a possible remedy for that.

Workaround 1

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):

Workaround 2

Another workaround to prevent this issue from happening, is to improve your existing rule to make it similar to the rule included in my answer to "How to implement a Rules Condition like [account:last-login] = never?". More specifically:

Add a Rules Condition like: User does NOT (!!!) have a role with role id = "4".
Add a Rules Action like: Grant User the role with role id = "4".

So this improvement of your rule will check if the user does not yet have some (designated) role with role id = "4" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case, then the user is granted that role. With this improvement to your existing rule, this is what will happen:

The 1st time your Rules Actions will still be performed (and grants the designated role).
the 2nd time not ALL of your Rules Conditions will be satisfied (since the designated role was granted before), and therefor your Rules Actions will no longer be performed.


selected option on drupal form not coming up first I added a '#default_value to my drupal7 form , and it says

<option selected="selected" value="81">Service</option>

(this is the option I want selected) but I want it to come out first in the list and it isnt .

how can I get it to come out first?

This is only a problem in firefox, and the way to fix it so it works in firefox as well is to add this:
     $form['#attributes']['autocomplete'] = 'off';


jQuery length of object to determine existence gives error? The following jQuery in my module gives an error that breaks LOTS of other javascript on other modules on the page. I want to know why. Why?

 var pid = $('input[name="product_id"]').attr('value');
 if ( pid.length )
   // do stuff

But this works fine:

var pid = $('input[name="product_id"]').attr('value');
if ( typeof(pid) !== 'undefined' )
  // this works fine

I've been using the first example for years in other environments to test for the existence of an object and it always works. What am I missing?

TIA.

if (pid.length)

causes a reference error in your script if pid is undefined.  So, if you don't know that pid exists ahead of time, then you have to check to see if that object is valid before trying to reference properties on it.

FYI, you could probably just use:

if (pid)

because that would protect you from pid being undefined or an empty string.

It has been raised in comments that maybe you're actually just trying to test for the existence of a DOM object, not the attribute.  If that's the case, then you should just be doing this:

if ($('input[name="product_id"]').length)

which tells you if the selector matched any DOM objects.


Are there modules for managing inline images? I would like to include inline images in my posts. Is there an easy way to:

find (and delete) unreferenced images
find which content references a given image
(ideally) keep things working if I decide to rename an image file
don't show the uploaded images except where referenced manually ("Image" field seems to show all linked images below the post)

After days of searching, I believe the closest there is is the Media module. It goes in the right direction on all counts, but seems to be a long way off "complete".

I haven't found any other modules that even remotely approximate what I'm after.


Detect profile2 save occasion in module and get user Is it possible with custom module to detect occasion when user saves/updates his profile2 profile ? ( i know it is possible with rules but want to do it programatically in custom module).

And from that point, is it possible to load user data (the fields of profile2 profile) that just did the changes ?

Thanks for clues!

Yes it is possible, you can use the generic hook_entity_presave (or update/insert). There is also a specific hook for profile2 as well, hook_profile2_presave (or update/insert), but it requires the Rules module to be enabled.


Adding a temporary column to a db_select query I'd like to add a temporary column with a fixed value to a database query. Eg a column called 'type' with a value of 'thing' for every result. I have tried using the addExpression and addField functions to do this but I'm not getting the right result.

Is this possible using db_select? I've tried the following:

$query = db_select('people', 'p')
   ->fields('p', array('id', 'date'));
$query->addField(':val AS type', array(':val'=>'thing'));

However this is executing the following query:

SELECT p.id AS id, p.date AS date
FROM
people p

I suppose I'm trying to get drupal to do:

SELECT p.id AS id, p.date AS date, 'thing' as type
FROM
people p

You just need to use an expression, e.g.

$query = db_select('people', 'p')
  ->fields('p', array('id', 'date'));

$query->addExpression(':val', 'type', array(':val' => 'thing'));

Gives:

SELECT p.id AS id, p.date AS date, :val AS type
FROM
{people} p

The replacement for :val will be injected when you execute the query.


How to retrieve a term tree for a specific vocabulary given the machine name? Retrieving a term tree for a specific vocabulary  in Drupal 8 requires the vocabulary ID. I can find no function/method/service that will return the vocabulary entity given the machine name, in order to get the vocabulary ID.

How do I get a vocabulary ID from its machine name?

The vid field is the machine name for a vocabulary in Drupal 8.

You just need to pass the the string you have to TermStorage::loadTree, it doesn't need to be altered. For example:

$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree("myname");


Add preview button on Taxonomy add/edit term form As we know that entity type node has preview button option which can be used during adding or editing of a node, to preview content.

Same feature is missing in case of Taxonomy entity.

If I want to add this feature where should I look into or is there any module available to achieve this?

Preview button added by node module in NodeForm as action in actions method:

$element['preview'] = [
      '#type' => 'submit',
      '#access' => $preview_mode != DRUPAL_DISABLED && ($node->access('create') || $node->access('update')),
      '#value' => t('Preview'),
      '#weight' => 20,
      '#submit' => ['::submitForm', '::preview'],
    ];

The Taxonomy entity form created by TermForm.php so i think you should:

Extends TermForm.php in another Class.
Add actions method.
Create a preview method like the node preview method but for the term.
Add a route subscriber to tell drupal to load your form not the default.


Update node multi value field programatically I am trying to update a node with a standard multi value text field programatically with the following:

$node = customfunctionreturnsnode();
$node->field_scores['und'][$dayof]['value'] = $total;
node_save($node);

More info: $dayof is a custom variable, that can be from 1 - 28. $total is numerical value that is determined elsewhere in the code.

Eventually the field will have 28 values, but they might not get entered in the 'correct' order. So I would like to be able to have my code above select which delta to add it to.  Also, the values could get updated, so this will allow me to update the correct value.

It seems to work, and the db shows the right delta. But when I add a new value the previous delta resets to 0.  The new delta has the correct value, but when I add another one the second value's delta goes to 1... and so on.

I checked, and the delta field is not an auto-increment table... but I'm not really sure where to look from here. I couldn't find anyone else that has this issue. Am I doing something wrong?

Thank you for you time.

I think I found a solution.  I used hook_node_presave to check if a value was set, ad if not to set it to -1 for the 28 fields I have.  Maybe not the most elegant (I would love to hear if there is a more drupally way to do this) but it works.

function mymodule_node_presave($node) {
if ($node->type == 'mynodetype') {
for ($i = 0; $i < 29; $i++) {
if (!isset($node->field_scores_a['und'][$i]['value'])) {
 $node->field_scores_a['und'][$i]['value'] = -1;
}
if (!isset($node->field_scores_b['und'][$i]['value'])) {
 $node->field_scores_b['und'][$i]['value'] = -1;
}
if (!isset($node->field_scores_c['und'][$i]['value'])) {
  $node->field_scores_c['und'][$i]['value'] = -1;
}
}
}
}


Looking for a special views exposed filter with pager and select list i'm looking for an exposed views filter like it is implemented at the linked page.
Example here

a) While click on "1.Spieltag" there is a select list.

b) Also there are pager arrows to scroll through 1.Spietag 2.Spieltag ect...

Is there a module or a widget i have missed till now, with which i can achieve the described functionallity? Any other idea how to achieve this?

Thanks Tom

I've updated Ctools, Views and date to the latest version as well.
Here the view i recreated from scratch after having updated the modules:

$view = new view;
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test';
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_label'] = 'Éléments par page';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['pager']['options']['expose']['offset_label'] = 'Décalage';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Champ: Contenu : Titre */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Critère de tri: Contenu : Date de publication */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Contenu : Publié */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Contenu : Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'publi' => 'publi',
);
/* Filter criterion: Recherche : Termes de recherche */
$handler->display->display_options['filters']['keys']['id'] = 'keys';
$handler->display->display_options['filters']['keys']['table'] = 'search_index';
$handler->display->display_options['filters']['keys']['field'] = 'keys';
$handler->display->display_options['filters']['keys']['exposed'] = TRUE;
$handler->display->display_options['filters']['keys']['expose']['operator_id'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['label'] = 'Termes de recherche';
$handler->display->display_options['filters']['keys']['expose']['operator'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['keys']['expose']['multiple'] = FALSE;
/* Filter criterion: Date : Date (node) */
$handler->display->display_options['filters']['date_filter']['id'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['table'] = 'node';
$handler->display->display_options['filters']['date_filter']['field'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['operator'] = '<=';
$handler->display->display_options['filters']['date_filter']['exposed'] = TRUE;
$handler->display->display_options['filters']['date_filter']['expose']['operator_id'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['label'] = 'Par date :';
$handler->display->display_options['filters']['date_filter']['expose']['operator'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['identifier'] = 'datepicker';
$handler->display->display_options['filters']['date_filter']['expose']['multiple'] = FALSE;
$handler->display->display_options['filters']['date_filter']['form_type'] = 'date_text';
$handler->display->display_options['filters']['date_filter']['date_fields'] = array(
  'node.created' => 'node.created',
);
$handler->display->display_options['filters']['date_filter']['date_method'] = 'AND';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test';
$translatables['test'] = array(
  t('Master'),
  t('test'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('Éléments par page'),
  t('- All -'),
  t('Décalage'),
  t('Termes de recherche'),
  t('Par date :'),
  t('Page'),
);


How to link to Entityform submissions page? I am using an Entityform in a block to enable site users to submit enquiries to owners of holiday cottages. I need to be able to allow owners to view those enquiries.

Each holiday cottage has its own page and the Entityform appears on each of those pages.

I have created a submission reports view that will list the enquiries for a specific property.

I have also used Views to create a block to appear on the page of each holiday cottage, visible only to the logged-in owner of that cottage, containing a link for the owner to click on to “View enquiries”.

My problem is what link should I use to display the submissions? I have tried the link "entityform_types/manage/accommodation_contact/submissions” to be found under the ‘FORM SUBMISSIONS’ tab, but without success.

I have also read through all the documentation for Entityform that I can find as well as all issues relating to submissions here.

Any help or guidance would be much appreciated.

Entitform module comes with pre-built Views that list the Submissions. It is called Entityforms (Entityform Submission) and you can access the Page through

/entityform-submissions/submissions/accommodation_contact/list

or the Table where you can see submissions directly:

/entityform-submissions/submissions/accommodation_contact/table

Display one of these links in the Block you created for your owners:

View submissions

These Pages use the access permission View any entityform submission so allow your owners role this.


Views3 and subqueries? I've got a view which generates a query that does multiple joins. This produces a cartesian join, and I need to "convert" the joins to subqueries.

I've looked through documentation, Google search results and other sources, but I am unable to find any decent description of how I can configure Views to do subqueries. I've used hook_views_data() to configure the relationships (which are now carried out as joins). Is it somehow possible to define subqueries through hook_views_data(), or do I need to take another approach?

Any advise appreciated!

I looked further, but could not really find any documentation describing this.

What I needed was a way to join the users table with two other tables holding data for the users. However, the two other tables are in a 'one-to-many' relationship with the users table, meaning that I'll end up with a Cartesian join if I attempt to join the users table with both of these tables at the same time. However, since all I need is to count the number of records in the two other tables associated with any given user, a subquery should be able to do the trick. However, I couldn't find any documentation on Views and subqueries - so here is what I did.

Created two dummy fields

I created two dummy fields (which I'll call 'downloads' and 'listens') through hook_views_data(). The definition of the field are listed below.

function hook_views_data() {

  $data['users'] = array(
    'downloads' => array(
      'title' => t('Downloads'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'listens' => array(
      'title' => t('Listens'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    )
  ),
);

Now, when you configure a view for users, the fields 'Downloads' and 'Listens' will appear. However, attempting to run a query now will result in an error as the dummy fields after all are dummy fields. They do not exist. The only purpose of these fields is to signal to to our implementation of hook_views_query_alter() that it needs to do a few replacemenets.

Implement hook_views_query_alter()

The trick here is to check wether the given query includes the 'Downloads' or 'Listens' fields. If it does, we'll remove the fields from the query and replace them with subqueries. The implementation of this function goes as below.

function mta_views_query_alter(&$view, &$query) {

  foreach ($query->fields as $field_key => &$field_values) {
    if ($field_values['table'] == 'users') {

      switch ($field_values['field']) {
        case 'downloads':
          unset($query->fields[$field_key]);
          $query->add_field(null, "(SELECT COUNT(*) FROM {fileusage} fu WHERE fu.externaluser = {users}.uid AND fu.action = 0)", $field_key);
          break;
        case 'listens':
          unset($query->fields[$field_key]);
          $query->add_field(null, "(SELECT COUNT(*) FROM {fileusage} fu WHERE fu.externaluser = {users}.uid AND fu.action = 1)", $field_key);
          break;
      }
    }
  }
}

Note that we're reusing the alias of the removed field for the subquery. That way, Views will think that the value returned from the subquery actually comes from the dummy field (which after all does not exist).

That's is. We're not getting a Cartesian join and both 'downloads' and 'listens' are counted correctly.


hook_node_insert() and drupal_goto conflicts with each other? I find some strange problem. I use hook_node_insert(). In order to create the other node after the user create the specific node! Then, I redirect the user to the other pages
But there are some error messages that i can't figure out!

the below code is my hook_node_insert()

function campaign_node_insert($node)
{
    global $user;
    global $base_url;

    if($node->type=="my_content_type")
    {

            $userid=$user->uid;

        /**

                My code is right here !

               **/

               drupal_goto('/user/'.$userid);

          }
}

My error Message is as belowed :

You can't use drupal_goto() in hook_node_insert() and other node_hooks too. The reason is that there is a queue of hooks that are executed on node insert and if you run drupal_goto() in some hook - all other hooks which goes after will not execute!

If you need redirect user after node insert to some url - implement hook_form_alter for node_form and add new submit callback $form['actions']['submit']['#submit'][] = 'my_module_submit_callback'. In this callback you will get $form_state with all $node fields and you can perform you redirect by specifying $form['#redirect'] = 'some/url'.


Double digit values for date I can not figure this out for the life of me, I am trying to have doubt digit values for  the day and month in my module using form api, I have tried this with the date api and still no luck,

my function looks like this

function set_dob_year_range($form_element) {
$form_element['year']['#options'] = drupal_map_assoc(range(1900, 2012));
return $form_element;
}

    $form['dob'] = array(
        '#type'  => 'date',
        '#title' => t('Date Of Birth'),
        '#default_value' => array(
            'month' => format_date(time(), 'custom', 'm'),
            'day' => format_date(time(), 'custom', 'd'),
            'year' => format_date(time(), 'custom', 'Y'),
        ),
        '#after_build' => array('set_dob_year_range'),
        '#required' => TRUE
    );

using in on the month should count the months values as 01 02 03 but instead its using 1 2 3, thing for the days it should be 01 02 03 instead its using 1 2 3.

Any help is greatly appreciated.

EDIT: The date formats are not passing through to the values for anyone that is confused.

You should try, i think it will work

format_date(time(), 'custom', 'm');
format_date(time(), 'custom', 'd');


Form returned by drupal_get_form() won't submit I am currently implementing an additional registration page on my drupal site, using drupal_get_form(), but I seem to be missing something cucial.

While the registration form is printed at the path I created, I can not submit the form - drupal will clear both the user and the email field and return an error claiming the form could not be submitted, because the fields were empty. They were not.

Do I need to hook up a custom validation handler? Something else?

My code so far:

function my_module_menu() {
  $items['customer/register'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_customer_registration'),
    'access callback' => TRUE,
  );

 return $items;
}

function my_module_customer_registration() {
  $form = drupal_get_form('user_register_form');
  return $form;
}

It's not working because the form builder function user_register_form() is expecting a couple of arguments, $form_id & $form_date, that you're not passing (see the drupal_build_form() docs to know more about what they're for).

If you want to provide a wrapper function around the user reg form, you can do something like this:

function my_module_customer_registration($form, &$form_state) {
  $form = user_register_form($form, $form_state);
  return $form;
}


Modal notification box on the screen of every authenticated user I want that every time I or any other admin (I have 2 more) post a new article each authenticated user should get a modal notification box on it's screen displaying a teaser of the Content Type I have posted.

I created an action 'Display a message to the user' for the trigger, 'TRIGGER: AFTER SAVING NEW CONTENT' and then tried saving new content and checked on a different account (which was already logged) for any message but nothing happened. Also, if this worked I'd like to show a modal box with the display settings (which I have in place already).

Drupal does not provide a way to send notifications to all site users by default. The action you are trying to use will only notify the user who triggers the action (you). Messaging can help you achieve what you want. You may also need the appbar module.


Creating a view block inside a fieldset using templates I am trying to create a new .tpl.php for some of my views.
I know how to create the file and display the elements the way I want, but only by changing the default views-view.tpl.php which would change the way all my views are displayed.

Supposedly I should be creating a new file by looking at Theme: Information and giving it one of the names available that would be something like: views-view--VIEW-NAME.tpl.php, but when I do this and leave the file in the theme folder in the views module and press "Rescan template files" it doesn't detect it.

Should I put the file in a different location?

FYI: What I am trying to do is place my views content inside a fieldset, something like this:

<fieldset class="fieldset collapsible form-wrapper"
 <legend>

       <?php print $header;?>

 </legend>

    <?php if ($rows): ?>

          <?php print $rows; ?>

    <?php elseif ($empty): ?>

            <?php print $empty; ?>

    <?php endif; ?>

    <?php if ($pager): ?>
        <?php print $pager; ?>
    <?php endif; ?>

As I said this is working, I am just trying to put it in a different .tpl.php file and apply it only to certain views. Also if there is an easy way of making the fieldset collapsible that would be useful, although not essential.

Put the template file in your themes directory not views theme directory. It will detect it there. I like to have a views directory inside the themes template directory to organize view template files. I mimic views naming convention for a directory structure so views-view-fields--brands--default.tpl.php and views-view-grid--brands--default.tpl.php would go in:

views/brands/default

It's a nice way to keep the files organized.


How do I get the title of an entity in hook_entity_presave? I am trying to get the title of an entity and I can do a dsm of the $entity, but when i do a dsm of $entity->values , nothing shows up.

If the entity is a node, you can do:

$entity->getTitle();

Or:

$entity->get('title')->value;

Here are a list of methods for the Entity object, and for the Node object.


Editing canonical links without a module, contained in $head? I've not been using Drupal for long (< 3 weeks) but have good knowledge of standard PHP, so I really don't know the 'Drupal' way of doing things yet.

What I'm trying to do is edit the canonical tag for a mobile site. The current path is realtive, however I need it to be absolute, and link to the desktop version of the site.

As far as I can tell the current implementation is not using any module to insert the canonical tag.

By looking at the source code of the rendered page the code appears to be contained in the $head variable which is in html.tpl.php as below

<head profile="<?php print $grddl_profile; ?>">
<?php print $head; ?>
<title><?php print $variables['field_meta_title']; ?></title>

I've come across a couple of pages like this one that mention things like template_process_html, drupal_get_html_head() and hook_html_head_alter() as relevant functions, but in that example the request is to remove the canonical tags, not to edit them.

I wouldn't mind using a module (providing it would allow me to change the link from www.mysite.com... to m.mysite.com...) but I would need to remove the current canonical tags which comes back to my orignial issue of not being able to find where it is.

You need the Meta Tags module.

After you activate it, go to /admin/config/search/metatags/config/global and, under advanced, you can change the default canonical link.

Look at the path patterns used for PathAuto and prefix them with the desired base url.


Manager for all Organic Groups I am working in a project that requires the use of organic groups and I was wondering is there is a way to setup a "global" drupal role that will give the users with that role access to all groups as managers.

Note: This managers might not be the user that created the group.

I received the same request once .. and what I need is this module og_role_override

  This module provides Core permissions to act as particular OG roles in
  specific group types.

  In other words, it creates permissions of the form 'Act as ROLE in
  GROUP-TYPE' for each role and each OG group type. Granting this
  permission to a Core role gives it the same permissions as that OG
  role, in all groups of that type.

  For example, you might want users with your 'site editor' role to be
  able to act as a 'board member' in all OG groups, without having to
  add them to each group, and without having to replicate all the OG
  permissions as Core permissions.

Hope it helps ..


Preprocessing function for specific view by name I'm using drupal 7.29 . I'm trying to write the preprocess function for a specific view named front-page. I have written the following functions in my template.php file:

function bartik_sub_preprocess_views_view__front_page(&$variables) {

  kpr($variables);
}

The function for preprocessing view works normally (without the __front_page at the end), but the above function isn't being called. I did create the corresponding .tpl.php (views-view--front-page.tpl.php) file which is used  but the function still isn't being called. I watched a couple of tutorials where the preprocessing function for a specific view was written like this and it worked,  any ideas why this isn't working?

you have to implement hook_theme function to make views aware of your custom preprocess theme function. You can find a tutorial on this here: http://www.appnovation.com/blog/theming-view-within-your-module


How to apply a patch for a Drupal module? I'm trying to us this patch http://qa.drupal.org/pifr/test/298933

Save the patch file to the root directory of feeds module (sites/all/modules/feeds) then apply the patch by using git bash.

So I typed:

git apply -v fcollection.patch

and it returns the following error:

  checking patch field_collection.module...
  error: field_collection.module: No such file directory

I hve a field_collection module installed in my site.

So what I did to experiment is to copy the patch to field_collection module folder and run the patch from that folder.

Then I got this error:

  error: patch_failed: field_collection.module:1142
  error: field_collection.module: Patch does not apply.

How can I apply the patch successfully?

This patch also exists at this #1063434 - the original issue for the test you reference above. One easy way to apply this patch would be to use the Drush Issue Queue commands.

Install with:

drush dl drush_iq

Then use it like this:

cd /path/to/drupal/root
drush am 1063434-#40

Presto!  Patch applied! Then drush-iq will work even better if you check out the module from git (i.e. drush dl field_collection --package-handler=git_drupalorg).

If you don't want to use drush-iq, try:

cd /path/to/drupal/root/sites/all/modules/field_collection
wget http://drupal.org/files/field_collection-feeds_integration-1063434-40.patch
patch -Np1 < field_collection-feeds_integration-1063434-40.patch


Default value for datetime field definition in content entity? I have the following datetime field definition for my content entity:

$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start date'))
  ->setDescription(t('Start date in GMT time.'))
  ->setSettings([
    'default_value' => DrupalDateTime::createFromTimestamp(time()),
  ])
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ])
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',
    'weight' => -3,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

As a result, when creating a new entity, I get the field display without default value set in a form. I also tried setDefaultValue method but with no luck.
What is the proper way to set the default values for the custom content entities?

You need to pass in a callback function that is evaluated when the entity is saved. If you evaluate the time value in YourEntity::baseFieldDefinitions, then the default value will fixed at whatever time the entity type was installed.

DrupalDateTime::createFromTimestamp can't serve as a callback because it expects you to pass a timestamp. The default value callback needs to take two arguments: the entity being saved and the field definition itself:

\Drupal\Core\Entity\FieldableEntityInterface $entity
\Drupal\Core\Field\FieldDefinitionInterface $definition

See the API docs: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldConfigInterface.php/function/FieldConfigInterface%3A%3AsetDefaultValueCallback/8.7.x

So you'll need to create a callback function, e.g.

use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;

// ...

function mymodule_get_current_datetime($entity, $definition) {
  $current_time = DrupalDateTime::createFromTimestamp(time());
  return $current_time->format(DateTimeItem::DATETIME_STORAGE_FORMAT);
}

And then pass that callback as a string.

$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start date'))
  ->setDescription(t('Start date in GMT time.'))
  ->setDefaultValueCallback('mymodule_get_current_datetime')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ])
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',
    'weight' => -3,
    'default_value' => DrupalDateTime::createFromTimestamp(time()),
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);


Entity Registration: Override built-in registration list with custom view I'm trying to override existing registration list (in Registration tab) with my custom built view, however if I set my View's path to "node/%/registrations", the tab "Manage registrations" is gone from entity tab.

What should I do?

In case someone is interested, I came up with a very nice and simple solution. I'm implementing hook_menu_alter() and overriding tab's "page callback" so that my custom view is called instead built-in registration list. (Note that solution below covers only tab for NODE entity!)

function MYMODULE_menu_alter(&$items){
    $items['node/%entity_object/registrations']['page callback'] = 'regstrations_view';
}

function regstrations_view(){
    $node = node_load(arg(1));
    return views_embed_view('my_registration_list_view','page', $node->nid);
}


Seven Sub-theme shows Branding and Nav instead of Local Tasks / Admin Menu [8] My client wants some basic changes to the Drupal admin pages (yay!) so I'm trying to create a sub-theme of the core seven theme.  I have my sub theme working and my css is being loaded, but the local admin menu normally shown in the header of the seven theme had been replaced by the branding block and main navigation from normal pages.

Here is my info.yml file :

name: My Admin
type: theme
description: A sub-theme of the seven admin theme.
core: 8.x
base theme: seven

libraries:
  - my_admin/global-styling

and libraries.yml :

global-styling:
  css:
    component:
      css/style.css: {}

I've tried copying seven.theme file to my sub-theme folder and renaming the functions with my theme name (which has an underscore), but no love there. Any ideas how to do this properly ?

I think you need to copy the regions as well.  Here's the YML from our custom Admin theme.

name: MY Admin Theme
type: theme
description: 'My administration theme'
core: 8.x
base theme: seven
libraries:
  - my_admin/global-styling

regions:
  header: 'Header'
  pre_content: 'Pre-content'
  breadcrumb: Breadcrumb
  highlighted: Highlighted
  help: Help
  content: Content
  page_top: 'Page top'
  page_bottom: 'Page bottom'
  sidebar_first: 'First sidebar'

ckeditor_stylesheets:
  - ../main_theme/css/style.css


How to install drush 8 properly? I'm trying to install drush 8 via composer:

composer global require drush/drush:dev-master (source)

but it gives me drush version 7.0.0 which is without D8 integration...
I'm using Linux Mint 17.

For Ubuntu

export PATH="$HOME/.composer/vendor/bin:$PATH"
source $HOME/.bashrc
composer global require drush/drush:8.x


Refreshless doesn't work I just tried to setup the RefreshLess module for my Drupal 8 site; after enabling it, I just see that some meta information is added to the DOM, but switching pages using links seems not to be effected in any way.

As written in the README file, I applied the patch to core.

How can I debug this?

PS: The refreshless.js file is not even loaded.

I was wondering the same and maybe this code is related:

function refreshless_page_attachments(array &$page) {
  $request = \Drupal::request();

  // Refreshless is only sensible when there is an actual session (otherwise the
  // entire page can be cached by the page_cache module, and be sent more
  // quickly than Refreshless could).
  // @see \Drupal\big_pipe\Render\Placeholder\BigPipeStrategy.
  $session_exists = \Drupal::service('session_configuration')->hasSession($request);

  $page['#cache']['contexts'][] = 'session.exists';
  if ($session_exists) {
    $page['#attached']['library'][] = 'refreshless/refreshless';
  }
}

It could be that for anonymous user the library is not loaded at all(check the comments in the function).

However I am not 100% sure.

Update: if you log in, you can see that refreshless.js is loaded.


How can I add class for div .form-item? I am using Drupal 7 and I need to change classes for ALL input textfield wrappers (class='form-item').
How can I do this without JS? please help

I could change form's, form-submit's and submit-wrapper's (form-actions) classes with this code in template.php:

    function mytheme_form_alter(&$form, &$form_state, $form_id) {
        $form['actions']['submit']['#attributes'] = array('class' => array('my_class', 'my_own_class'));
    }

but I cant do anything with textfields and their wrappers

You can override the output of theme_form_element() function in your theme's template.php file. Just copy the function from includes/form.inc file and put it in template.php as MYTHEME_form_element(), and you can now change classes for only text fields with something like this before initializing $output variable :

if($element['#type'] == 'textfield'){
  // Add a class specific to textfields
  $attributes['class'][] = 'custom-textfield-class';
}

This code is not tested, but it should work. You should clear drupal cache after implementing the function in template.php.


Theming of Entity registration form I'm using entity registration module on a drupal 7 for events. I managed to enable the registration but I can't find out how to style the registration form.

I tried to modify the form via css but I would prefer have a better control over it, in a template page for example.
I'm quite new to drupal so any help would be much appreciated.

I use Display Suite to arrange elements and css to style elements. You can create your own template layout in display suite if you need it.


Cannot install Search API pages module, due to database errors? Trying to install search_api_page created repeated database errors about the search_api_page table not being available.

Is it a known problem known to happen?

I have had a similar issue.  I resolved it by installing search api on a fresh drupal install and exporting the databases then importing to the original database.  I would not recommend doing this first however.

First you should uncheck search api module in your modules list, then click the uninstall tab and uninstall it.  Grab a new copy of the search api module to make sure you didn't have corrupt files and install it again.  If this doesn't work, then you may want to try what I had to do.


Is there a module/Drush command for updating multiple field settings at once? Just for convenience I wish change all required fields to optional at once.

Is there module or even better, a Drush command supporting module to do so?

I don't think there's a module or anything to do this, as it's quite a specific use case.

However, you could try something like the following in either a custom module's update/install hook.

Note I've not tested this, but you'll have to tweak it for your use case anyway.

$options = array(
  'entity_type' => 'node'
);
// Get all field instances that are on nodes
$fields = field_read_instances($options)

// Loop through the fields...
foreach ($fields as $field => $data) {
  // ...and prune the array to remove any non-required fields
  if ($data['required'] == 0) {
    unset($fields[$field]);
  }
  // $fields now only contains data for required fields attached to nodes
}

// Loop through the remaining fields
foreach ($fields as $field) {
  $instance = array(
    // Provide the default information that field_update_instance requires
    'entity_type' => $field['entity_type'],
    'bundle' => $field['bundle'],
    'field_name' => $field['field_name'],
    // Make your required changes
    'required' => 0
  );

  // Take the data in the $instance array and pass it through to field_update_instance.
  field_update_instance($instance);
}

You can filter down your selection of fields by passing different options through to field_read_instances() (e.g. if you only want fields attached to the Basic Page content type, the $options array would look like this:

$options = array(
  'entity_type' => 'node',
  'bundle' => 'page'
);

As a sidenote, field_update_instance clears the field cache at the end of every call, so if you have a lot of fields, then this might take a while .

Documentation:

field_read_instances();
field_update_instance();


Download attached files in a Zip Im doing a website for photos. The photographer uploads all the images and drupal generates a thumbnail and a resized image.

What i'm trying to do is to put a link , so the final user can download all the original files in a zip files.

Can you guys help me out?

Yes, there's a module for that (of course ;) )

Download module:

  This module can compress any files attached to a node and provides a download link. To use this module you have to extract the PclZip library in /sites/all/libraries/pclzip which can be downloaded here: http://www.phpconcept.net/pclzip/pclzip-downloads.


List all available items with Apache Solr if the search keyword is empty I have created 2 search pages with Apache Solr module one with content type filter and another for search in taxonomy terms. By default if the keyword string is empty the search pages don't return any results. How can I list all available items with certain content type or with taxonomy term in this case? Thanks

Thanks Letharion, to answer your question I have found this option in the Advanced options region for the search pages. Here is how to get there:

admin/config/search/apachesolr/search-pages

Create a new search page for Solr search with content type filter or enable one for taxonomy/term/%

Select "Show enabled facets' blocks in their configured regions and first page of all available results" under the Advanced options for this page


Install a module that creates a content type with fileds via YAML I am new to drupal 8, I have been using drupal 7 for quite some time and I used to write the code that creates content types and fields in hook_install / hook_update.

Now I am creating a module that creates a new content type with a few fields. I tried to do it with YAML config files but it does not create my fields.
The code I have so far:

/module/custom/mymodule/mymodule.info.yml

name: My Module
description: Applies customizations for my website.
package: Custom

type: module
core: 8.x

dependencies:
    - breakpoint # toolbar dependency
    - image
    - link
    - taxonomy
    - toolbar

/module/custom/mymodule/config/install/node.type.article.yml

type: article
name: Article
description: 'Use articles for time-sensitive content like news, press releases or blog posts.'
help: ''
has_title: true
title_label: Title

settings:
    node:
        options:
            status: true
            promote: true
            sticky: false
            revision: true
        preview: true
        submitted: true

status: true
langcode: en

new_revision: true
preview_mode: 1
display_submitted: true

dependencies: {  }

And one of my fields:
/module/custom/mymodule/config/install/field.field.node.article.image.yml

langcode: en
status: true
dependencies:
  config:
    - node.type.article
  module:
    - image
id: node.article.image
field_name: image
entity_type: node
bundle: mymodule
label: Image
description: 'A representative image for the current article.'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  file_directory: '[date:custom:Y]-[date:custom:m]'
  file_extensions: png
  max_filesize: ''
  max_resolution: ''
  min_resolution: ''
  alt_field: true
  alt_field_required: true
  title_field: true
  title_field_required: true
  handler: 'default:file'
  handler_settings: {  }
field_type: image

What am I missing? Why don't the fields get created at install time?

For a node type + fields + formatter/widget settings, you need:

The node type, you already have that
The field.storage.node.* config entities for your fields. If they are shared with other node types/modules then it gets a bit complicated. You can't define the same default config as another module. You could make it optional config, but then all your config needs to be optional
The fields themself, like the example the one that you already have.
The core.entity_form_display.node.article.* config entities for the different form displays, for node, probably just default.
The core.entity_view_display.node.article.* config entities for all the view modes you want. default, teaser, ...

Also, note that tis is install configuration. It will only get created when you install the module. There is no standard mechanism to update configuration when you change the files and the module is already installed. There are modules for that, like config_update, features possibly also contains that.

If this is a custom module that you just need on a single site and want to use it for dev -> staging -> production (or whatever you call your environments) deployments, it's easier to use the global config folder for that. Create your config, export it, commit it, and then import again. That also does updates and deletions.


Is there a good way to determine which database table are associated with each module? I have been installing and uninstalling modules on my site and I am starting to run into problems involving re installing previously disabled modules.  The install script is finding old database tables from previous module installations and is refusing to install.  For some of these modules, there is no 'uninstall' option.  Is there a good way to determine which database table are associated with each module?  I'm looking for a method of discovery or an online list.

I am unaware of an automated way to check for orphaned tables.  Before the Schema API was rolled out in Drupal 7, people would use the Schema module.  This had a hook_requirements() in it that would do this check and list orphaned tables on the status report.

You could make your own automated test.  The procedure would be something like

Do a SHOW TABLES query to get the list of all of the tables.
Query the {system} table to get a list of all modules, both enabled and disabled
Loop through the modules, and then use drupal_get_schema_unprocessed() to get the module's schema.  From this, build up a list of tables.
Do an array difference between the list you just built and the list from SHOW TABLES.  This should be all tables that aren't owned by a module that is enabled or disabled.

Something like this:

$alltables = db_query('SHOW TABLES')->fetchCol();

$modules = db_query("SELECT name FROM {system} WHERE type = 'module'")->fetchCol();

$accountedfor = array();

foreach ($modules as $module) {
  $schema = drupal_get_schema_unprocessed($module);

  if (!empty($schema)) {
    $accountedfor = array_merge($accountedfor, array_keys($schema));
  }
}

// tables not accounted for by hook_schema() from enabled and disabled modules

$orphaned = array_diff($alltables, $accountedfor);

This ignore the intricacies of table prefixes, multiple catalogs, and sharing catalogs between applications.

Use at your own risk.


confirm email form type? There is a confirm password form type.  I don't suppose there is a confirm email address form type available?  Possibly as a contributed module?

You can try LoginToboggan

You will get a screen like this in example.com/admin/config/system/logintoboggan


Building an advanced multicriteria search I'm kinda new to Drupal and I would like some advises.

I have a Drupal website, with a few nodes (1000 - 5000) of a particular content type, let's say a "House".

This "House" content type has a few properties (20) like price, location, number of rooms, etc.

In order to allow my end users to find those nodes, I've build an advanced search with the Finder module.

However, this module is no longer maintained and it is not really appropriate to search through many nodes.

  Finder does not work like a typical search module, it does not base
  it's functionality on search indexes, and therefore is not an
  efficient choice for searching body content, though it can technically
  do that. It is more suitable for filtering on short field values.

What are the best options to build an advanced multi criteria search with Drupal 7 ?
Do I need to do it by hand ? What are the modules out there that could help achieving that ?

Is Facet API the way to go ?

I think facets are a great way to do advanced searching.
Facet API is a great module that is flexible.

You can use it with core drupal search using Faceted Navigation for Search or Search API, which can use the drupal database to search.

However, due to the queries that are run in the calculation of facet data, there are performance implications of using faceted search with drupal SQL based searching.

If you have a lot of content, are using a lot of different facets, or have high traffic, I would definitely recommend using a better search engine.

Apache solr, is great and is pretty easy to get set up these days.

You main options are the Apache Solr Search Integration module and the Search API module, in conjunction with the Search API Solr search module.

Both those integrate with the facet API module.

Solr is not really shared host friendly though. Generally you will have to find a host that will provide apache solr hosting, or use a VPS or dedicated server that allows you to install solr yourself.


Could not determine database connection parameters. Pass --db-url option when site-install i am writing drush script to install drupal site

 $build_make_file = ($build_src = drush_get_option('build-src', FALSE)) ? $build_src : '../builds/build-drupal-core.make ';
    $dest .= ($build_dest = drush_get_option('build-dest', FALSE)) ? $build_dest : 'test';
    $options = array();
    $options['debug'] = drush_get_option('debug', FALSE);
    $options['no-core'] = drush_get_option('no-core', FALSE);
    ($contr_dest = drush_get_option('contrib-destination', FALSE)) ? $options['contrib-destination'] = $contr_dest : '' ;
    $status = drush_invoke_process('@none', 'make', array($build_make_file, $dest), $options);
    drush_print('Site Download '.(($status) ? "SUCCESS" : "FAILURE" ));

    // go to install directory before we do anything else
    drush_op('chdir', $dest);

    $dbHost="localhost";
    $dbName="drupal_test_db";
    $dbUser="test_user";
    $dbPassword="xxxxxx";
    $dbPort ="3306";
    $status = drush_invoke_process('@self',
                                   'si',
                                   array(
                                          'db-url' => 'mysql://'.$dbUser.':'.$dbPassword.'@'.$dbHost.':' . $dbPort . '/'.$dbName,
                                          'account-pass' => $AdminPassword,
                                      )
                                  );
    drush_print('Site Install - ' . (($status) ? 'SUCCESS' : 'FAILURE'));

The site download part works where it downloads the make file. The second part running 'site-install' returns an error:

Could not determine database connection parameters. Pass --db-url option

How to call 'site-install' command from the drush script correctly? I would appreciate much of your help. Thank you

It appears, i passed one too few parameters to 'drush_invoke_process'. The documentation shows:

function drush_invoke_process($site_alias_record, $command_name, $commandline_args = array(), $commandline_options = array(),....)

In my case, I was not passing in the 'commandline_args' making the 'commandline_options' become 'commandline_args' instead of options including 'db-url'

Here, is the correct one:

$status = drush_invoke_process('@self', 'si', array('standard'), array(
                                                        'db-url' => 'mysql://'.$dbUser.':'.$dbPassword.'@'.$dbHost.':' . $dbPort . '/'.$dbName,
                                                        'account-pass' => $AdminPassword,
                                                   )
                              );

I hope this helps anyone


How do I disable the cache clear on comment form submission? Unless I'm reading this incorrectly, it looks as if the last thing comment_form_submit does is clear the cache. All of it. This is done so anonymous users see the comment they posted.

I have a site that does, at times, receives high comment volume and the site does not allow anonymous users to post comments, so this behavior is suboptimal for me to say the least.

What's the Drupal way to override/kill the call to cache_clear_all() when comments are submitted? Can I do this in a module?

Should be reasonably straight forward with a form alter (mileage may vary slightly here but this is the general idea):

function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $key = array_search('comment_form_submit', $form['#submit']);
  if ($key !== FALSE) {
    $form['#submit'][$key] = 'MYMODULE_comment_form_submit';
  }
}

function MYMODULE_comment_form_submit($form, &$form_state) {
  // Copy code from comment_form() here, remove what you don't need.
}


Add custom tag in RSS XML header Drupal 7 I'm using Views to generate a custom RSS feed. I need to add an extra tag in the header. I tried different setting in Header section of the Feed Display, but nothing gets displayed in the feed.

Could anyone explain what's the best way to do it

Maybe it's because I don't know the views module well enough but I could not get views to do this at all. Instead I created a simple module that outputs an RSS feed. Use:

header("Content-type: text/xml");
print '<rss version="2.0">';

to have PHP output the correct headers.

EDIT: not sure it makes sense to just post the code but I can describe it:

1) The code below creates the page where your XML feed will live (should be in *.module file):

function xml_sender_menu() {
   $items['feed'] = array(
     'title' => 'RSS Feed',
     'page callback' => 'rss_feed',
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );

     return $items;
}

2) Then in the same file create a function called "rss_feed()" (this name should be the same as the 'page callback' => 'rss_feed', in the above array) which will contain the code that produces the actual website. The function doesn't need to return anything.

3) http://cyber.law.harvard.edu/rss/rss.html contains a good readable description of the RSS specification, use Drupal API/PHP to output the data you want into the correct fields. For example I used the node's title to fill in the <title> field in RSS by doing this:

$sourcetitle = htmlspecialchars($node->title);
    print '<title>'.$sourcetitle.'</title>';

4) At the end output all the closing tags </channel> & </rss>

I don't know what data you are trying to fill your RSS feed with, so can't really be any more specific. Finally, copy/paste the output into an RSS validator to make sure you are not missing anything.

** Something I just realized: if you are adding other fields that aren't in the RSS specification, it's no longer an RSS feed. Instead you are just getting a plain old custom XML feed, don't know if that makes a difference to you.

HTH


User accounts for customers How would I go about having a feature for customers to create their own accounts on my Drupal? Will I need PHPMyAdmin and some SQL?

This is a setting that's built into the core of Drupal. On D7/D8 the Who can register accounts? (Public registrations in D6) setting adjusts who can create accounts on your Drupal installation.

Administrators only
Visitors
Visitors, but administrator approval is required

The settings form can be found under /admin/config/people/accounts (/admin/user/settings in D6).


Search result is empty When I do a search, I got an empty result even though the result shouldn't be null.
I even get a null result if I don't filter anything. However fulltext search works, only facets corresponding to a field seems to not work.

I copied a production database to a test server. Everything works fine on production, but I can make the test copy works.

I've seen there is some issue with facets if the user doesn't have the permission to create temporary table. I checked that, and I think I have the permission.

Any idea ? (I use drupal commerce)

The problem was due to different behavior between mysql 5.6 and 5.7. I thought I had the same environment between production and test but I was wrong. I use a docker image for mysql but didn't specify a version so I ended up with two different versions on the two systems, even though the provisioning looked the same.


Can I add custom fields to a single page? Sorry for another "In Wordpress..." question but here we go...

In Wordpress, I can use ACF to add custom fields to a single page. This is done either in code or in the GUI by basically doing something like (pseudocode),

if id = 123
  add_field "Phone Number"
end

This is especially useful on homepages or landing pages where the layout is unique and I want to provide structured data entry without needing to create a custom type that is only used once. In Drupal, I dont see a way to dynamically add fields to an arbitrary piece of content. Is this possible? How?

Wordpress custom fields:

If you are using Drupal 8, you can create a block type and add fields to it. Then create a block of your block type and on visibility rules you can assign it to a specific page.

Video Tutorial.

If you're using Drupal 7, you can do the same, but you'll need the Bean module


Views charts pager doesn't match parent I have a view with a table that has a pager to show 5 items at a time:

Items to display:Display a specified number of items | 5 items

In another display I have a chart that is attached to the table. How can I set the view so that the chart display the same content that is in the table? There is the Inherit pager option that I set to Yes but the chart always show the firts 5 items and not the 5 items showed in the table.

You can see in the image below that the chart is in fact limited to 5 (as the table) but the dates (x-axis) don't match.

Am I missing something here? Or is this a limitation?

Maybe there is another solution for this problem but after trying many things I noticed that one solution is to disable the sorting of the "Run Date and Time" field. This way, the table is always sorted in the same way for that field but the pager is respected.


multi price in drupal commerce in drupal 7 I have a shop created with drupal commerece modules,I enabled 2 currency in my shop , but only show one of them, I want to show price in 2 currency

something like this
price :  10$  / 20 IRR
I use multi currency module to achieve this job, but  I my problem is in payment  phase,
I use multi currency module to achieve this job,in multicurrency  module's setting I don't want  use  synchronize method, if you want have two field in my product , one form $ and another for IRR, I did this job by this method

first enable IRR currency in
 admin/commerce/config/currency
 then in
 admin/commerce/config/currency/handling
under Enable dedicated price fields for Product check Iranian Rial
 by doing this  another field added you my product ( ** Price for IRR** ), this is good , after this I enable  *currency selector * block ,in checking out process by switching the currency I don't see any change in current currency of billing and cart. :(
why changing currency not changing cart currency?

Commerce Multicurrency module enhances some of the multi-currency capabilities of Drupal Commerce. You can show two or more currency for a product and check this video tutorial and this one

  Current features:

  UI for fine granular definition of exchange rates.
  (Every currency combination can be defined separately if needed)
  Synchronization of currency exchange rates directly from the European Central Bank (ECB).
  UI to specify which rates shall be synchronized and which are handled manually.
  Generation of currency specific price fields inclusive generation of rule-set to handle them.
  hooks for easy integration of custom currency exchange rate sources.

this tutorial will help you without sync http://mcaleaa.wordpress.com/2012/04/08/drupal-commerce-multicurrency-recipe/


Move uploaded content automatically from one node to another Is it possible post images/text on a different page other than the one being uploaded?

I have an insert page where users can add images/text but I want whatever they post to go on another page automatically ('things' page) sorted by the most recent first. I only want to keep the 'insert' page as an 'insert' and without content!

Content in Drupal is organized in "nodes":

  A node is any piece of individual content, such as a page, poll, article, forum topic, or a blog entry. Comments are not stored as nodes but are always connected to one.

So you'll always have a "page" or whatever your content type is named, to store and edit the content. But you don't need to show these pages necessarily to the visitors or users of that site.

You should take a look into Views module, which will enable you to create (another sort of) "pages" that automatically collect content from "nodes" according to the rules and filters that you have definded for it.


How to show another user the goals I completed? I have a view that shows the goals (created using the Goals module) I've completed. For this I use the view that comes with the Goals module (and which only shows the Goals completed by the current user).

But I'd like that other users could see that view too whenever other users browse my account. So that another user can see which goals I completed (instead of showing the goals completed by that other user).

So I'm looking for help about:

placing the view.
making it visible to other users whenever they browse my profile.

Here is an export of a view, which is an improved version of the view that is included with the Goals module (disclosure: I'm its maintainer):

$view = new view();
$view->name = 'goals_completed_by_a_user';
$view->description = 'A block showing goals completed by a user.';
$view->tag = 'Goals';
$view->base_table = 'goals';
$view->human_name = 'Goals Completed by User';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Your completed goals';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'grid';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Goal: Goal - completed by users */
$handler->display->display_options['relationships']['goals_completed_goals']['id'] = 'goals_completed_goals';
$handler->display->display_options['relationships']['goals_completed_goals']['table'] = 'goals';
$handler->display->display_options['relationships']['goals_completed_goals']['field'] = 'goals_completed_goals';
/* Field: Goal: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_goal';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['exclude'] = TRUE;
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;
/* Field: Goal: Goal Image */
$handler->display->display_options['fields']['goal_img']['id'] = 'goal_img';
$handler->display->display_options['fields']['goal_img']['table'] = 'field_data_goal_img';
$handler->display->display_options['fields']['goal_img']['field'] = 'goal_img';
$handler->display->display_options['fields']['goal_img']['label'] = '';
$handler->display->display_options['fields']['goal_img']['exclude'] = TRUE;
$handler->display->display_options['fields']['goal_img']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['goal_img']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['goal_img']['settings'] = array(
  'image_style' => 'goal_image',
  'image_link' => '',
);
/* Field: Goal: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'goals';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['text'] = '[title][goal_img]
';
$handler->display->display_options['fields']['title']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['path'] = '[url]';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Sort criterion: Goal - completed by users: Created */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'goals_completed_goals';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['relationship'] = 'goals_completed_goals';
/* Contextual filter: Goal - completed by users: User */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'goals_completed_goals';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: My goals */
$handler = $view->new_display('block', 'My goals', 'block');
$handler->display->display_options['display_description'] = 'Goals completed by the current user';
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;

/* Display: User's Goals */
$handler = $view->new_display('block', 'User\'s Goals', 'block_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Goals completed user';
$handler->display->display_options['display_description'] = 'Goals completed by a selected user';
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'goal_img' => 'goal_img',
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'goal_img' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Goal: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_goal';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['exclude'] = TRUE;
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;
/* Field: Goal: Goal Image */
$handler->display->display_options['fields']['goal_img']['id'] = 'goal_img';
$handler->display->display_options['fields']['goal_img']['table'] = 'field_data_goal_img';
$handler->display->display_options['fields']['goal_img']['field'] = 'goal_img';
$handler->display->display_options['fields']['goal_img']['label'] = '';
$handler->display->display_options['fields']['goal_img']['exclude'] = TRUE;
$handler->display->display_options['fields']['goal_img']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['goal_img']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['goal_img']['settings'] = array(
  'image_style' => 'goal_image',
  'image_link' => '',
);
/* Field: Goal: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'goals';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['text'] = '[title][goal_img]
';
$handler->display->display_options['fields']['title']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['path'] = '[url]';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Goal - completed by users: User */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'goals_completed_goals';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['uid']['default_argument_options']['index'] = '1';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

In this view I've added an extra block named "User's Goals". This extra block has a contextual filter which I configured like so:

When the filter value is not available: Provide a default value with Type = "Provide raw value from URL" and Path component = "2" (this is what differs from the Views block delivered with the Goals module).
In the block settings I've adapted the block visibility to only show this block on pages with a path that matches user/* ( i.e. when browsing a user's account, as in your question). And of course I've then enabled this extra block also to display it in an appropriate theme region.

Note: I've also extended the list of fields shown in the block, by also adding the Goal URL (excluded from display) and Goal title, though that is not really relevant to answer the question here.


Rewrite the image markup from specific image field In a Drupal 7 site, I have an image field that allows unlimited images, called field_gallery_images. I built a template file for this field to create a custom image slider. I want to rewrite the HTML markup for the image to add a lazy-load component. So, instead of:

I want:

Right now, the images are being run through theme_image() and so by the time it gets to the template, the markup is all set. I only want to alter the markup for this one field. I tried theme_preprocess_image(), but that altered all images.

I assume that you are using Drupal 7.

Short Answer

Implements template_preprocess_field() and overrides theme_image().

/**
 * Implements template_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];

  if ($element['#field_name'] === 'field_image') {
    foreach (element_children($element) as $key) {
      $item = &$element[$key]['#item'];

      $src = file_create_url($item['uri']);
      unset($item['uri']);
      $item['attributes']['data-lazy'] = $src;
      $item['attributes']['class'] = array('lazyload');

      $element['#items'][$key] = $item;
      $variables['items'][$key]['#item'] = $item;
    }
  }
}

/**
 * Overrides theme_image().
 */
function mytheme_image($variables) {
  $attributes = $variables['attributes'];

  if (!empty($variables['path']) || !isset($attributes['data-lazy')) {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

Long Answer

By implementing template_preprocess_field(), you can alter the theme variables and also the theme function for a field.

Example code:

/**
 * Implements template_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];

  if ($element['#field_name'] === 'field_image') {
    foreach (element_children($element) as $key) {
      $item = &$element[$key]['#item'];

      $src = file_create_url($item['uri']);
      unset($item['uri']);
      $item['attributes']['data-lazy'] = $src;
      $item['attributes']['class'] = array('lazyload');

      $element['#items'][$key] = $item;
      $variables['items'][$key]['#item'] = $item;
    }
  }
}

Remember to change field_image to the field name you defined.

It is the structure of $variables:

$variables['items'][0]['#item'] is a typical usage of theme function in render array. The code above has done a couple of things:

unset uri, which is used to format the attribute src in theme_image()
construct image path and assign it to the attribute data-lazy
add lazyload to class
synchronise the item array to different location of $variable

The last point is a bit weird, but there are 3 different location always store the same item array. They are

$variables['element'][0]['#item']
$variables['element']['#items'][0]
$variables['items'][0]['#item']

Theoretically, $variables['items'][0]['#item'] is the only one be used in theme function, But, in my opinion, it is better to change them at the same time for preventing any potential issue in future. (Maybe someone can provide more suggestion here?)

The last but not the least, you have to override the theme_image(). It is a global change but won't affect too much.

/**
 * Overrides theme_image().
 */
function mytheme_image($variables) {
  $attributes = $variables['attributes'];

  if (!empty($variables['path']) || !isset($attributes['data-lazy')) {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}


How can I log variables to a txt file? In Drupal 7 I use devel's  drupal_debug() or its alias dd() to log a variable to a drupal_debug.txt in the site's temp directory.

In the Drupal 8 version of devel this function has disappeared. It seems to be replaced by DevelDumperManagerInterface
But it is not clear to me how it used.

How can I log variables to a txt file in Drupal 8?

The DevelDumperManagerInterface interface is implemented by DevelDumperManager. This class is in turn used as a service, 'devel.dumper'.

One way to use this function would be the following:

$ddumper = \Drupal::service('devel.dumper');
$ddumper->debug($variable_name);

Good luck!


Disabling language prefix for route in module How can I disable the automatic redirect to the language prefixed URL for a URL defined in a routing.yml in my module?
I'm developing a custom sitemap.xml module, because the Simple Sitemap XML module does not have the options I need. I've got it just about working, except the URL /sitemap.xml 301 automatically redirects to the URL /lang/sitemap.xml - and it really shouldn't. How can I disable this redirect?

Yes, has to be redirect.module, core doesn't do that. See https://www.drupal.org/node/2854462#comment-12047347, just add the '_disable_route_normalizer' flag to your route and you should be fine.

module_sitemap.routing.yml:

module_sitemap.sitemap:
  path: '/sitemap.xml'
  defaults:
    _controller: '\Drupal\module_sitemap\Controller\SitemapController::view'
    _title: 'View Site Map'
    _disable_route_normalizer: 'TRUE'


How to add og:video tag at my site? I want to share my video site on Facebook.
Facebook detect only thumbnail of video.
I see France24.com add og:video on the source of site and show direct video on facebook.
I use auto_opengraph but this module can't generate og:video
How  can i do?

new version of XML Sitemap module helped me.

  The XML sitemap module creates a sitemap that conforms to the
  sitemaps.org specification. This helps search engines to more
  intelligently crawl a website and keep their results up to date. The
  sitemap created by the module can be automatically submitted to Ask,
  Google, Bing (formerly Windows Live Search), and Yahoo! search
  engines. The module also comes with several submodules that can add
  sitemap links for content, menu items, taxonomy terms, and user
  profiles.


Replace date by text in date_popup default value (or in-field label) I am desperately trying to display a date_popup field in my form with a text eg("please select date") as default value and not a date. Can someone help?
Thanks a lot.

Try using the placeholder html5 attribute by removing the #default_value from the array.

So, take out....

'#default_value' => $date,

and replace with

'#attributes' => array('placeholder' => t('Please select date')),

or, as you already have attribute, add it to that


Why is hook_schema() called twice? I'm working with entities and, in trying to troubleshoot another issue, I noticed that hook_schema() is called twice each time the module is installed. This happened even with a bare bones test module containing only a hook_schema() definition. My questions are:

Is it normal for hook_schema() to be called twice on module installation?
Why would hook_schema() be called twice on installation?

It seems to be normal. Looking at the hook_schema documentation, you see that it is invoked in drupal_get_complete_schema() in includes/bootstrap.inc and in drupal_get_schema_unprocessed() in includes/common.inc. The main difference is that the latter does not invoke hook_schema_alter() after the hook_schema is invoked. The first of those functions seems to be called on practically every page load. The second function is called from drupal_install_schema() during the module install process.

Concluding, looking at the code it seems to me that:

It is normal
It happens because during installation, Drupal needs the un-altered schema definitions


How to render random image on every refresh page I have got a content type and an image field.

How can I render the field with a random image at every page refresh.

Previously I write a small module for this purpose, named Many to one image

This is a small display formatter, Download and install then go to manage display and select it.


How to create different Views pages for different taxonomy vocabularies? I have two vocabularies that require two different taxonomy view pages. For example, I have vertebrates with terms fish, cats and snakes and invertebrates with sea cucumbers, spiders and snails. I would like to create a different view for each. Can I configure Path Auto to create separate URLs passing the vocabulary term ID as an argument? If so then how do I change the link of the Term found in the Term Reference field of the node view to point to these pages? I'm thinking about installing the Taxonomy Views Integrator but would rather leave out an extra module if it's just a matter of configuring a Views argument correctly.

The Taxonomy Views Switcher does the trick. It does something clever. If the default view page path is 'taxonomy/term/%' it will walk through the paths of the. If the vid of the term is 3 it will associate the term with the view that has vid/3 in the path and will when taxonomy/term/% is called pass it -- the second view -- the argument of the term ID. Since this is a separate view it can have any field, sort, filter or display plugin.

Now I need to trigger contexts based on views that are triggered.


Math Field doesnt recalculate when fields are populated I have 2 Select list(Integer) fields and I am using Math Field to get the sum of the two fields. But when I populate the first value the field is calculated and when I populate the second field it does not recalculate. Help me please.

The (fairly new) Math Field module for D7 is a not commonly known/used alternative to Computed Field).

However, there are still a few other (known) issues with it, as mentioned also on its project page:

The cTools math expression library causes an error when using function that take more than one parameter. This effects pow(), min(), max() (#1958538: Improve math expression engine).
Math Field does not yet support multivalue options fields (checkboxes, or multiselect) (#2483453: Add aggregate functions for multivalue fields).

However, if you're trying to use this module to handle multivalue fields, then that would explain why you can't get that to work (as per the issue mentioned before: multi value fields are not yet supported).


How to properly inject services into other services I'm trying to figure out how to inject Drupal services into a custom service class. The class in question is my MenuService which builds an associative array of menu items which will be encoded to json and sent as a response for my custom REST endpoint ( /api/menu/{menu_name} ).

As a part of that, I need three classes:

\Drupal\Core\Path\AliasManager

\Drupal\Core\Menu\MenuTreeParameters

\Drupal\Core\Menu\MenuLinkTree

Any help on tracking down the MenuTreeParameters service would be helpful. I don't see it on this list. If it's not a defined service, can it be injected?

Note: Made some edits as I answered most of my own question

Alright, I think I figured it out. It should look something like this:

I couldn't find the service name anywhere for MenuTreeParameters so it's omitted in the examples for now.

I setup my menu service in rest_api.services.yml

services:
  rest_api.menu_service:
    class: Drupal\rest_api\Services\MenuService
    arguments: ['@path.alias_manager', '@menu.link_tree']

And created my service:

namespace Drupal\rest_api\Services;

use \Drupal\Core\Menu\MenuLinkTree;
use \Drupal\Core\Path\AliasManager;
use \Drupal\Core\Menu\MenuTreeParameters;

class MenuService {

  protected $aliasManager;

  public function __construct(AliasManager $aliasManager, MenuLinkTree $menuTree) {
    $this->aliasManager = $aliasManager;
    $this->menuTree = $menuTree;
    $this->items = array();
  }


How to call php snippet which is save as basic page? I have a php code as below:

$("#tbMGroup tr.odd").click(function() {
              $("#m_id").val($(this).attr("m_id"));
              $("#form1").first().attr("action", "search.php");
              $("#form1").submit();
            });

but,
I have add search.php to a basic page. now, these code need to call search.php when mouse click, I don't know how to call search.php snippet, because search.php now is not a independent file, it is a snippet.
Thanks for your help...

I think you should use hook_menu to define the path the drupal way and rewrite your form using drupal FAPI. This gives you a clean system.