How do I create a path alias? I'm trying to create a path alias for a node type, where the first part of the alias is the url path of the organic group. I tried this

[node:og-group-ref:1:url]/[node:content-type]/[node:title]

but it didn't work. When I tried this

[node:og-group-ref]/[node:content-type]/[node:title]

it did create an alias, but [node:og-group-ref] refered to the node title, not the path alias of the node.

From here - https://www.drupal.org/node/2302879 - saw that there are tokens for [node:og-group-ref:url:relative], but thats not a valid token on my site. I am using Organic groups 7.x-2.7.

Is this a possible alias?

I'm not sure what the real answer is to this issue, but I found a workaround: I created my own token which provided me this alias

/**
 * Implements hook_token_info().
 */
function example_tokens_token_info() {
  $types['og_path_alias'] = array(
    'name' => t('The OG Path Alias'),
    'description' => t('Tokens for the OG path alias'),
  );
  $og_path_alias['path_alias'] = array(
    'name' => t('The OG Path Alias'),
     'description' => t('The OG path alias'),
  );
  return array(
    'types' => $types,
    'tokens' => array(
      'og_path_alias' => $og_path_alias,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function example_tokens_tokens($type, $tokens, array $data = array(), array $options =     array()) {
  $replacements = array();

  if($type === 'og_path_alias') {
    $node = $data['node'];
    foreach($tokens as $name=>$original) {
      switch($name) {
      case 'path_alias':
      $node_wrapper = entity_metadata_wrapper('node', $node);
      if($node_wrapper->__isset('og_group_ref')) {
        $chapters = $node_wrapper->og_group_ref->value();
        foreach($chapters as $chapter) {
          $new_alias = drupal_get_path_alias('node/' . $chapter->nid);
        }
      }
      $replacements[$original] = $new_alias;
      break;
  }
}
}

return $replacements;
}


How to optimize D7 Views? I would like to optimize Views as they cause most of my performance bottlenecks.

The MySQL slowlog shows not only Views related query times > 5s but, what is more scary, selects with over 10 LEFT JOINs. I have already manually removed some columns from views. It was over 14 LEFT JOINs before...

Are there any solutions (without writing custom module queries) to eliminate or limit LEFT JOINs in Views select queries ?

I found there is the Shadow contrib module available. Is it ready for production website?

I would use that contrib module. Beta releases are generally darn tight and seeing that it is beta3 would lend to the idea that it will soon be out of beta. (Of course it may never come out so that doesn't say much.) Also, the maintainer group seems to be high quality which gives me even more confidence.

To answer your other question I do not thing there is anything else you can do besides write something yourself. I was looking around and saw some initial phases of work being done on this but nothing as far along as that project you linked. I imagine this is something they will work on for D8. Your find is surprising. The only other place I might check if I were is IRC just to make sure that there isn't some other optimization technique or module out there that isn't Views specific but that will help. (Probably not, but worth a try.)


Domain Name language negotiation and mobile prefix m I have a question regarding the domain name language negotiation.

I have 3 languages and the following domains:

de.domain.com
en.domain.com
fr.domain.com

When I set this as the domains for each language and use the domain name language negotiation everything works as expected.

My problem is that I have an adaptive mobile theme and I have to use following domains for that:

m.de.domain.com
m.en.domain.com
m.fr.domain.com

How can I achieve that those urls point to the correct language (de, en, fr). Now, all point to the default language (de).

Any help?

Take a look at the Language Negotiation API, specifically hook_language_negotiation_info_alter.  With this hook, you can replace the default URL based language negotiation callback function with one that respects the m. prefix.

Something like this should get you started.

function mymodule_language_negotiation_info_alter(&$negotiation_info) {
  // Replace the core function with our own function.
  module_load_include('language', 'inc', 'language.negotiation');
  $negotiation_info[LANGUAGE_NEGOTIATION_URL]['callbacks']['language'] = 'mymodule_from_url';
  $negotiation_info[LANGUAGE_NEGOTIATION_URL]['file'] = drupal_get_path('module', 'mymodule') . '/mymodule.module';
}

function mymodule_from_url($languages) {
    // Your version of locale_language_from_url() that ignores the m. prefix.
}

For reference, the core function that handles language negotiation based on URL is locale_language_from_url.


Why are there so many settings.php files one in each folder or sub-directory? I am Drupal newbie taking over a poorly documented D6 group of sites organized by sub-domains. In examining the dev.[domain].org/sites/ folder I discover folders: all, default, demo.[domain].org and [customer].[domain].org and each folder has its own settings.php?

For example, /default/settings.php allows me to configure-or-edit the 'site_name' => and $db_url and $base_url. The $db_url works.

while, /all/settings.php has a disabled # $base_url and a disabled # 'site_name' => yet an active $db_url that is connecting to a 'mysql://[detail]' that may or may not be an active db.

I presume folders demo.[domain].org and [customer].[domain].org in the /sites/ folder are just legacy folders left by the previous coder/hacker of the settings.php used in the those sub-domains.

Your thoughts and answers will be gratefully consumed.

Thank you, Steve

Refer the multisite doc as Molot suggested. We don't know how your site(s) have set up, so you have to experiment it yourself.

  Q1: Why isn't there just one settings.php per sub-domain site?

There is. sub.example.com site's settings.php file is sites/sub.example.com/settings.php. The reason to have a whole folder is to make it possible for you to store files, modules, themes and libraries separately (sites/sub.example.com/modules will be only available to sub.example.com likewise.)

  Q2: What is the difference between /default/settings.php and
  /all/settings.php?

You should not have a settings.php file in sites/all folder. That folder is a special one that is used to store common files across all the sites, and the default modules/themes/libraries folder for the only site if it's not a multisite.

  Q3: And why are folders demo.[domain].org and [customer].[domain].org
  in the /sites/ folder? Perhaps they are just legacy folders left by
  the previous coder/hacker of the settings.php used in the those
  sub-domains.

If there are demo.example.com site, that site is probably using the settings.php inside to load the settings. You can however change this in the sites/sites.php file. Unless you override, demo.example.com site is using sites/demo.example.com/settings.php.


Changing a node field without going to the admin section? I have a page listing articles (in teaser view mode), one of the fields of the article is a taxonomy term reference.

Is there a method allowing users to change this field and save the new article with this new taxonomy term chosen by the user (without going back to the admin section, just in the teaser view mode)?

Thanks in advance

Editablefields https://drupal.org/project/editablefields lets you edit many things, including terms, with ajax (without going to node edit form) but you'd have to be in fields mode.

Make a view, showing fields, and in the term's field settings you can choose "editable" and adjust some settings.


field_info_instances() returns an empty set in hook_uninstall but not in module file Why would field_info_instances() return an empty set in hook_uninstall() when it returns the expected results in the main module file?

I've used the exact same code to delete the fields for a set of bundles in both the .install file and the main .module file:

  $bundles = array('property', 'open_house', 'agent', 'office');
  // Delete fields
  foreach ($bundles as $bundle) {
    $instances = field_info_instances('content', $bundle);
    if (!empty($instances)) {
      foreach ($instances as $instance) {
        dpm($instance);
        //field_delete_instance($instance);
      }
    }
  }

The following code (pulled from _field_info_collate_fields() in field.info.inc) outputs the fields in a list:

  $definitions = array(
    'field_ids' => field_read_fields(array(), array('include_deleted' => 1)),
    'instances' => field_read_instances(),
  );

as shown here:

 ... (Array, 2 elements)

     field_ids (Array, 149 elements)
     instances (Array, 8 elements)

It was suggested that I need to use drupal_load() and/or drupal_load_include() to load the field module or field.info.inc to use the field_info_instances() function. I also tried using drupal_load() to load my module, but the following code also does not work:

  $bundles = array('property', 'open_house', 'agent', 'office');
  drupal_load('module', 'field');
  module_load_include('inc', 'field.module', 'field.info');

  // Delete fields
  foreach ($bundles as $bundle) {
    $instances = field_info_instances('content', $bundle);
    dpm($instances);
    if (!empty($instances)) {
      foreach ($instances as $instance) {
        field_delete_instance($instance);
      }
    }
  }

Does anyone know why field_info_instances() would be unable to read the information about the field instances?

UPDATE:

When I run the following code: dpm(field_read_instances(null, array('include_inactive' => TRUE))); my fields are displayed.  Why are they inactive, is it because the module is being uninstalled and is disabled?  What should I do to work around this?

I found out that this has been fixed in 7.8. #943772 by jpsoto, yched, catch, bojanz, pillarsdotnet, steinmb: Fixed field_delete_field() and others fail for inactive fields.


How do I change the capitalization formatting of my Taxonomy terms programatically? I am using taxonomy terms with the formatting where the first Letter of the phrase (if there is more than one word in the taxonomy) is capitalized, and then the others are not. So, for examples 'Cars and trucks'

In house we have made the decision to change these so that every major word is capitalized, so, 'Cars and Trucks,' excluding minor words like and, it, but, etc - basically the word list that is in the Path auto terms to exclude.

I have thousands of terms. More over, there was a point when the community contributed them so there is no consistency.

Thoughts on how to tackle this without having to edit them one by one?

Thanks

It's fairly easy to cobble some (admittedly inefficient) code together that will convert a string to title case while ignoring certain words (you'll have to choose the words yourself though):

function _MYMODULE_custom_title_case($string, $blacklist = array()) {
  // Split the words into an array
  $words = explode(' ', $string);

  $new_words = array();
  foreach ($words as $word) {
    // If the word isn't in the blacklist, capitalise it.
    if (!in_array($word, $blacklist)) {
      $word = ucfirst($word);
    }

    $new_words[] = $word;
  }

  // Join the string back up and return it.
  return implode(' ', $new_words);
}

Then you can simply load all of the terms in your vocabulary, change the title, and save them:

$vid = 1; // Vocabulary ID
$terms = taxonomy_get_tree($vid); // Get the terms

// User the pathauto blacklist
$blacklist = variable_get('pathauto_ignore_words', array());
foreach ($terms as $term) {
  // Update
  $term->name = _MYMODULE_custom_title_case($term->name, $blacklist);

  // And save
  taxonomy_term_save($term);
}

I confess to not having tested that so use a bit of caution! If you've got a lot of terms you might want to split it up into batches to avoid hitting a PHP timeout.


How to add 100 contributed modules into git repository fast? I use a git repository, and Drush to manage Drupal projects.

What I would like to do now is to add more then 100 contributed modules to the git repository to keep track on these modules as well.

If I am forced to add contributed modules manually, I have to do the following steps over 100 times:

drush dl <contributed module name>
git add .
git commit -m "<contributed module name> <contributed module version> imported"

I would like to avoid or limit this manual task.
Is there any automated way to do this?

You can use submodule on if you want keep tracking all latest commit for each project, but that means that your project can have development code from one of these modules.

Or, you can also download all your 100 modules with Drush and just do a git add . in the parent directory (git add all files recursively).


Choosing sub-term after choose term when user post article This is my taxonomy, really large. My client want to choose in 2 dropdown menu, first one is parent term, after that, the second menu fetch sub-term which belong to parent term in first menu. How can I do? Is there any module for this case?

  Car

  BMW

  BMW1
  BMW2
  BMW3

  Audi

  Audi1
  Audi2
  Audi3

  Toyota

  Toyota1
  toyota2
  toyota3

Hierarchical Select is exactly for that purpose.

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

  Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!


How do I send http authorization header in GET request in drupal? How do I send http Authorization header in http GET request in drupal ?

Every things else works except the authorization part.

My custom module code:

/*
 *Implements hook_menu
 */
function mymodule_menu() {

$items['demo'] = array(
    'title' => 'Demo API integration with Drupal 7',
    'page callback' => 'demo_page',
    'access callback' => TRUE,
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );
return $items;
}

//page callback
function demo_page() {

$options = array(
  'method' => 'GET',
  'data' => '',
  'timeout' => 15,
  'headers' => array('Accept' => 'application/json',
                    'Authorization' => 'Basic SomeKey23412lkjdfadjfadfasd'),
);

$result = drupal_http_request('https://api.examlesite.com/test/', $options);
var_dump($result);
drupal_set_message("Result is processing");
return "hello world";
}

You can add basic authorization to url to access http basic protected address.

  // http auth
  $remote_url = 'http://uname:pw1234@example.com/service/node';


jquery code for drupal 6 I try to implement this simple js tooltip script on drupal 6 site.

http://jsfiddle.net/wrN2u/50/

$(document).ready(function(){

$('#container').on('mouseenter', '#radiobtn', showBox);
$('#container').on('mouseleave', '#radiobtn', hideBox);

function showBox(e){
var x = e.pageX + 20;
var y = e.pageY + 20;
$('#hoverbox').fadeIn();
$('#hoverbox').offset({ left: x, top: y });
}
});
function hideBox(){
$('#hoverbox').fadeOut();
}

However, the framework is 1.8.2
The script is not working under 1.3.2 which uses drupal 6
Can somebody help me with js code for 1.3.2?

Thank you very much

if you don't want to upgrade the jQuery version. Please try this.

http://jsfiddle.net/ravindrasingh22/3HVpW/

$(document).ready(function() {

    var changeTooltipPosition = function(event) {
      var tooltipX = event.pageX - 8;
      var tooltipY = event.pageY + 8;
      $('div.tooltip').css({top: tooltipY, left: tooltipX});
    };

    var showTooltip = function(event) {
      $('div.tooltip').remove();
      $('
I\' am tooltips! tooltips! tooltips! :)
')
            .appendTo('body');
      changeTooltipPosition(event);
    };

    var hideTooltip = function() {
       $('div.tooltip').remove();
    };

    $("label#tooltip2'").bind({
       mousemove : changeTooltipPosition,
       mouseenter : showTooltip,
       mouseleave: hideTooltip
    });
});

HTML Code

Mouse Hover here

CSS Code

#hint{
     cursor:pointer;
    }
    .tooltip{
        margin:8px;
        padding:8px;
        border:1px solid blue;
        background-color:yellow;
        position: absolute;
        z-index: 2;
    }


Getting Files to show up on new submitted Module page I have a module that is ready for public use, and I have created a Drupal Account and created a development sandbox, and even uploaded the files via git. Now, I am very much a newb regarding git, so perhaps I have done something wrong. I have attached 2 screenshots of my module page screens (public facing page and the edit page).

Now I am pretty sure that the reason I cannot promote to a full project as seen on this page is because I need to create an issue so that the Drupal team can review the module. This page says to create an issue with specific details included. However, for Component, I am supposed to select either 'Module', 'Theme', or 'Feature'. I would like to select Module, but the only options that are provided at this time are 'Code', 'Documentation', 'Miscellaneous', and 'User Interface'. What am I missing? What additional steps do I need to follow to get this module publicly published?

Found answer. Apparently I missed the part where sandboxes do not have download buttons on the project pages. And I was trying to add an issue for MY project, rather than submit an issue to Drupal.org.


Thickbox with Ajax loaded images I using ThickBox to display large image when thumbnails are clicked. This works great with static content that;s loaded with the page.

However, I'm now trying to use Ajax calls to display some of the content, as it involves API calls that can slow down the page generation. I've placed a small JQuery document.ready script like this:

Drupal.behaviors.brickFilterBehavior = function (context)  {
  var element = this;
  $('.brick-filter-test').each(function () {
    var element = this;
    $.get('/brick_filter/test/', function(data) {
      element.innerHTML = data;
    });
  });
});

This fetches HTML from the URL and inserts it into a
 with the class "brick-filter-test". The handler for the URL looks like this:

function lego_filter_test()
{
  // Print out HTML directly.
  print ('');
  // Return success.
  exit(0);
}

The real handler uses API calls to generate the content, so I've simplified for this example. This just returns a static HTML snippit.

On my test page, I have the following HTML:

Loading test content...

You can see this in action here: http://www.neoclassicspace.com/test

In the example, I have two thumbnail images, one statically included in the page, the other dynamically loaded. The static one behaves correctly, and the ThickBox pop-up gets applied. The dynamic one isn't getting the Thickbox treatment, even though it uses the same HTML.

I have tried adding alerts into the JS for both my code and Thickbox, and this has shown that my code runs before Thickbox initialises, so my dynamic DOM objects should be present when it runs.

I've also tried adding Drupal.behaviors.initThickbox(context); to the end of my function, which should cause Thickbox to reinitialise. I've confirmed this runs twice with an alert statement when I do this.

I'm really appreciate any suggestions on this.

Thanks,

James

You need to add the behaviors like this:

Drupal.attachBehaviors($('.ajax-container'));

So looks like in your case it would be:

Drupal.attachBehaviors($('.brick-filter-test'));

This should do the trick

$.get('/brick_filter/test/', function(result){
  element.innerHTML = data;
  Drupal.attachBehaviors($('.brick-filter-test'));
});


Unable to run database updates via Drush - Call to undefined function batch_get() Having some difficulty running database updates via drush after updating modules in the codebase.  This is the error that is being reported:

Error: Call to undefined function batch_get() in /root/.config/composer/vendor/drush/drush/commands/core/drupal/batch.inc on line 92 #0 /root/.config/composer/vendor/drush/drush/includes/batch.inc(98): _drush_batch_command('11459')

This is only happening on our production environment, our staging environment is identical and works without issue.

We are able to run the updates via update.php; but we are planning to migrate to the new core media module in the coming days, and those updates bring the site down until database updates are run so update.php will not be an option.

The database is located on another server, but we have no problem connecting to that server via tools such as drush sql-cli.

We have also tracked down the 'undefined' method in question and verified it to be in existence.

Many thanks in advance for any help.

Run your drush statement with the --debug flag, you will see something along the lines of:

Checking DB credentials yielded error: Unable to find a matching SQL     [debug]
Class. Drush cannot find your database connection details.

Try navigating to the actual sites folder e.g. /var/www/vhosts/EXAMPLE/website/sites/default and run the drush command from the site specific directory.


What might cause the unexpected workflow state changes after executing a rule? I want to change the workflow state to draft from publish and unpublished the node on edit. I used rules for this:

For Unpublish:

For publish:

When I edit a node and save it, workflow state changes to draft through Rules and again changed to published state.

I have not set any trigger settings.

Please suggest what could cause this.

Option 1

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are typically 2 ways of debugging, as further detailed below.

Rules Evaluation Log

Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

More info

For way more details about these 2 variations, move on to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".

Option 2

Try to consolidate your 2 rules in a single rule, by using the Conditional Rules module. This module allows you to use Rules Conditions within Rules Actions. So in your case if you can think of an appropriate Rules Event that fits both cases, you simply use the Rules Conditions and Rules Actions within such consolidated single rule, whereas you use Conditional Rules to trigger either (not both!) of your Rules Actions.


How to access webform field labels in a twig template? The YAML below represents a webform. Theming is simple using the twig template also found below, but the label for email is inline with the input field by default. How can the labels in the webform be accessed through twig for further theming?

Webform YAML

name:
  '#title': Name
  '#type': textfield
  '#required': true
  '#default_value': '[current-user:display-name]'
email:
  '#title': Email
  '#type': email
  '#required': true
  '#default_value': '[current-user:mail]'
subject:
  '#title': Subject
  '#type': textfield
  '#required': true
  '#test': 'Testing contact webform from [site:name]'
message:
  '#title': Message
  '#type': textarea
  '#required': true
  '#test': 'Please ignore this email.'
actions:
  '#type': webform_actions
  '#title': 'Submit button(s)'
  '#submit__label': 'Send message'

webform--contact.html.twig

    <form{{ attributes }}>

            {{ element.elements.name }}
            {{ element.elements.email }}
            {{ element.elements.subject }}

            {{ element.elements.message }}
            {{ element.form_token }}
            {{ element.form_build_id }}
            {{ element.form_id }}
            {{ element.elements.actions }}

    </form>

Your last comment:

  Well that isn't very intuitive. It would be nice to just access
  everything directly in the twig template.

OK, then try different templates:

When the form theme wrapper is executed the inside of the wrapper is already rendered in {{ children }}. Don't try to render the form again, use this template only for the form tag and the outside container:

webform--contact.html.twig

   <form{{ attributes }}>
   {{ title_prefix }}
   {{ children }}
   {{ title_suffix }}
   </form>

Use for the inside of the form the #theme template itself:

webform-submission-form--contact.html.twig

        {{ form.name }}
        {{ form.email }}
        {{ form.subject }}

        {{ form|without('name', 'email', 'subject') }}

Finally you can theme the form element in form-element--webform-email.html.twig


Tabs and Form Submit I have an app that has multipla page tabs. One of the tabs has a form that does a search. The issue I am running is that when I do a search on the form, and then go to a different tab, and then come back, it does the search again. How can I make it so that when I switch tabs and come back that the form is in its default state.

Thanks much for the help.

Include the following within the submit button tag:

onclick="return false"


Table Sorting on "Content Indexed" View type I'm working on maintaining a site that has a view of type (Content Index). This is the only site I've worked on that has had this view type on it. I may have traced that view type down to Search API.

The issue is I have a table that I need to be able to have the fields be sortable.
Right now there is one field that is sortable, but when I go into the Format/table settings, that is the only field (with the exception of the Node ID) that has a checkbox for sortable.

To check to make sure there wasn't anything wonkey going on with the fields, I created a quick view of type content (so a basic view) and recreated it, and all the fields provided were sortable, not just this one.

Is there a reason that one field would be sortable and not the rest, and if so is there something special that needs to be done in order to get the Content Indexed views to have more fields be sortable?

EDIT: "Content Indexed" view type is generated by search API, not Views Aggregator Plus. The body of the question has been updated to reflect this.

As indicated in the edit, the "Content Indexed" view type comes from the module Search API. After digging around I was able to find the page

admin/config/search/search_api

Which houses a bunch of search indexing. For me, I was able to go into the "Content Index" and find a list of fields, with options for how they are indexed. At the top of this page there is the help text:

  The datatype of a field determines how it can be used for searching and filtering. Fields indexed with type "Fulltext" and multi-valued fields (marked with 1) cannot be used for sorting.

I noted some the fields I was trying to sort on were listed ether as full texted, or did not have an option set for indexing at all. Setting these fields to something other than "Fulltext" allowed them to become sortable in the view.


How to build a menu hook module I am trying to get into module building with Drupal 7.

Why is  $tryk = "test" not being taken for the title, but literal strings such as "testmenu" are working?

$tryk = "test";
function menufun_menu() {
    global $tryk;
    $items['menufun'] = array(
        'title' => $tryk,
        'page callback' => 'menufun_greeting',
        'file' => 'menufun_greeting.inc',
        'page arguments' => array('Jane', 'Doe'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
);
return $items;
}

If you want to use a variable for the page title, it is better to use a title callback.

function menufun_menu() {
    $items['menufun'] = array(
        'title callback' => 'menufun_title',
        'page callback' => 'menufun_greeting',
        'file' => 'menufun_greeting.inc',
        'page arguments' => array('Jane', 'Doe'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
function menufun_title(){
    $tryk = 'test'; // dynamic title set here.
    return $tryk;
}


How to move block functions into .inc file? I have a module that is getting pretty large and I want to move the functions that define blocks into another file to better organize my module.

I did this:

Moved those functions ( _block_configure, _block_info, _block_view, etc) to includes/blocks.inc in my module.
Put files[] = includes/blocks.inc in my .info file

This doesn't work though - the blocks disappear when I do this.  What am I doing wrong?

The files directive is used to include files containing classes, check documentation.
You could include the file in the .module file.

require_once __DIR__ . '/includes/blocks.inc';

Edit: Included the other solutions added by @Beebee and @Jimajamma in the answer:

require_once  drupal_get_path('module', 'mymodulename') . '/includes/blocks.inc';
module_load_include('inc', 'MY_MODULE', 'FILE_NAME');
// This method is including a file residing in the module folder not in a subdirectory.


Problem drupal with domain and redirection I have problem with drupal site when migrate it from dev to production. My website works fine until I tried to login as admin. After enter username,password ,and click login I got error page not found. Because I were redirected to a wrong path. For example. I were redirected to www.domain.com/cgp/user but the correct path should be www.domain.com/user. Bellow is actual screenshot. Does anyone have the same problem and know to to fix it? Thank you.

Bellow is virtual host config

<VirtualHost *:80>
   ServerName www.domain.com
   ServerAlias domain.com
   DocumentRoot "/root_directory"
   ProxyPass /  http://webserver_id/cgp/
   ProxyPassReverse /  http://webserver_id/cgp/
   ErrorLog "logs/cgp-error_log"
   CustomLog "logs/cgp-access_log" common
   # redirect non www to www
   RewriteEngine On
   RewriteCond %{HTTP_HOST} !^www\. [NC]
   RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

The problem could be in several areas, depending on your deployment method.

First of all, have you cleared your caches?  This fixes most issues, especially after importing a database.

It could be a server configuration issue, did you set it up or did someone else?  There could be version differences between the installed software on the dev and prod servers.

Lastly, have you tried setting the $base_url in your settings.php?


How to detect when a user navigates to a taxonomy term page and access that terms data? I'm making a custom directory navigation using the PHP code filter, and putting the code in a block. I need to detect when a user navigates to a taxonomy term page, and extract data related to the term so I can display the children of that term, just like a web directory.

Since there is no global variable that you could use to load the node, you will have to use code like the following:

<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
$node = node_load(arg(1));
}
dsm(get_defined_vars());
?>

The dsm(get_defined_vars()); part is of course optional and will only work if you have the devel module enabled. However, if you do have devel, you will be able to see the whole $node object and the tags associated with the specific node.

Notice, that if you are in a term page, you can use the same principle to load a specific term. For example:

<?php
if ( arg(0) == 'tag' && is_numeric(arg(1)) && ! arg(2) ) {
$term = taxonomy_term_load(arg(1));
}
dsm(get_defined_vars());
?>


Organic Groups vs Group - on D7 vs D8? I've done some research on this question, posted it here without any feedback, and have left messages for OG owner (amitaibu) without any response, so hopefully I can solicit useful feedback here.

I'm building a story telling platform that combines passions for genealogy,
family photography, and social media, and brings them to a whole new and
integrated level of telling stories about your ancestors, and celebrating the
life of an individual who has just passed away. I'm building this on Drupal
with Organic Groups as the main organizing construct. Every Album - whether
it's a family tree, a single individual, or even a photo album - is
instantiated as an OG. I'm writing about it and will launch it at
www.greatalbum.net.

Right now, I'm building the prototype on D7+OG because it's stable and it's essential that any piece of content (family/individual/event/place/story/media/etc.) be allowed to exist in more than Album. The goal
is to launch the prototype in April, and then launch the production v1
site in June or July. I'd love the public launch to be on D8+OG, but I'm not
sure how realistic that is, since OG v8.x is currently 1.0-alpha2.

So, my questions are:

Am I correct to understand that Group module does not allow content to exist in more than one group at a time, and hence based on my requirement OG is the better choice?
Should I assume that OG 8.x-1.0-alpha2 is not stable enough to use for a production site, and that I should stick with OG 7.x-2.10 on Drupal7 for now, and wait on the benefits of Drupal8 until OG matures at least to RC1?

Any guidance?

... Am I correct to understand that Group module does not allow content to exist in more than one group at a time ...

Yes that is correct, but you seem to not take into consideration that the Group module has the notion of Group Types, and when you create "a" Group, you have to specify which its Group type is (compare to creating nodes, which you can only do if you first specify the content type for that node).

Moreover, a user can:

have multiple levels of access (none, read, update) to some group (outsider, member, etc).
be member of multiple Groups.

  ...  and hence based on my requirement OG is the better choice?

That's a matter of preference (opinion based), e.g. if you prefer to go for D8, at this time, IMO, the Group module is way more stable ...

  Should I assume that OG 8.x-1.0-alpha2 is not stable enough to use for a production site, and that I should stick with OG 7.x-2.10 on Drupal7 for now, and wait on the benefits of Drupal8 until OG matures at least to RC1?

If you do decide to go for OG, then for the sake of stability, at this time, D7 seems to be the way to go.

Read more: What are the features of the Group module versus Organic Group module?


How to generate an unique code for every node I have a social article website; I created a content type named Article.
When a user creates an article, I want to generate a code shown to the user. This code should be saved in the database because users can return to this article with this code.
It's important to build a views with this code.

I think I must create a CCK field, generate a code (for example hash the node ID or the timestamp of when the node has been create), and show this code in disable a text box for the  author.

Is there any module to do this? What other alternatives do I have?

With some PHP knowledge, you can implemented the field using the Computed Field module. You can also use the module Universally Unique IDentifier. This does not require PHP knowledge, but does not store the code as a CCK field.


Exclude a block from the views result I've created a views page named "Search" with a path of "product-page". Then I created a views block named "Sponsored Ads".

With the "Search" page, I exposed some fields for the filtering, then assigned the "Sponsored Ads" into the region and shows to only page listed "product-page".

I only want to display the "Sponsored Ads" into the "product-page" only, then exclude it from the results with "?"
(Eg. /product-page?title=test&field_category_tid=All)

How can I achieve this? Please help...

There are actually quite a few methods on how to do this. The method here is quick and easy to do.

Install the devel module (you will uninstall it when your site goes live).

Make sure the block visibility settings is set up to only show on product-page.

Then add this code to your theme's template.php file.

function MYTHEME_block_view_alter(&$data, $block) {
  dpm($block);
  if ($block->module == 'views' && $block->delta == "BLOCK_DELTA") {
    //hide the block
    $params = drupal_get_query_parameters();
    if(count($params) > 0) {
      $data["content"] = FALSE;
    }
  }
}

Change MYTHEME to your theme's name, and clear your cache.

Now you need to change BLOCK_DELTA with the delta of your block. To do that you will need to inspect the dpm output, and find your block, then find the delta of your block.

To further assist you in finding your block delta, you can inspect the block in question in your browser, and look at the id of the block. It will contain the delta as a substring with just the hyphens altered.

My delta is block_content-block so my line of code will be:

if ($block->module == 'views' && $block->delta == "block_content-block") {

When you are done remove the line dpm($block);. You may then uninstall devel module if you wish. This code is a primer and you can adjust it if you need, but as is it will work.


User name list in Select Option field I am using webforms and I want to add a Select Option field with the list of all authenticate user names. And if any new user add in my site than it will add automatically in that list
Is that possible? if yes than how?

You could use the References module. This module enables you to use the results from a view as the values for a field.


Drupal 7 webform module is not sending email properly I have this modules enabled in my Drupal 7 site:

Mail System v7.x-2.34
Mime Mail v7.x-1.0-alpha2
Smtp Authentication v7.x-1.0
Webform v7.x-3.19

I have configured Mail system to "format" mails with MIME Mail and "mail" with SMTP Authentication. This configuration is set as site-wide default class.

It works fine for register user email, but when send mail with webforms it doesn't use that configuration (It sends emails with a local smtp).

How can I make webform take mail system configuration?

This is what I did:

Install smtp module and config to send mails with amazon ese service. (Using the test option of this module it was working fine)
Needed to send html mails so I installed "mime mail" and "mail system" modules
After enable both modules I have created a class with "mail system" module in this way:

Create a class with:

format: MimeMailSystem

mail: SmtpMailSystem
After that apply the new class to:

Site-wide default class

Mime mail module class

Tested the result with post register emails (This was working fine, amazon ses with html emails)
Installed "webform" module and create a contact form
Webform is sending mails but is not using my smtp config, it's using my local sendmail server (I realize this when the email was detected as possible phishing and looked at the email header)
This shouldn't be working like this, it should be using the site-wide default class defined in "mail system"
Post register emails are still working

I found the solution for the problem, it's really easy by the way. I hope this is helpfull for somebody else.

What we need is go to:

admin/config/system/mailsystem

Then press "New Setting" link, select "Webform" in the combobox, leave the "key" field empty and save configurations.

Then a new option is enable as shown in the image:

Then we only need to select the right class for Webform module and save.

That's all, i think this should work for other modules too.


Is there a way to add node grants to anonymous users? I want anonymous users to be able to access nodes that are promoted to the front page. (They can't access to nodes that are not promoted.) It seems hook_node_access() isn't seem called for anonymous users. I tried using hook_node_grants() and hook_node_access_records(), but the code I am using doesn't seem to give anonymous users access to nodes promoted to front page.
function myModule_node_grants(\Drupal\Core\Session\AccountInterface $account, $op) {
   return ['show_promoted_news' => [9999]];
}

function myModule_node_access_records(\Drupal\node\NodeInterface $node) {

  $grants = [];

  if ($node->isPublished() and $node->isPromoted() and $node->getType() == 'article') {
    $grants[] = [
      'realm'        => 'show_promoted_news',
      'gid'          => 9999,
      'grant_view'   => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'langcode'     => 'en'
    ];
  }

  return $grants;
}

The access content permission is overriding the grants I give to the anonymous users, who can't access published content. Adding a greater priority does nothing.
I'm being forced to allow anonymous users to access content and override that when I don't want them to have access with hook_node_access().

You might get this to work by using the Group module. Below are some details about how to do so.

1. Configuration

Create a Group Type (pick whatever name you want).
For this case, there is no need for special (custom) Group Roles for the Group Type you created. Since you'll be able to configure what you want by using these Special Global Roles (hardcoded) that come with the Group module (they cannot be defined by the Drupal administrator, and they are always available for any Group Type):

"Outsider": a signed in user that did not join a group.
"Member": a signed in user that did join a group.
"Anonymous": a user that is not signed in.

Create a Group (pick whatever name you want) for the Group Type you created, and let's say you name it "Promoted nodes" (feel free to use another name if you prefer).
Grant the appropriate Group Permissions for the configured Group Type. To do so, you can also configure for each Content Type which Group Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these Group Permissions are not the same permissions (they are specific to the Group module). With the above setup in place, just grant "view" access to the Special Global Role named Anonymous (and pick whatever rights you want for the other roles).

2. Granting access

With the above Group module configuration in place, all you need to do is:

assign each promoted node to the Group "Promoted nodes".
remove the node from the group again if it is no longer promoted.

For sure this assign/remove can be done manually (whenever a node is edited), but it should be straight forward to somehow automate it using "promoted or not" as the trigger to do so (using the API that comes with the Group module).

More info

Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.


Simplest way to get a full set of favicons and touch icons So you've generated a big batch of favicons, touch icons, tiles and whatever to cover the full range of files a broswer might look for, and the generator you used has helpfully given you a whole lot of code to just drop into your HTML <head>, something like this:

<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
<meta name="msapplication-square70x70logo" content="/smalltile.png" />
<meta name="msapplication-square150x150logo" content="/mediumtile.png" />
<meta name="msapplication-wide310x150logo" content="/widetile.png" />
<meta name="msapplication-square310x310logo" content="/largetile.png" />

Great. Trouble is, that's not so simple in Drupal, where:

The root site directory is off limits due to updates.
Even after, say, find/replacing content="/ to content="/sites/all/themes/yourtheme/icons/, the standard way to add items to <head> is one line at a time, through a hook in your template.php or similar.

This is a routine task I do for every site. Is there are simpler way than turning every one of those into something like this from a related apple-touch-specific question in a template hook:

 $appleIcon = array(
    '#tag' => 'link',
    '#attributes' => array(
       'href' => '/sites/default/files/apple-touch-icon-144x144.png',
       'rel' => 'apple-touch-icon', 'type' => 'image/png'
     ),
  );
  drupal_add_html_head($appleIcon, 'apple-touch-icon');

Best  I can think of is overriding my html.tpl.php file, but I'd prefer not to override it if possible, in case Core or my base theme update it due to some new feature or best practice.

Everything  I can find online seems to be only interested in one favicon and one Apple icon, which isn't a problem.

There are custom modules for this, like Responsive Favicons, but they have issues reporting that some icons don't get picked up, and it seems an overcomplicated approach to simply adding some icons.

If you use the metatag module you can use the -favicon and -mobile submodules.

If you visit admin/config/search/metatags (Configuration > Search and Metadata > Metatags), you can alter a metatag set. And you'll get this section:

Here you can enter the paths to the files relative to your Drupal root. eg. sites/default/files/metatags/favicon.ico. Depending on where you've uploaded these files. (You need FTP for this.)

The -mobile submodule will add MS Application icons and in another section.


Add a field in node metadata I am trying to make a module that has two parts:

  1) It calls an API when article is set to published. The API returns a
  work id.

  2) The workid must be saved to the articles metadata or something
  similar so that another function uses that id to display specific html
  in that article.

I am done with the first part. Now I want to know how to save workid in the metadata, is there any option for that in drupal? because I have done this kind of work in joomla.

There no such thing as "node metadata", there are just fields.

So the easiest thing to do is to create a field (in the UI for example, you can then also export the configuration into your module), field_work_id or something, and in put in there with $node->set('field_work_id', $work_id).

You can do that in hook_node_presave(), but then you might not have an node ID yet for a node that is just being created and is already published. You could also use hook_node_insert()/hook_node_update(), but then you need resave the node and make sure you don't trigger a loop.

You can also save the work ID in your own table, or you can store the node together with the work ID in a way that allows you to do a lookup with a query.


Instagram Block Not Showing on Page I have followed all of the tutorials for implementing a Instagram Feed / Block.  I have the correct client id and client information as requested, however my block doesnt show up when i enable it.  Is there an issue with the Instagram Block?

Figured it out.  I was using the Client ID instead of the User ID.   It's all good now :).


D8 - Using Composer to download git repo I want to download my libraries (/libraries) via composer.

Content of my composer.json:

 "repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "github",
        "url": "https://github.com/w8tcha/CKEditor-CodeMirror-Plugin.git"
    }
]

I call composer require "w8tcha/CKEditor-CodeMirror-Plugin":"*"

which tells me

Error -  The requested package w8tcha/ckeditor-codemirror-plugin could not be found in any version, there may be a typo in the package name.

What I am doing wrong?

Thanks

As per @igorw's answer

{
        "repositories": [
            {
                "url": "https://github.com/w8tcha/CKEditor-CodeMirror-Plugin/blob/master/composer.json",
                "type": "git"
            }
        ],
        "require": {
            "ckeditor-codemirror-plugin": "~1.17.2"
        }

}

Then type

  composer require "ckeditor-codemirror-plugin":"1.17.2"


Commerce: How to save user data (in the order date) when delete it Hi all for one of my client site I use Drupal Commerce.

Now: when an user make an order his/her uid and email are stored in the order's tables (I don't know which one, but this is not important) and this is ok.

When the user (or the administrator) delete his/her account all orders related to this user lost account information so in commerce there are orders without uid and email, and this is not good: How to know which is the client that have bought the order XYZ ?

How can I resolve this problem ? Is there the possibility to not delete this information. Other commerce suite like Prestashop op Magento do not have this problem.

M.

Interesting question.

Though I have never worked with Magento or Prestashop(I have made a simple site with it), so I don't know how they deal with it.

At first I saw your question two days ago & I didn't give much thought about it but today I came again & thought, why do we expect a contributed module to do everything for us? We all have to set our own store & can have different requirement...

Commerce Guys are great & have worked so hard to keep it tight with drupal as well as followed the same way which drupal has done to leave hooks for extending it anywhere you want..

You will have to make your own module for this & will have to play around a bit. It would be very interesting I promise.

There is a hook as I remember hook_commerce_checkout_complete() to get all the info of a order when you are going through checkout.
You can pass $order variable as parameter here & it will have all the value related to current order.
You can check like --

function MYMODULE_commerce_checkout_complete(){
  dpm($order);
}

Now go for buying anything on your instance and see what you get.

So the next you will do is...you can retrieve more data if you want(like user data if it exists in case of authenticate user or what ever you want to save for next) and save it in your own table.
Once you get data...there are many things which you can do now...make your own listing page by executing query or...expose your table to views so you get to feel the power of it for your own data too...

And as this is your table...removing your user or in case he deletes his account will never have any effect on this..GOOD!!


Drupal multisite configuration with a single database and redirection based on IP I need to implement multi site configuration in Drupal 7. I have a Drupal code base called example.com and two subdomains sub1.example.com and sub2.example.com in sites/ folder. I am using a shared database also. My requirement is to to redirect a user to sub1.example.com if the user enters the url http://example.com from country1. When any other user hits the same url http://example.com from country2 then he must be redirected to sub2.example.com. The user must be unaware of the country specific domain redirection.

I am using drupal 7.7. I installed ip2locale module for redirecting the users based on their IP and a domain access module also is installed.

  Is the domain access module really needed for meeting my requirement ?

If I have to use domain access module

  do I need to set up virtual host separately for each sub domain when
  domain access module is used? Is ip2locale module alone sufficient for
  redirection based on IP?

If you are using IP2Local and purely redirecting to completely independent url that has a directly associated database (users, content, configurations) you don't really need domain access. You could keep all the data in the same database (save time on table maintenance) and separate them with prefix's.

You will need domain access if you are centrally sharing content, users and admin tasks as well as the database but need to open or restrict access based on the domain that the user is accessing through. If your users need to cross from site1 to site2 or access common content, this would be the way to go. Domain gives you more flexibility and scalability that option 1 but may require a little more work to set up.


How to prevent executing .php files in sites/default/files directory for nginx+php7.0-fpm? URL to Drupal.org article Preventing execution of untrusted PHP

By default .htaccess inside sites/default/files contains:

<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

Adding mod_php7.c version doesn't fix.

Temporary solutions are:

ProxyPassMatch ^/(.*\.php(/.*)?)$ "fcgi://127.0.0.1:9000/var/www/drupal"

And

<FilesMatch \.php$>
   SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>

But they are not recommended and they are overrideable.

There is a Drupal Core issue for adding mod_php7.c to .htaccess, but it's only for Drupal 8 (so how is this solved in Drupal 7 then?) https://www.drupal.org/node/2455465

There is solution for Apache How to disable PHP files from being run in the sites/default/files directory? but not nginx and php7.0-fpm.

So what is the solution?

(I'm running Security Review module that reports PHPs are executable within sites/defaul/files)

Screenshots:

Permissions:

www-data:www-data 755 for dirs / 644 for files

.htaccess:

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

<IfModule mod_php7.c>
  php_flag engine off
</IfModule>

I did restart nginx and php7.0-fpm.

This is what works for nginx and only targets files directory:

location ~ /files/.*\.php$ {
    return 403;
}

This is more generic and wont let any php file in a directory execute directly:

location ~ /.*/.*\.php$ {
    return 403;
}

WARNING, this is posted all over the web but only works for hidden directories:

location ~ \..*/.*\.php$ {
    return 403;
}


Do something after submit the form at hook_form_alter I want to do something after I submit the node. How can I do that?

I use hook_form_form_id_alter(),but I dont know how to use callback function called after the user submit the form

function mymodule_form_node_form_alter(&$form,&$form_state,$form_id)
{
     if($form['#node']->type=="my_content_type")
     {
          $form['actions']['submit']['#submit'][]=my_callback_function;
     }
}

function my_callback_function($form,$form_state)
{
     //my code here!!
     //execute after the user submit the node form
     //and then redirect user to another place,after executing the code above

}

it doesn't work! and I don't know why?
Please tell me how can I do that?

Sorry about that! My problem is fixed.

the code belowed is the anwser

function mymodule_form_node_form_alter(&$form,&$form_state,$form_id)
{
     if($form['#node']->type=="my_content_type")
     {
          $form['actions']['submit']['#submit'][]='my_callback_function';
     }
}

function my_callback_function($form, &$form_state)
{
     //my code here!!
     //execute after the user submit the node form
     //and then redirect user to another place,after executing the code above

}

[Edit] For me, the callback would not fire unless form_state was declared as &$form_state (pass by reference)


Does Drupal have some kind of Structure system? I looked all over but no result ...

I wonder if there is a Structure System for Drupal like: Spaces - Sections - Groups - Blocks - etc.

Where to use Spaces and may I have groups in spaces? The documentation is somehow messy, I'm lost. But there seems to be no good guides (like books) for a Drupal beginner.

Edit:

It takes time to find out what I need, where to install, etc.

Drupal 7 with Open Atrium 2 should be used for a Information an collaboration suite for a company. Login and all user-information and its roles comes over LDAP and active directory. So far I haven't got any problems.

But now I would like to build a user page:

I take a layout with two cols.
In the right column I have all the information read from active directory and user information.
In the left column there should be some different things.

But I would be very happy if I could understand how to build a user page with all the logged in user information automatically where user will be redirected after logged in.

I don't know how the hierarchy in Drupal works:

Do I need a space for all user who are logged in in Drupal?
And do I have groups inside a space or can I have groups without a space?

Edit:

So please don't mind if I give you this advice:

Not to explain all this modules and for what they are all for but to give specific projects and go through this from the first plane and road-map over the modules which we need till the building and setup.

So we can see it quit from the other side. Starting from a project going through drupal. And not from Drupal and for what it could be all for.

In my case I should build a company platform for all employees with there personal date from active directory (LDAP) and build up a personal page for each employee with his personal data with Drupal.

If you're new to Drupal, you might have a hard time getting your head around the (amazing) Panels module, and things like "context", etc. But it sounds that's part of what you're looking for. Watch the videos about Learn Page manager for more details. After you reviewed these videos, you should understand various features that come with the Panels module ... but also its challenges.

As an alternative, you may want to give it a try to see how far you can get with any (or all?) of these modules:

Display Suite (a typical alternative for using Panels).
DataTables used in combination with Views (especially because of its client side search facilities).
You might want to check also to what extend the features provided by Organic Groups module might help in your case.

Fairly sure that at some point you should also look at the Rules and Flag module.

Video tutorials

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great (+ free) video tutorials Learn the Rules framework, organized in 7 chapters.
Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.
The amazing set of videos to Learn Organic Groups might help to better understand what Organic Groups is all about.
While you're there, why not also review the set of 30 video tutorials about the Views module.


How to select quarters in a date field not the actual date? Is there any way that I can select quarters in a date field not the actual date. I want the date field exactly like in the below image.

I have checked for the options in the date field but I didn't find any such option?

Or is there any other module which provides the same functionality?

I also could not find a widget that provides this functionality but I would stick to the date field.

You need 2 things:

A widget that allows you a selection like that.
A custom format for the display of your field's value. The default date format will not help here since PHP does not provide the quarter.

Keep in mind that the storage for the values will be a normal date but you could i. e. interpret "2017-01-01 00:00:00" as "Quarter 1 2017", "2017-04-01 00:00:00" as "Quarter 2 2017", etc.

You can find further information on how to create your widget and formatter here:

Widget: You can also take a look at the date_popup sub module of the date module.
Formatter


Add new taxonomy term on node edit form I'd like to add a new taxonomy term and assign the node while adding or editing the node. I don't want to use any of third party modules. I'd like to do it by myself in code. Maybe some of you have faced this problem. Anyone know how to do it?

Go to admin/structure/types/manage//fields
Add new field:

Select field type -> Term reference
Select a widget -> Autocomplete term widget (tagging)

You should now be able to add new terms in node add/edit form via the autocomplete field. You don't need any custom modules. Drupal's core taxonomy module offers this functionality.


Exposed filter slider for numbers I am creating real estate website and as exposed filter for search in views i have a price.

Core view options are sufficient but maybe not so user friendly (as i have to explain in details how to input price, like dont use dots or spaces) so i was thinking of using slider so user can pick price range (for example from 10.000 up to 100.000).

I am not good at coding so was looking for module that does this ?

There is also the Better Exposed Filters module.

If you use the latest dev version there is support for jQuery UI slider, which was recently committed from a patch at http://drupal.org/node/1627524

It allows the use of a jQuery UI slider for any numeric filter (except date filters, which are technically an extension of the numeric filter).


Command to start nodejs? Server.js and app.js missing The outdated documentation for drupal integration of nodejs using the nodejs module instructs me to start  nodejs with the command node server.js.

But neither server.js or app.js (replacement to server.js) exists

I can see a file called nodejs.js but running node nodejs.js produces this error;

ReferenceError: jQuery is not defined
    at Object.<anonymous> (/data/disk/o1/static/hood-7.43.1/sites/all/modules/nodejs/nodejs.js:132:4)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

What is the command for starting nodejs?

If you're downloading the app from github directly, follow these instructions:

Download the archive
Extract to a folder oustide of Drupal's root (this app is separate to your Drupal installation so shouldn't be within)
cd to the folder and run npm install
Run cp nodejs.config.js.example nodejs.config.js, edit the resulting file as required
Run node app.js

Voila, server up and running.

If you're using the npm install drupal-node.js approach, the instructions are a bit unclear. To clarify:

Create a folder outside of the Drupal root
cd to it and run npm install drupal-node.js
Run cp node_modules/drupal-node.js/nodejs.config.js.example nodejs.config.js, edit as required
Run node node_modules/drupal-node.js/app.js to start the server

You should see the same result as the first method.


Custom block with configurable message inside it When creating a custom block, how can we add a message and have it configurable by the user?  Is this possible?

This is a good example for a Drupal 8 custom block that is configurable by the user


Drupal 7 Views - Get link to node I use theme information to style the output of my view.
I'm overriding this file: @file views-view-fields.tpl.php

I access my custom fields by using:

$fields['field_FIELD_NAME']->content

Now I want to get the link to the node.
I know I can get the link by choosing "link field to node" in the view settings.
However, I don't want each field to link individually, I want to wrap them in a link.
Any ideas ?
Thanks!!

Select the following fields to output:

1- title, body, path, (Global: Custom text) and any other fields you want. and make sure that (Global: Custom text) is ordered last, and all other fields are excluded from display.

2- in (Global: Custom text) settings, use the fields' tokens in the body. [title], [body], then choose "Output this field as link" and in the path just enter the [path] token. (See Replacement Patterns for more details)

Hope this works... Muhammad.


Loading cck fields from nodes of a content type I have created 4 nodes by a content type called insert_item using CCK; now I am trying to load all CCK fields into a template of a new node where I would use the CCK field value of the insert_item content type.

What I have written is the following code:

$nodes = array();
$result = db_query("SELECT nid FROM {node} WHERE type = 'insert_item'");
while ($row = db_fetch_object($result)) {
  $nodes[] = node_load($row->nid);
  print $nodes;
}

What I got is the following:

  ArrayArrayArrayArray

I really don't know what to do.

Try changing print $nodes to print_r($nodes) and also move it to the outside of your while loop.

Your code should look like this:

$nodes = array();
$result = db_query("SELECT nid FROM {node} WHERE type = 'insert_item'");
while ($row = db_fetch_object($result)) {
  $nodes[] = node_load($row->nid);
}
print_r($nodes);
//If you use Devel, uncomment this next line and comment out print_r above
//dpm($nodes);

This will give you an easy to read value.

Another option is to use the Devel module, and instead of using print_r you can use dpm() which uses Krumo to pretty print the contents of your array.  There are some basic instructions for that dpm() here and here.

Information on print_r here.

  If given an array, values will be presented in a format that shows
  keys and elements. Similar notation is used for objects.


Saving the content from a Textarea dont works An Textfield within my Custom Content Pane works fine.

An Textarea incl. input-filter ('#type' => 'text_format',) will not be saved.

<?php
  function text_edit_form($form, &$form_state) {
      $conf = $form_state['conf'];

      $form['form_text'] = array(
        '#type' => 'text_format',
        '#title' => t('Text'),
        '#format' => 'filtered_html',
        '#size' => 50,
        '#resizeable' => TRUE,
        '#default_value' => !empty($conf['form_text']) ? $conf['form_text'] : '',
      );

      return $form;
    }
  function text_edit_form_submit($form, &$form_state) {
    foreach (array('form_text') as $key) {
      $form_state['conf'][$key] = $form_state['values'][$key];
    }
  }
?>

At drupal.com somebody wrotes, that #default_value expect and string, but text_format is an array. So he postet the following solution.

But how can I build that within my hook_edit_form?

<?php
      // Retrieve the default values for 'value' and 'format', if not readily
      // available through other means:
      $defaults = array(
        'value' => '',
        'format' => filter_default_format(),
      );
      $my_richtext_field = variable_get('my_richtext_field', $defaults);
      // Just construct a regular #type 'text_format' form element:
      $form['my_richtext_field'] = array(
        '#type' => 'text_format',
        '#title' => t('My richtext field'),
        '#default_value' => $my_richtext_field['value'],
        '#format' => $my_richtext_field['format'],
      );
 ?>

Who can help me with that?

Solved!

I just rebuild the save-stuff:

<?php
function text_edit_form_submit($form, &$form_state) {
  $form_state['conf']['form_text'] = $form_state['values']['form_text']['value'];
}
?>


Add Admin User in Drupal 6 I have an old site built in Drupal 6 and I need to add a new admin user. I cannot give out user #1 and need a new one.

As far as roles go, I have authenticated and anonymous.

Is it as simply as adding a new role and granting full access or is there something a little easier I can do to accomplish this?

Admin role with this module you can add more super users.

  This module is a little helper to maintain an administrator role which
  has all available permissions. By default, Drupal only has one super
  user and this module helps improve this drastically.


How can I build a redirect from submitted form values? I'm working on a short weather app.

What I want to do, is to catch name of the input of city and redirect users to the city's page URL after submit.

function form_findYourCity_submit($form, &$form_state) {

  $city = $form_state['values']['city_name'];

  // catching city name from input and assigning it to a variable
}

And I want after submit redirect user to new page with url/something/?city=something on which I then want to use if isset $_GET['city'] and then do my operations with the weather API database and pulling data based on the city.

Okay I have figured it out by myself.

Here is what I needed:

function form_findYourCity_submit($form, &$form_state) {

  $city = $form_state['values']['city_name'];

  $form_state['redirect'] = [
    'showCity',
    [
      'query' => [
        'city' => $city,
      ],
    ],
  ];

}


Theme Suggestion for overridding page-title.html.twig file? Is there a way to override the default page-title template using the theme suggestion. Like we can override node for article type as below,

For all nodes:    node.html.twig

For nodes of article type:    node--article.html.twig

same way,

for all page title: page-title.html.twig

for page title on article content type: ???

I tried many things like page-title--article.twig, field--page-title--article.html.twig, field--bartik-page-title--article.html.twig, node--article--page-title.html.twig etc.. these are not working. OR it is not possibel to do this with page-title file?

You can do this by adding your own suggestion. In your theme's ThemeName.theme file add a hook_theme_suggestions_HOOK_alter() for the page title:

// Add content type suggestions, e.g. page--node--article.html.twig.
function ThemeName_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  // Are we looking at a node?
  $node = \Drupal::routeMatch()->getParameter('node');
  // Object check required, sometimes it's a string, yes, really. Who knew?
  if (!empty($node) && is_object($node)) {
    array_splice($suggestions, 1, 0, 'page_title__' . $node->getType());
  }
}

Then create templates per node type, e.g. page-title--article.html.twig, page-title--custom-content-type.html.twig etc.

Edit: rather than the array_splice you can just push suggestions onto the array, e.g.:

  if (!empty($node) && is_object($node)) {
    $suggestions[] = 'page_title__node';
    $suggestions[] = 'page_title__node_' . $node->getType();
  }

array_splice() is just a trick I commonly use to position suggestions in the $suggestions array so I can control when they are picked up and used.


form or content type creation interface? I want users to insert information. I can define a complex Content type with multiple fields, restricting the kind of info user is allowed to insert (integer, text…), as well as rules… and expose it as if it were a form when user clicks on 'add new info'.

But I want more complex things to happen, for example, when user submits data.

I am confused about how to achieve that (hooks in a module?).

Moreover, I have seen many tutorials around about creating forms (which imply a lot of coding for things like defining the data types, validation...that can be easily defined in Content type creation UI). Which difference would be between 'hacking' the 'add new content type' operation and creating a brand new form?

Sorry, as you may notice I am a brand new beginner in Drupal.

You don't usually create a custom module just to have fancy fields in a form. If it can be done with fields, you do it with fields (i.e. you use the content type creation UI). For data types that doesn't exist in the core (e.g. links and entity references) there is almost always a module that let you add fields of those types to a standard Drupal entity.

You only create a custom content type if you want to do a lot more than just capturing the data. With "more", I means such things as computing aggregates, transforming it, combining it with other data, visualizing it, etc.

My rule of thumb is: If it can be done with fields and contributed modules - do it with fields.  If it can't be done with fields, create a custom module.  And in that case, I let the custom module also manage the form and data validation (but built-in top of the Form API).

If you want do just want to interact with the creating, validation or deletion of an entity, there is a lot of good examples of what you can do in the entity_example.module.

For instance, to have a submit handler that does extra validation before saving, look at function entity_example_basic_form_validate.


Allow all OG members to view/edit all content I'm pretty new to OG and I'm testing a collaborative intranet site at this moment with Drupal7 and Organic Groups 7.x-2.3.

It is a simple app for a small group where all the members know each other and can be trusted. We're working on a Degrowth Workshop (link to the workshop announcement, in Spanish).

I've used OG to set the organizers in the different work areas (catering, activities, kids, lodging,...), have lists grouped by... groups (of course), and create a customized homepage for the members of the different groups. Everything ok until this point.

Now what I want is that everyone (all registered users - there's NO access to anonymous) have access, can read, write, edit, comment, etc to any node, whether it be of their group or not.

I'm fighting with the Field Settings, Permissions and roles but can't get to achieve it and there's always some hidden content to members of different groups. I've read quite a few solutions to similar issues but can't get a clue.

Organic groups controls (Organic Groups Global Permissions) are different from your site permission, roles etc. To allow authenticated users the required permission, configure the organic groups global permission:

Navigate to: Configuration -> Organic Groups Global Permissions (drupal/admin/config/group/permissions), here you will find the controls over who can view and edit nodes and fields on your group pages.

Few reference for the organic groups permission:
http://vimeo.com/32398425
http://vimeo.com/32398425
https://drupal.org/node/2014929
https://drupal.org/node/2014793


Override webform module submit I want to save webform submissions in node table..

I want to use the solution from "How to create a node out of a webform submission?".

How can I implement it? I used hook_form_alter but it doesn't work.

The question about "How to create a node out of a webform submission?" that you linked to, is about D8, while yours is about D7 ...

In D7, for sure,, you can use the Rules module for this. As an example, consider this rule (in Rules export format), which does what you're asking for:

{ "rules_create_a_node_from_webform_data" : {
    "LABEL" : "Create a node from webform data",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form_id" ],
          "selected_webform" : { "value" : { "webform-client-form-191" : "webform-client-form-191" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform submitted contains these fields:\r\n\u003C\/ul\u003E\r\n\u003Cli\u003Ethe field labeled \u0022[data:demoform_title-title]\u0022 which has value \u0022[data:demoform_title-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_text-title]\u0022 which has value \u0022[data:demoform_text-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_number-title]\u0022 which has value \u0022[data:demoform_number-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_option-title]\u0022 which has value \u0022[data:demoform_option-value-raw]\u0022.\u003C\/li\u003E\r\n\u003C\/ul\u003E" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_text-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_text" : "Form variable text" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_number-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_number_text" : "Form variable number text" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "var-demoform-number-text" ] },
          "PROVIDE" : { "conversion_result" : { "var_demoformvar_number" : "Form variable number" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_option-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_option" : " Form variable option" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "article",
            "param_title" : "[data:demoform_title-value-raw]",
            "param_author" : [ "user" ]
          },
          "PROVIDE" : { "entity_created" : { "article_created" : "Created article" } }
        }
      },
      { "data_set" : {
          "data" : [ "article-created:body:value" ],
          "value" : [ "var-demoform-text" ]
        }
      },
      { "data_set" : {
          "data" : [ "article-created:field-free-format-nr" ],
          "value" : [ "var-demoformvar-number" ]
        }
      },
      { "data_set" : {
          "data" : [ "article-created:field-optionlist" ],
          "value" : [ "var-demoform-option" ]
        }
      },
      { "data_set" : { "data" : [ "article-created:comment" ], "value" : "0" } },
      { "entity_save" : { "data" : [ "article-created" ], "immediate" : "1" } },
      { "drupal_message" : { "message" : "A new article got created, with nid=[article-created:nid] and url=[article-created:url]" } }
    ]
  }
}

Anybody a bit familiar with Rules and Webform, while know that it's often a struggle to get access to the data contained in a submitted Webform. Mostly because they are not available to select them when building Rules Actions.

However by introducing those var-demoform-... variables (as in the above rule), you can make the typical Rules magic happen. Refer to my answer to "How to create a node from a Webform using rules?" for more details about all this.


Similar Module for Drupal: Easy Folder Listing? Do you know of a Drupal module that does this: I have been searching for a solution to use in a Drupal site where the Folder Contents are Listed in a Table, exactly as described in the below description of this Joomla module.

http://extensions.joomla.org/extensions/directory-a-documentation/downloads/12249

Description:
This is a simple-to-use module that is used to list the contents of a folder in either a table or a list. The folder listing can display the filename, with or without the extension, with or without the date modified and file size, as well as a icon representing the file type. It has the feature of allowing the user to specify whether the filename listed should be linked or not.

Main features:

  List files in a specified sub-folder of the Joomla root
  Show icons for file types
  List files in either a table or a unordered list
  Option to link to the files or not

Maybe you have to try two modules who allow to manage files in Drupal:

media project

  The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site

workbench media : it's an integration of the first module in the workbench suite, that's great if you want a listing of all your files uploaded in your site.

If you just want to display files to the users, you can do that quickly with views:

Add a new view
In show section select files

After you'll be able to show all the files you have in your folder (but you can also restrict to only show files from a specific content type)
I took a photo of all the fields available :


Entity Reference - adding fields to reference? I'm using taxonomy and nodes to create a tree structure. Inside the taxonomy term I created an Entity Reference (referencing to nodes). I know this looks like the world upside-down, but for this time this was the easiest way.

Term1 (reference to:) - Node A, Node B, Node C, Node D
Term2 (reference to:) - Node B, Node D, Node E

I want to add custom fields to the node, but with different values for each reference. Let's say I want to add a date field with different values for each reference. Adding a custom field to the content type won't work, because they will be the same for all references.

The Entity Reference module does not support this. You'll want to check out the Relation module. With this module the reference (relation) itself is a fieldable entity.

I do realize you'll have to write an update function to migrate your current references to relations, but aside from creating a custom table as @FriOne suggested, it's the only way to go as far as I know.


How replace city text box in shipping address with select component in drupal 7 commerce I want to know, is there any way to change city textbox in shipping address (in Drupal commerce 7) to select component?

in normal mode, user have to write the name of city but I want to change it to select field so user can select a city between available items in select field.

Also I want to add another select field to address that contains provinces.

In drupal several module can solved your problem:

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

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

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

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

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

you can choose on of them and edit for your country. for example in addressfield_vn change country code «VN» to your country code. and add your province and city name to module.
for iran address i create a module. if you want then email to me.


When/where to include my own function library (like common.inc)? When, hence where, should I include my own library of functions that I will use throughout my whole project.

Drupal has it's common.inc that is included in drupal_bootstrap during the fase DRUPAL_BOOTSTRAP_FULL. I also have a common.inc with functions that I use all the time, in different modules. I want to include this file once so I can use it everywhere without having to include it in each file separatlely.

So what is the right location/hook to do it?

Probably best to put it in it's own custom module, e.g

sites/all/modules/custom/mymodule_common

and enable it as required.

You can make it a dependency of other modules by adding it to those module's .info file, e.g

dependencies[] = mymodule_common

You could also use subfolder and standalone file in sites/all/libraries/common though the module route is recommended.


Links inside SVG have undefined events I have a problem with a site I'm developing in which I have a US map with each state as a polygon defined in an svg. Each of those polygons is wrapped in a link so users can click on a state to be taken to information about that state.

Code layout:
<svg...>
  <a xlink:href="...">
    <polygon ...><title>{stateName}</title></polygon>
  </a>
</svg>

The problem I'm having is when someone clicks one of these links I get several errors:
TypeError: this.href.match is not a function in googleanalytics.js line 36, col 66
    ...rupal.settings.googleanalytics.trackOutbound && this.href.match(/^\w+:///i))
TypeError: target.protocol is undefined in overlay-parent.js line 575
    if (href != undefined && href != '' && target.protocol.match(/^https?:/)) {

After some experimentation I narrowed it down to those functions having undefined events.

The googleanalytics.js function is:

...
$(document.body).bind("mousedown keyup touchstart", function(event) {
...

The overlay-parent.js function is:

...
Drupal.overlay.eventhandlerOverrideLink = function (event) {
...

I assume this has something to do with the links being nested in the svg for some reason but I can't find any good information on why or how to get around that.

I tried using a jquery.svg.js plugin but that had no impact.

Using:
Drupal 7.34
jQuery 1.10.2 (via ajax.googleapis.com)
Google Analytics 7.x-2.1 (googleanalytics.js)
jQuery Update 7.x-2.4 (replace/misc/1.9/overlay-parent.js)

If any other info is needed to help figure this out let me know.

Thanks in advance for any help you can provide!

The issue is the way the google analytics module tracks clicks.  It adds mousedown, keyup, and touchstart events to the body and tries to match the clicked position the the closest anchor.  When it encounters a click on an SVG element it gets confused and is not able to properly match the closest anchor.

There are a couple options to remedy this:

Using :after on your anchors to create a block that covers up the SVG elements.
Using pointer-events: none on all SVG elements inside your anchor.
Turn off click tracking in your Google Analytics settings.
Unbind click tracking on your map page only with something like $('body.mymappage').unbind()
Manually patch the GA module:

Change the line (googleanalytics.js):

$(event.target).closest("a,area").each(function() {

to:

$(event.target).closest("a,area").not(".svg-anchor").each(function() {

The first 2 options are documented here, and a codepen example fix is here.


tpl.php files in a module directory I am trying to have one tpl file per view mode inside a module folder. But I can't get drupal to pick up the right tpl file.

I have been trying solutions on these pages:

http://www.metachunk.com/blog/adding-module-path-drupal-7-theme-registry

/**
 * Implements hook_theme_registry_alter()
 **/
function nwd_press_room_theme_registry_alter(&$theme_registry) {
    global $theme_key;
    $mod_path = drupal_get_path('module', 'nwd_press_room');
    $theme_registry_copy = $theme_registry;       // munge on a copy
    _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', $theme_key, $mod_path);
    $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
    $hooks = array('node');

    foreach ($hooks as $h) {
        if (!isset($theme_registry[$h]['theme paths'])) {
                $theme_registry[$h]['theme paths'] = array();
        }
        nwd_press_room_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
    }

    dpm($theme_registry);

}

/**
 * Helper function for re-ordering arrays (needed by theme_registry_alter)
 */
function nwd_press_room_insert_after_first_element(&$a, $element) {

    if(is_array($a)) {
        $first_element = array_shift($a);
        if ($first_element) {
            array_unshift($a, $first_element, $element);
        } else {
            array_unshift($a, $element);
        }
    }
}

Since I still want the tpl file to be overridable in the theme. Does anyone have an example that works?

Found the solution after extensive search and trial & error:

/**
 * Define the new view modes
 *
 * implements hook_entity_info_alter()
 * @param $entity_info
 */
function my_module_entity_info_alter(&$entity_info) {

    $entity_info['node']['view modes']['grid'] = array(
        'label' => t('Grid'),
        'custom settings' => TRUE,
    );

    $entity_info['node']['view modes']['list'] = array(
        'label' => t('List'),
        'custom settings' => TRUE,
    );
}

/**
 * Tell Drupal to also look for template files in the modules folder
 *
 * implements hook_theme_registry_alter
 *
 * @param $theme_registry
 */
function my_module_theme_registry_alter(&$theme_registry) {

    $path  = drupal_get_path('module', 'my_module');
    $theme_registry += drupal_find_theme_templates($theme_registry, '.tpl.php', $path);
}

/*
 * Implements template_preprocess_node().
 */
function my_module_preprocess_node(&$variables){

    // Add the theme hook suggestion to include view mode
    $variables['theme_hook_suggestions'][] = 'node__'.$variables['type'].'__'.$variables['view_mode'];

  }
}


How to delete all but the current revision from the field_collection_item_revision table? I have a Drupal 7.24 Website making heavy use of field collections.

The field_collection_item_revision keeps getting bigger and bigger (9'000'000 rows) and only 200'000 entries are in field_collection_item.

What is the most secure and efficient way to "clean" this table?

PS: A SQL request with nested selects is not an option, it's too slow.

(Assuming a MySQL database)

Execute the following MySQL request:

DELETE fcir FROM field_collection_item_revision AS fcir
  RIGHT JOIN field_collection_item AS fci
    ON fcir.item_id = fci.item_id
  WHERE NOT fcir.revision_id = fci.revision_id;

We delete all revisions that are not present in the field_collection_item table under "revision_id".


Drupal7: Rules Module - change the FROM field I am using the Entityform module with the Rules module.

When the user submit the form, an email notification is sent out. In the email notification, I want the FROM field to be the user's email address as opposed to the 'site-information' email address.

I couldn't set this with Rules in the Drupal Admin (I can only adjust the 'TO' field)
How can I do that by code? or if you have any other idea to have the FROM field varies depending on the user's email address.

Thanks.

Boutros.

I finally figured it out.
You can edit the "Send mail" component of the Entityform rules at:
/admin/config/workflow/entity_rules/entityform_submission/manage/rules_entityform_notifications_email_send

Then specify the value of the FROM field from the replacement patterns.
Keep in mind, when you build the form, or any new future forms, make sure that you always use the same field for the email and make it required. An empty email will result of the FROM field being sent from the site-wide admin email and not from the user's email.
See image, hopefully it helps:


Get Checkbox Value From Another Form How do i get the value of a checkbox from another form/page and how do i make it so if the checkbox is enabled, it'll allow a button to be visible?

checkbox in SettingsForm.php:

$form['#tree'] = TRUE;
    $form['clients_enabled'] = array(
      '#title' => t('Enable PixelPin OpenID Connect'),
      '#type' => 'checkboxes',
      '#options' => array('pixelpin' => $this->t('Enable')),
      '#default_value' => $clients_enabled,
    );

button ion LoginForm.php:

public function buildForm(array $form, FormStateInterface $form_state) {
    $definitions = $this->pluginManager->getDefinitions();
    foreach ($definitions as $client_id => $client) {
      foreach ($this->pluginManager->getDefinitions() as $client_name => $client_plugin) {
        if (!$this->config('pixelpin_openid_connect.settings.' . $client_id)
          ->get('enabled')) {
          $url = \Drupal::service('path.current')->getPath();

          $find = 'login';

          $pos = strpos($url, $find);

          if ($pos === false){
                $value = 'Register Using @client_title';
            } else {
                $value = 'Log in with @client_title';
            }

          $element = 'clients_enabled[' . $client_plugin['id'] . ']';
          $form['pixelpin_openid_connect_client_' . $client_id . '_login'] = array(
            '#type' => 'submit',
            '#value' => t($value, array(
              '@client_title' => $client['label'],
            )),
            'visible' => array(
              ':input[name="' . $element . '"]' => array('checked' => TRUE),
            ),
            '#name' => $client_id,
            '#prefix' => '<div>',
            '#suffix' => '</div>',
          );
        }
      }
    }
    return $form;

Create a config file inside your_module/config/install/.

Inside SettingsForm.php write,

$form['#tree'] = TRUE;
$form['clients_enabled'] = array(
  '#title' => t('Enable PixelPin OpenID Connect'),
  '#type' => 'checkboxes',
  '#options' => array('pixelpin' => $this->t('Enable')),
  '#default_value' => $clients_enabled,
);

public function submitForm(array &$form, FormStateInterface $form_state) {
  $config = $this->config('pixelpin_openid_connect.settings');
  $config->set('clients_enabled_key', $form_state->getValue('clients_enabled'))->save();

}

Inside LoginForm.php, get it :

public function buildForm(array $form, FormStateInterface $form_state) {
$definitions = $this->pluginManager->getDefinitions();
foreach ($definitions as $client_id => $client) {
  foreach ($this->pluginManager->getDefinitions() as $client_name => $client_plugin) {
$is_enabled = isset($this->config('pixelpin_openid_connect.settings')
      ->get('clients_enabled')) ? $this->config('pixelpin_openid_connect.settings')
      ->get('clients_enabled') : false;
    if ($is_enabled) {
      $url = \Drupal::service('path.current')->getPath();

      $find = 'login';

      $pos = strpos($url, $find);

      if ($pos === false){
            $value = 'Register Using @client_title';
        } else {
            $value = 'Log in with @client_title';
        }

      $element = 'clients_enabled[' . $client_plugin['id'] . ']';
      $form['pixelpin_openid_connect_client_' . $client_id . '_login'] = array(
        '#type' => 'submit',
        '#value' => t($value, array(
          '@client_title' => $client['label'],
        )),
        'visible' => array(
          ':input[name="' . $element . '"]' => array('checked' => TRUE),
        ),
        '#name' => $client_id,
        '#prefix' => '<div>',
        '#suffix' => '</div>',
      );
    }
  }
}
return $form;
}


Change the Solr Operator to OR Am working with drupal search api solr module am trying to get it to work with the OR Operator so if i do a search for "David Smith" it should show results for both "David" and "Smith" does anyone have ideas on how to achieve this

By default, the apachesolr Drupal module is set to do an AND search.  However, you can change that in one of two ways:

Implement a custom module that alters the queries sent to apachesolr.  All you'd need is to implement the apachesolr_query_alter hook.

 <?php
 function HOOK_apachesolr_query_alter($query) {
   // Force an OR keyword search.
   $params['mm'] = '100%';
 }
 ?>

More details can be found on this drupal.org documentation page: http://drupal.org/node/1159424

The second thing you can do is modify the deafaultOperator from "AND" to "OR" in apachesolr's schema.xml file.  You should be able to find that in your modules/apachesolr/solr-conf folder.  That setting should be towards the end of the file

<!-- SolrQueryParser configuration: defaultOperator="AND|OR" -->
<solrQueryParser defaultOperator="AND"/>   // change to OR here

With this second one, just be careful.  You don't want to make this change to your schema file and then forget and have it replaced later when you update your module or something like that.  Just by searching now, I can see there is this rather unstable module that exposes some of the configuration options of the schema file in the User Interface: http://drupal.org/project/apachesolr_confgen, but I'm not sure I'd choose to use that...

Hope one of these helps!


"The website encountered an unexpected error. Please try again later." I get this error with Drupal 7.

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

How can I get more information about this error? Is there any report or log to understand what happened? The PHP log doesn't report errors.
How can I disable that message and have a more useful one for debugging purpose?

This error comes from an uncaught PHP exception. Drupal catches exceptions so no ugly PHP error message is displayed to user. You can find the exception info in the 'Recent log messages' link on Reports (or try this path: /admin/reports/dblog). Make sure 'Database logging' module is enabled because this module provides this report.

You will see all the internal messages that have been generated. Filter by type 'PHP' and Severity 'error' and you'll probably find a message about an uncaught exception. This is causing your problem. Now you have more information so you may be able to fix it.


Best method of changing content of one field based on whether another exists I have one field, field_foo, that I want to be rendered one way if field_bar does not have a value. Should field_bar exist, I would like to render the values of both field_foo and field_bar together inside the same markup that all my other fields have.

I could do this in the template file for the content type, but that does not seem like the Drupal way (logic in the tpl file).

I am already using theme_field to adjust the way some of my fields are being rendered, and I have tried to put the logic in there, but I am not sure how to access other fields from within a field-specific theme_field function. Moreover, this does not really strike me as the proper place for this logic either.

What would be the best way of implementing the different rendering of one field based on whether or not another field has content?

look in to https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7.x

In Drupal 7 yes you can do this in the template file for the content type, -> unless you are changing themes lots perhaps the "custom logic" in the  theme file is the quickest win.