AJAX returns response code 200, and displays error messages in callbacks I'm running Drupal 7.34 with quite a few modules (relevant because unfortunately I did not notice when the problem first started and it would take ages to look through them all one by one) and I have some quite strange behaviour. Whenever I try to fill in an autocomplete text field, manually check for updates or do anything else that involves AJAX really, I get an error message with the HTTP Response Code 200 and the response text is actually the HTML of the user profile page. One exception to this is in a custom module I wrote which uses callbacks, and strangely when the callback is outputted any persistent messages (i.e operating in maintenance mode) are also displayed in the same place. I have tried disabling and deleting this module but it did not change anything.

Also, I suspect it could be related that my messages log is filled with warnings saying:

Warning: Cannot modify header information - headers already sent by (output started at /home/site.com/public_html/includes/common.inc:2725) in drupal_goto() (line 697 of /home/site.com/public_html/includes/common.inc).

Does anybody have any idea what could be causing this?

Thanks to some brilliant and generous help from @thedotwriter, I believe I have found the cause of this problem and a solution.

In turns out that the root of the redirection to the user profile page, which meant that the AJAX response text was the code of that page, was some PHP code similar to the following, in one of my nodes:

if(!user_is_logged_in()){
   drupal_goto("user");
}

At first, this seemed odd because the node was in no way related to AJAX. To complicate the issue further, if the line was removed and then re-added once the node had  been updated, AJAX worked again... for a few hours.

Looking in the log, I noticed that just before the error returned Cron had run. This made sense - sort of  - because then I found that when I ran Cron manually it never completed but ended up on the user page, which can be explained by the fact that Cron would have evaluated the above code due to the fact that it runs as an anonymous user.

Here my answer falls down a bit because I'm not quite sure how this all affects AJAX. I'm assuming that it's due to caching and/or the fact that part of Cron indexes the site so therefore because Cron was being redirected the index was corrupt/incomplete. I don't have any solid evidence, but it can be backed up by the fact that before the site would only ever get up to being 82% indexed, but without that code it is now 100% indexed. If anyone would like to offer there thoughts on this answer however, please feel free to do as I really would like to confirm 'the missing piece of this puzzle'.

There are a few ways to avoid this issue. One would be to check to see if the script that is accessing the node is cron so that you know not to do any redirects (see here). However, the method I chose was to move this 'functionality' into a rule. I do so for many reasons, but most importantly because it is not recommended to use PHP codes in nodes at all and I think that this incident illustrates why.


I am trying to use AJAX with Drupal 6. How do I determine the URL I am trying to contact? I looked at the documentation here and it left me a bit confused. I don't need to access any files, I am just returning the date that is on the server to my Javascript code. (I don't want the date/time from the user's perspective)

The example gives this in the javascript portion of the example. This example seems to already know where get should call to get the response back. I am not sure what the URL would be on my server to just talk to my php code.

$.get('/photos/get/photos/' + parseInt(this.id, 10), null, imageDetails);
        return false;

The URL you use is the one that delivers you the data you want.  If you want to grab the server time you can create a short PHP script that gets the info and then make that info available to JS using Drupal.settings.

For example:

// Create the array that is required by drupal_add_js()
$server_time = array(
  'serverTime' => date("h:i:sa"),
);

// This is what makes the variable available to JS
drupal_add_js(array('time' => $server_time), 'setting');

Then, in your.js:

var time = Drupal.settings.time.serverTime;


Empty value , Contextual Filters This is my problem:
I have 3 contextual filters, 2 Content : Has taxonomy term ID and 1 Content :Updated month

if I write in the url : test.com/International/North/06

It will show all the articles update the 06  in the International + North category

But if i write test.com/International/06 or International//06 to show just the articles update the 06 in the International category it doesn't work..

How can hide or set an empty condition on the second contextual filter to access on the third ?

contextual filters doesn't necessarily know when something is incorrect - it assumes the values are accurate and attempts to use them as you have it setup. You could do it this way:

create a custom views handler, or install Views PHP

assuming Views PHP:

for the second filter, provide a default php value that evaluates the url - if only two arguments are provided assume the second is missing and return all

Of course, this is quite presumptuous on the url information provided to Views, and will inevitably fail in some situations. Depending on how you link to the view and create the url, you are probably better off using a place-holder for the second value (international/--/06), with a similar default value set up as above whereby if the place-holder is found, it would return all


How do I spawn additional instances with the same configuration? I have the following scenario:
I will develop an application based on Drupal.
Everything will be developed on a local instance.
Composer files, configuration and so on will be kept in a git repository.
The repository will be hosted on GitLab.
I will use the CI/CD features over there.
I will need one test instance.
The project starts with one production instance.
In the future, there will be additional production instances.
They all should have exactly the same configuration, but different content.
I already did something like this, where I copied the initial database from my local install to my test and production server.
Afterwards, my CI/CD scripts could load the configuration from git to the different instances.
But there, I only hat one production server.
If I remember correctly, configuration is bound to an ID of the initial database.
So, I can't just set up a new instance and load the configuration from the old one.
Since they all will have exactly the same configuration, I would love to have a develop branch for delivering to the test server and a master branch to deliver to all production servers. If there are better solutions, I'm also open for them.
What would be the best workflow to add additional instances in the future that use the same config and can receive updates from the same CI/CD?
Would this workflow be completely incompatible in the case that, somewhere in the future, one instance would start getting additional configuration?

Would this workflow be completely incompatible in the case that,
somewhere in the future, one instance would start getting additional
configuration?

If having one instance with divergent configuration is a concern, it is probably worth considering setting it all up as a distribution.
While rolling your own distribution may be overkill, this provides the most "future-proofing" long term because you will have a base configuration in the distribution that can be overridden on a per-site basis if it becomes necessary.
Rough documentation on configuration in distributions
With a distribution, in addition to default configuration, you can even include default content.


Allowing node creation/editing inside other node creation form I have a custom content type congress, and inside the congress creation form, I want to allow the user to create and edit as many nodes as he wants of the custom type event.

How can I accomplish that? I've seen it's possible to create a field for selecting an existing node with node reference and node connect modules, but those do not allow me to create or edit nodes.

If you're not opposed to using Entity Reference module as instead of node reference, there's the Inline Entity Form module that does what you want:

  Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.


Garbage values in From: in the email sent from Webform I find some garbage values in the from field of email sent from contact us page in webmail(as in the image From= field below in the top left in which "F" is cut-off by mistake). I've configured correctly as we do in D6.

I've also sent email from my webmail account from the same email account and it's ok.

This site is the latest version( 1 month old only).

Here I'm pasting what is seen in the image in text:

From: =?UTF-8?B?Ij0/VVRGLTg/Qj9RV1J0YVhOemFXOXVJRU52ZFhKelpYTWdTVzVrYVdFaElPQ2s=?=

This snapshot is from Thunderbird email client:

Looks like it is appearing from this(snippet from the email headers ):

........
X-Mailer: Drupal Webform (PHP/5.3.23)
From: =?UTF-8?B?Ij0/VVRGLTg/Qj9RV1J0YVhOemFXOXVJRU52ZFhKelpYTWdTVzVrYVdFaElPQ2s=?=
 =?UTF-8?B?cXVDbGplQ2tzT0NrdGVDbGgrQ2t0aURncEtvPT89CiA9P1VURi04P0I/NEtTKzQ=?=
 =?UTF-8?B?S1NnNEtXTjRLU3Y0S1NWNEtXTjRLU3c0S1N1SU9Da3JlQ2t2dUNrc09Da3BDRGc=?=
 =?UTF-8?B?cEs3Z3BZZmdwSUk9Pz0iIDxjb250YWN0dXNAYWRtaXNzaW9uY291cnNlcy5jb20=?=
 =?UTF-8?B?Pg==?=

I've Googled too but did not find any similar issue anywhere else.

Am I missing anything?

If you fill out the form and submit it does your message contain similar encoded data in the from field?

If not, then it's likely these are spam submissions.

Try adding Spamicide and/or reCAPTCHA to filter these out.


How to add a view mode caching dependency in my custom block? I have a block which renders fields of a node. The output of each field is controlled in the view mode settings of the node entity. Now, how can I add caching which is depended on the view mode settings?

Found it out :)

Using entity_get_display to actually load the display view settings of the current node and then just merge the tags:

<?php

public function getCacheTags() {
  if ($node = $this->getNode()) {
    $cacheTags = Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
    $display = $this->getEntityViewDisplay(); // function which uses entity_get_display
    $cacheTags = Cache::mergeTags($display->getCacheTags(), $cacheTags);
  }
  else {
    $cacheTags = parent::getCacheTags();
  }

  return $cacheTags;
}


Custom validate exposed filter on a view I have a view with a single exposed taxonomy field that requires the user to click apply before any results are shown.

The options in the list appear like this

Please Select (All label overridden with form alter, also the default option)
option 1
option 2

if the user clicks apply when please select field is highlighted I would like to show an error message rather than all of the results I have tried the following.

Form:

$form['#validate'][] = 'MY_MODULE_claims_validate';

Function:

function MY_MODULE_forms_claims_validate(&$form, &$form_state) {
  if($form_state['values']['user_category'] == 'All') {
    // $form_state['values']['user_category'] = 0;
    form_set_error('user_category', 'please enter a value');
  }
}

It does set a form error message but also throws the follwoing warning, it also does this on the first page load which I don't want it to do either.

Notice: Undefined index: nid in views_handler_field_term_node_tid->pre_render()

It throws this error the first time the page is loaded which is a

Another approach is to use hook_form_FORM_ID_alter() like other answers suggest, but to put custom validation before the default validation callback of views. By this way you can stop to step over to the second validation callback if validation fails, otherwise validation continues to process.. Example:

function MY_THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-MY_VIEWS_NAME_MY_VIEWS_DISPLAY') {
    array_unshift($form['#validate'], 'my_custom_validation_callback');
  }
}

function my_custom_validation_callback($form, &$form_state) {
  if(/* CONDITION */) {
    form_set_error('user_category', 'please enter a value');
  }
}


Enable a button basing on multiple form values being equal I would not like users to be able to submit a form until:

All fields are filled out
The password and confirm password fields are equal

I can do this with JavaScript, potentially, but then the JavaScript code would managing some states and the PHP code would manage other states. It seems messy.

This is the code I wrote.

'disabled' => array(
// disable button if missing required fields
        array(
          ':input[name="field1"]' => array('value' => ''),
        ),
        array(
          ':input[name="field2"]' => array('value' => ''),
        ),
        array(
          ':input[name="password"]' => array('value' => ''),
        ),
        array(
          ':input[name="confirm_password"]' => array('value' => ''),
        ),
      ),

      // only enable the button when passwords are ==
'enabled' => array(
        array(
          ':input[name="password"]' => array('value' => ':input[name="confirm_password"]')
        )
      )

'array('value' => ':input[name="confirm_password"]')

This means the value equals the literal string ":input[name="confirm_password"]".
As far as I know, #states can't check if the value of two fields are the same.

  I can do this with JavaScript, potentially, but then the JavaScript
  code would managing some states and the PHP code would manage other
  states. It seems messy.

Here is a way that may seem less messy. Use a hidden compare_passwords field whose value will indicate whether the password and confirm_password fields have the same value:

$form['compare_passwords'] = array('#type' => 'hidden', '#default_value' => 'fail');

Use the value of that field in the #states array for your button.

':input[name="compare_passwords"]' => array('value' => 'match')

Write some JavaScript that changes the value of compare_passwords whenever the value of password or confirm_password changes (use .on() instead of bind() if your site uses jQuery 1.7+):

var password_selector = ':input[name="password"]';
var confirm_selector = ':input[name="confirm_password"]';
var compare_selector = ':input[name="compare_passwords"]';
$(password_selector + ',' + confirm_selector).bind("change paste keyup blur", function () {
  if ($(password_selector).val() == $(confirm_selector).val()) {
    $(compare_selector).val('match').change();
  } else {
    $(compare_selector).val('fail').change();
  }
});

By the way, you can use '!value' to put all your "does not equal empty string" conditions under "enabled", using the Boolean "AND" structure. The Boolean "OR" structure, which is wrapping each condition in its own array, is harder to understand if you aren't familiar with #states.

// Only enable the button when all fields have a value and passwords match.
// The value in "compare_passwords" is dynamically updated by my_script.js
//  whenever the user types inside the password or compare_password fields.
$form['my_button']['#states'] = array(
  'enabled' => array(
    ':input[name="field1"]' => array('!value' => ''),
    ':input[name="field2"]' => array('!value' => ''),
    ':input[name="password"]' => array('!value' => ''),
    ':input[name="confirm_password"]' => array('!value' => ''),
    ':input[name="compare_passwords"]' => array('value' => 'match'),
  ),
);


diffrent theme for admin without use theme appearance config by default Drupal(7) use "page.tpl.php" for all(front and admin) pages.but I want use another file for example "page-admin.tpl.php" for admin layout.i don't want change admin theme in config/appearance.

Copy page.tpl.php to page--admin.tpl.php (note two hyphens) clear theme registry / all caches and should be good to go.


Views... two panes each contains a view.  One is the exposed filter, other is the fields.  How can they communicate? I have have two panes each containing a view.  But, these views are and exposed filter and it's fields/results.  How can I make these views aware of each other?  I want results of the exposed filtered view to be displayed in the other fields pane.

I'm assuming this would be done through relationships.

Exposed filters are only linked to the view they were exposed on.

I haven't done this before, but I think the correct method would be:

Create a view
Expose any of the filters you need to on that view (not a separate one)
In the advanced settings of that view, set "Exposed form in block" to yes
Add the block to your panel (not a separate views pane)


alternatives to media module? Are there any alternatives to the drupal media module for drupal 7?

Looking for functionality to preview and upload images and set the image style before displaying the image. Or would the media module be the best bet for this type of task?

Have you check the Scald module?
This is a real alternative in active development.

  Scald is a different take on how to handle media (audio, video, image or otherwise) in Drupal and beyond. It is a platform designed to make it extremely easy to implement the social features which are so essential -- and so unique -- to web communities. Additionally, Scald -- in tandem with the DnD module -- provides a novel and natural way for users to compose complex posts.

Feel free to ask me for details, or to put a issue in the module issue queue.


Multiple Ajax submit, same Form ID I have a page with a table of nodes each one with it's own submit button. When pressed the button should call a custom ajax function which creates a cookie with the corresponding orm ID as its value.

My code:

function custom_cart_form_alter(&$form,&$form_state,$form_id){
    if ((stristr($form['#form_id'], 'uc_product_add_to_cart_form')) != FALSE){
        $form['#submit'][] = 'set_custom_cookie';
    }

    return $form;
}

function set_custom_cookie($form, &$form_state){
    user_cookie_save(array($form['#form_id'] => TRUE));
}

However, when the set_custom_cookie() function is called it receives the last value of $form['#form_id'] and not the ID of the corresponding form.

To clear things up: if I add the following at the end of hook_form_alter() :

function custom_cart_form_alter(&$form,&$form_state,$form_id){
    if ((stristr($form['#form_id'], 'uc_product_add_to_cart_form')) != FALSE){
        $form['#submit'][] = 'set_custom_cookie';
    }

    $form['#form_id'] = "test123";  //Added this line to demonstrate the issue
    return $form;
}

then function set_custom_cookie() will receive "test123" on call as the value of $form['#form_id'].

How can I make set_custom_cookie() receive the corresponding form ID?

I'm using Drupal 7.

You should be able to get the form id from the $form_state variable as $form_state['build_info']['form_id'] inside your submit handler.


Where can I find the link between field answers and the user who submitted it? Noob here. I can't figure out how entity forms stores which user submitted each answer for it's fields on the database.

All I can see is a table for each field, and the columns within being: Entity_type, bundle, deleted, entity_id, revision_id, language, delta & Field_(the name of my field).

None of which tells me which user submitted each answer. Yet drupal and entity forms clearly knows which user submitted each answer, because when I go to (Administration > Structure > entityform types > my form > form submissions) I can see a table of every submission with the name of each user who submitted it, and I can see all their answers.

So where the heck is this being stored on the database? If it matters, my database was built with phpmyadmin.

Thanks in advance for your help, I really appreciate it. I'm sorry if my terms are all jumbled and wrong.

Look for "entityform" table - column "uid" gives you user id of the user who submitted the form.


How can I react when a commerce product is explicitly created via the UI? how do we add a submit handler in drupal commerce everytime a product is created.

I tried using the following code.

function custommodule_formid_form_alter(&$form, &$form_state, $form_id) {
    $form['#submit'][] = 'custom_submit_function';

    return $form;
}

function custom_submit_function() {
    print "<pre>";
    print_r($form_state);
    print "</pre>";
    die();
}

Is this the correct way?

I tested it, and actually managed to get the form submit new handler works, but the problem is after the form is submitted, I wanted to get the submitted data and manipulate it. It is not working out as the form data is all gone.

function custommodule_form_alter(&$form, &$form_state, $form_id) {
    $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  $value = $form_state['values']['field_data'];
}

If you're only wanting to respond do products created via the UI, then form submit handlers should work. As noted, this wouldn't work for products created by any other method.

The correct hook you should use is hook_commerce_product_insert(). This isn't documented, but it should be. Using this hook will ensure that no matter where the product gets added that the hook runs.

function MYMODULE_commerce_product_insert($product) {
  ...
}

If you're wanting to create 100 new products, you can still loop in this function but you'll just need to differentiate between products that are created and the one that you began looping by some particular method. This could mean, for instance that there is particular SKU format (e.g. all created products end in -XXX where XXX is some number and the one created via the UI does not) or some extra field (e.g. field_parent_product that is empty on the one created in the UI but isn't on the sub-products). It's then trivial to both skip products that have a non-empty field, but also be able to handle updates or deletes down the road.


how to show views for particular language I have simple problem - there is a view that is aggregating some info and it has a link in the main menu. I'm also using i18n and would like to have that particular view only in one language, but it looks like that it's impossible to make it - I can't find any option how to make the view just in one language - the main menu item appears in both languages and I can't figure out how to disable it.
I'm using D7 and newest Views.

Have you tried to use filters? When you create your view, you add a new filter and select "Node translation" from the "Groupes" list and the check "Node translation: Language" and click "Add". Then you can chose language(s) on which you want the view to show


How to execute jQuery on body elements? I'm screwing around with jQuery for the first time, and I'm unsure of where to add a call in Drupal to allow it to alter classes of elements within the body tag.

I'm looking at utilizing something like the following:

$('header').toggleClass('Scrolling', $(document).scrollTop() > 0);

Without any custom modules at this point, the only robust method I have available seems to be using my custom theme. I've included a script in my custom theme's .info file:

scripts[] = scripts/mine.js

Within that file I've added a test script:

(function($) {
  var e = document.getElementsByTagName("body");
  alert(e.length);
  for (var i = 0; i < e.length; i++) {
    alert(e[i]);
  }
})(jQuery);

The result is an empty array. When I change "body" to "html", "head" or "script", I get an array populated with HTML objects. This leads me to believe that because the script is included in the header of the HTML page, it doesn't have access to body elements, as they haven't been loaded yet.

What am I missing that would allow this type of script to interact with body elements, and therein let me add a class to an element via my first line of code?

If your question is "How do I add theme javascript to the footer instead of the header?", I have this snippet in my starter theme's template.php file:

/**
 * Add a custom, theme-specific JS file. Added here so it can be placed in the
 * footer instead of the header which is where the info file places JS.
 */
$options = array(
  'type' => 'file',
  'scope' => 'footer',
);
drupal_add_js(drupal_get_path('theme', 'bootstrap_starter') . '/js/theme.js', $options);

Change bootstrap_starter to the name of your theme and make sure the folder js contains a file named theme.js within your theme folder.

See drupal_add_js() for more info.


How can I get the active menu trail for the current page? If I use Drupal::menuTree() to load a menu it seems to always have inActiveTrail set to FALSE for all my items.

As an example consider the following code:

$menu_tree = Drupal::menuTree();
$parameters = new MenuTreeParameters();
$parameters->setTopLevelOnly();
$main_menu_top_level = $menu_tree->load('main', $parameters);

That code returns the top level of the main menu with inActiveTrail = FALSE for all items regardless of what page I am on.

I believe MenuTreeParameters::setActiveTrail() is meant to help here but then I have to pass in an active trail.

How do I get the active menu trail for the current page load so I can then pass it in?

MenuLinkTreeInterface::getCurrentRouteMenuTreeParameters() is what you want. To use the example above:

$menu_tree = Drupal::menuTree();
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters('main');
$parameters->setTopLevelOnly();
$main_menu_top_level = $menu_tree->load('main', $parameters);

The resulting menu tree should have inActiveTrail flagged.


Webform depending on Select List - Number of delegates Webform 4.x

On a Webform booking form how would one add the functionality where from a dropdown list of number of delegates (1,2,3...) would then add the necessary number fields on the form. So if 1 was selected from a list then only 1 set of fields is presented, but if 2 is selected from the list then 2 set of fields is presented.

For example:

Booking Contact Name: Booking Email address: Number of Delegates:(Select options: 1,2,3,4,5...) Number 2 Selected!

Delegate Name: Delegate Date of Birth:

Delegate Name: Delegate Date of Birth:

I would create conditionals. E.g. if Number of Delegates is 2, then show the second pair of fields. If it is 3, show the third...

You can consider this solution if the number of delegates is limited.


how to give parameters in url for getting json parse for both taxonomy terms AND nodes i created 2 nodes in Company CCK under taxonomy A, 2 nodes in Company CCk under taxonomy B. now i want to get a json parse for all the nodes in a taxonomy A.

I tried like this www.mywebsite/api/taxonomy_term?selectNodes&parameters[tid]=1 it gives the value of that taxonomy term but, i wont get nodes under that category . In what way the url  should be framed for attaining values of nodes of a particular category(taxonomy) i.e i would like to filter the nodes of my choice.

so any one help me, Thanks in advance

you can use taxonomy_select_nodes to find all nodes associated with a term.

Return nodes attached to a term across all field instances.

Parameters

$tid: The term ID.

$pager: Boolean to indicate whether a pager should be used.

$limit: Integer. The maximum number of nodes to find. Set to FALSE for no limit.

$order: An array of fields and directions.

API


What extensions are used in a module, and what do they mean? I suppose there's a drupal page somewhere that explains this, but I can't find it.

When creating a module, you can have files that end with .module, .info, .inc, etc...

What are all the file extensions that are recognized and what do they do?

The extensions that are specific for Drupal, or that have a specific meaning in Drupal, are the following ones:

The .api.php extension is used for the file describing the hooks used by a module, such as system.api.php.
The .install extension is used for the file that is used when a module is installed, such as system.install. It is also loaded when Drupal is verifying the requirements needed from a module.
The .inc extension is used for any secondary file that contains code that is loaded only when necessary. If the code is used in specific cases, such as when a specific menu callback is being invoked, then the code is moved in a separated .inc file. Often, you will find modules using a file with the .admin.inc extension (e.g. node.admin.inc) that includes all the code necessary to run the administrative interface, and a file with .pages.inc extension (e.g. node.pages.inc) that contains the code executed for other menu callbacks. If a module implements tokens, in Drupal 7 you will find files using .tokens.inc as extension (e.g. user.token.inc); those are the files where the implementations of hook_token_info(), and hook_tokens() are looked for (see system_hook_info()).
The .info extension is used for the file describing the module, or the theme, such as system.info. It contains metadata, such as the required Drupal version, the minimum PHP version with which the module/theme is compatible, and other information specific for the module, or the theme.
The .module extension is used for the main file of a module, such as system.module.
The .test extension is used for the files containing the testing code (e.g. system.test), which is actually running on the SimpleTest framework.
The .theme extension was used from themes not using PHPTemplate template engine. In Drupal 6 (and before) the extension was used from the chameleon.theme file; in Drupal 7, there aren't themes using that extension.
The .tpl.php extension is used for the template files used from theme functions, such as node.tpl.php.

Third-party modules can use specific extensions, such as the following ones:

The .views_default.inc extension is used for files (e.g. node.views_default.inc) containing the code to implement the default views used from a module that integrates with the Views module.
The .views_template.inc extension is used for files (e.g. node.views_template.inc) containing the code for views templates.
The .rules.inc extension is used for files containing code for integrating with the Rule module.


Does drush fire hook_exit() I am trying to write my own drush command. I have a hunch that something is not quite working right. I can't see documentation saying whether drush fires hook_exit()

Anyone know this?

Judging by grep -R exit * in the drush folder, I think not. However, there is hook_drush_exit(), see docs/drush.api.php.


Custom widget field only saves first letter, disappears on edit I'm trying to create a custom module for Drupal 7 that makes two widgets available for Text fields. They autocomplete from a database table using #autocomplete_path. The autocomplete works fine and when a match is selected it is made the value for the field, but when the node is saved only the first letter from that field is shown. Then when the node is edited, the field comes up blank in the edit form.

Here's my module code:

<?php
/**
 * Implements hook_menu().
 */
function autocomplete_jsb_users_menu() {
    $items['jsbu/speaker/autocomplete'] = array(
        'page callback' => 'jsbu_speaker_autocomplete',
        'access callback' => TRUE,
        'weight' => 1,
    );
    $items['jsbu/venue/autocomplete'] = array(
        'page callback' => 'jsbu_venue_autocomplete',
        'access callback' => TRUE,
        'weight' => 2,
    );
    return $items;
}

/**
 * Implements hook_field_widget_info().
 *
 * Two widgets are provided.
 * - A textfield Speaker name autocomplete widget.
 * - A textfield Venue name autocomplete widget.
 */
function autocomplete_jsb_users_field_widget_info() {
    return array(
        'autocomplete_speaker_name' => array(
            'label' => t('Autocomplete Speaker Name'),
            'field types' => array('text'),
        ),
        'autocomplete_venue_name' => array(
            'label' => t('Autocomplete Venue Name'),
            'field types' => array('text'),
        ),
    );
}

/**
 * Implements hook_field_widget_form().
 */
function autocomplete_jsb_users_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    // set the default text instance
    $element += array(
        '#type' => 'textfield',
        '#size' => $instance['widget']['settings']['size'],
        '#maxlength' => $field['settings']['max_length'],
        '#attributes' => array('class' => array('text-full')),
    );

    if ($instance['widget']['type'] == 'autocomplete_speaker_name') {
        $element['#autocomplete_path' ] = 'jsbu/speaker/autocomplete';
    } else if($instance['widget']['type'] == 'autocomplete_venue_name') {
        $element['#autocomplete_path' ] = 'jsbu/venue/autocomplete';
    }

    return $element;
}

/**
 * Implements the autocomplete_jsbu_speaker() callback.
 */
function jsbu_speaker_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_speaker_name', 'sn');

    // Select rows that match the string
    $query
        ->fields('sn', array('field_speaker_name_value'))
        ->orderBy('field_speaker_name_value', 'DESC')
        ->distinct();

    $result = $query->execute();

    // add matches to $matches
    foreach ($result as $row) {
        $matches[$row->field_speaker_name_value] = check_plain($row->field_speaker_name_value);
    }

    // return for JS
    drupal_json_output($matches);
}

/**
 * Implements the autocomplete_jsbu_venue() callback.
 */
function jsbu_venue_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_venue_name', 'vn');

    // Select rows that match the string
    $query
        ->fields('vn', array('field_venue_name_value'))
        ->orderBy('field_venue_name_value', 'DESC')
        ->distinct();

    $result = $query->execute();

    // add matches to $matches
    foreach ($result as $row) {
        $matches[$row->field_venue_name_value] = check_plain($row->field_venue_name_value);
    }

    // return for JS
    drupal_json_output($matches);
}

Any ideas? Thanks!

It may help to just wrap the returned array from the _field_widget_form in yet another array

return array('anything' => $element);

Worked for me ;)


Poll module for blogs I have a blog that needs a poll attached to it.  I've looked at a few modules, but they seem to be buggy.

Any suggestions on a good poll module or methodology?

I've been using the Advanced Poll module, and it seems to handle what I need.  It lets you display the poll as a block, but doesn't have an option to get rid of the author info.  It looks like the best one so far.


How to disable javascript validation of html5 URL element? The LinkWidget uses a URL render element, which behaves differently in different browsers.  In chrome, there is annoying pop-up, which is out of character with other validation within Drupal where there is an error message at the top of the page and a red border added to the form element.

In order to gain more control over the validation, I'd like to do away with the javascript (i.e. HTML 5) validation.  There are various suggestions using javascript or CSS, but they are heavy handed as the most effective method is to set the "novalidate" parameter on the entire form, which loses the benefit of validation on other html 5 elements such as email or dates.

What is a good way to turn this off for link fields that are set to accept external links?  (If you also accept internal links, this doesn't happen).

One way to do this is to simple not use the URL render element.  You can still use its validation, but you replace the URL element with a textfield element.

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getType() == 'link') {
    $settings = $context['items']->getFieldDefinition()->getSettings();
    // If external link, don't use HTML5 URL element, to prevent its annoying
    // pop-ups.  Use a textfield with the backend validation from the URL element.
    if (!empty($settings['link_type']) && $settings['link_type'] == 16) {
      $element['uri']['#type'] = 'textfield';
      array_unshift($element['uri']['#element_validate'], ['Drupal\Core\Render\Element\Url', 'validateUrl']);
    }
  }


Remove "Submitted by" on search results How can I modify the search results on drupal 7 so that the submitted by author and date doesn't appear?

Try below code in your template.php

<?php
  function YOURTHEME_preprocess_search_result(&$variables) {
  $variables['info'] = '';
  }
?>

Or create a template file for search results if not there  named "search-result.tpl.php" and add this

<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
 <h3 class="title"<?php print $title_attributes; ?>>
   <a href="<?php print $url; ?>"><?php print $title; ?>

 <?php print render($title_suffix); ?>

  <?php if ($snippet): ?>
    <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

<?php endif; ?>
<?php if ($info): ?>

<?php print $info; ?>

<?php endif; ?>

and To remove the author, date and comments count remove or comment out the following lines:

<?php if ($info): ?>

<?php print $info; ?>

<?php endif; ?>

and in css

.search-info {
display: none;
}

Taken answer from this link


Views caching strategies - relationship between query cache and rendered output cache First off, I'm trying to ensure due diligence and not duplicate questions that have come up before. There are numerous posts on stackexchange, and various other places, that discuss views caching and even some specifics about the different types of view caches (e.g., here and here). However, I've yet to find any details that sufficiently explain the relationships between different layers of views caching, and how they may impact case-specific caching decisions. For simplicity I'm also focusing the scope of this question to out-of-the box views 7.x-3.x caching options independent of other layers offered in the contrib space.

Views exposes 2 layers of time-based caching for each display, a "query results" cache and a "rendered output" cache. The specifics of what raw data each cache encompasses is clear, but the ways they interact is not. I'm specifically wondering if a hit on the rendered cache will completely bypass they query cache, or if the 2 layers operate separately. I've seen some references that claim the former (like this one), and some that claim the latter (like this one).

Theory 1 - Separate cache layers

I was initially under the impression (and hoping) that each layer is invoked separately "in series", and that the rendered output cache hashes the actual query results within its cids. This way I would have an elegant way to cache the most expensive post-query load/build work, while still ensuring that new content is immediately reflected in the view ("query results" cache off and "rendered output" cache on). Some quick tests reveal that this might not be possible though, as the rendered output cache may not be aware of the current query results.

Theory 2 - Rendered output cache "encompasses" query results cache

The other possibility is that the rendered results cache is keyed by a hash of the query itself (not the results). If this were the case, a hit on it could return the rendered output directly, without the need to consult the query cache, or DB. If this were the case then I suppose it would not make much sense to have the "query results" cache set with a time interval less-than the "rendered results" cache. The advantage of course would be that one could refresh the rendered output more frequently (if they have lots of dynamic theme logic, or frequent entity updates), while still avoiding direct queries to the DB. However, for all but the most complex view queries, this kind of separation does not seem all that advantageous.

I've done some "black box" tests that point to theory 2, but I'm not sure if there are some other settings that might be at play or if the answer differs by views version. I've also explored the code a bit, but I find it frustrating that most views' plugin methods are undocumented and occasionally hard to follow. No matter what, I think the answer to this would be useful to have as a reference for others.

I looked into some of the internal views logic, and from what I can there are elements from each theory that are correct, but neither is 100% accurate. It seems that both caching layers are separate, and always checked in series, so the "rendered output" cache does not really have the ability to "bypass" the query layer. Additionally, the query results do not factor-in to any cache keys, so changes to query results unfortunately do not trigger a refresh in the rendered output.

7.x-3.x

The "query results" cache is managed in view::execute() and the "rendered output" cache is managed in view::render(). Because execute() is called before the "rendered output" cache logic, a "rendered output" cache hit cannot bypass the query layer. It's not totally clear to me why this is as seems a little wasteful to run a query, or even check a query cache, if the display will just be built in-full from a cache. I suspect that there is plenty of other logic in view::execute() (access checks, hooks, plugin management) that must always be run independent of caching, and the "query results" cache part could not easily be separated from it. Anyway, that detail is a bit tangent to the question, but maybe someone else would be able to comment on it.

In terms of cache keys both cache layers are keyed by the view name, the display name, the cache type and then a hash of a bunch of contextual "stuff" from views_plugin_cache::get_cache_key(). A look at this get_cache_key() method is insightful as it shows that a some common contextual data is always factored-in (user roles, language, base_url), but the "rendered output" case takes things a bit further by also hashing the raw query string, but not the query results. So if the raw query changes, the rendered output will be refreshed, but if the query results change, the rendered output will still be returned from cache.

So I think that from a performance perspective each cache layer can really be dealt-with independently, but the "rendered output" cache will still most directly govern how often "stale" data is displayed. I could further conclude that:

The refresh interval for the base list of items in the view is greater-than-or-equal-to whichever cache interval is larger (the actual list of items can't update until both caches expire for any given view).
If the "rendered output" cache for a given view refreshes before the "query results" cache, the list of items won't refresh, but the content displayed for each item could (i.e. a new item added to the list 5 seconds ago still won't be shown, but teaser text that was updated 5 seconds ago on an item that was in the list previously would update).
Even when the "query results" cache is not influencing the final output it still offers a performance boost for view::execute().

It's also worth noting that some of this behavior could be changed by overwriting methods in the views_plugin_cache class locally, such as views_plugin_cache::get_cache_key().

8.0.0

As of 8.0.0-beta7 views (core) retains the option for time-based caching. As best I can tell it will behave like 7.x-3.x but it's really too early to do any conclusive testing - see this meta discussion. What is clear however is that many of the concerns and limitations around views time-based caching may become moot, as it looks like D8 views will also support tag-based caching.  This should offer a way for truly smart expiration of cached data.


How to create multi-value, multi-bundle entity reference fields in code? I'm looking for example code that demonstrates creating a new entity reference field with multiple values, referring to multiple different bundles.

Sorry for the long code dump but there's really no other way to do this:

field_create_field(array(
  'translatable' => '0',
  'entity_types' => array(),
  'settings' => array(
    'target_type' => 'node',
    'handler' => 'base',
    'handler_submit' => 'Change handler',
    'handler_settings' => array(
      'target_bundles' => array(
        'article' => 'article',
        'page' => 'page',
        'webform' => 'webform',
      ),
      'sort' => array(
        'type' => 'none',
        'property' => 'nid',
        'field' => 'body:value',
        'direction' => 'ASC',
      ),
      'behaviors' => array(
        'views-select-list' => array(
          'status' => 0,
        ),
      ),
    ),
  ),
  'storage' => array(
    'type' => 'field_sql_storage',
    'settings' => array(),
    'module' => 'field_sql_storage',
    'active' => '1',
    'details' => array(
      'sql' => array(
        'FIELD_LOAD_CURRENT' => array(
          'field_data_field_entity_reference' => array(
            'target_id' => 'field_entity_reference_target_id',
          ),
        ),
        'FIELD_LOAD_REVISION' => array(
          'field_revision_field_entity_reference' => array(
            'target_id' => 'field_entity_reference_target_id',
          ),
        ),
      ),
    ),
  ),
  'foreign keys' => array(),
  'indexes' => array(
    'target_id' => array(
      'target_id',
    ),
  ),
  'field_name' => 'field_entity_reference',
  'type' => 'entityreference',
  'module' => 'entityreference',
  'active' => '1',
  'locked' => '0',
  'cardinality' => '-1',
  'deleted' => '0',
  'columns' => array(
    'target_id' => array(
      'description' => 'The id of the target entity.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
  ),
  'bundles' => array(
    'node' => array(
      'page',
    ),
  ),
));

The target_bundles in the handler_settings is where you assign the different bundles, and the cardinality of -1 ensures unlimited values for the field.

In case you're interested, this is the code that allowed me to build the above definition from an existing entity reference field (which seems to have originated at this blog post):

$entity_type = 'node';
$field_name = 'field_entity_reference';
$bundle_name = 'article';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

It's a handy little script; I'm sure I've posted it somewhere here before but I can't find it at the moment.


How to get group id from custom url I have some more custom url with og group id like

www.example.com/students/6593
www.example.com/results/6953
www.example.com/book-listing/5367/6953

here 6953 is a group id.

these are the sample link. my questions is how to get the group id from url? And i can't use arg(). because i have more no of url and group id position also varied.

There is any robust solutions for this.

I have used the following code in hook_preprocess_page() to solve this issue.

$url = current_path();
  $arguments = explode('/', $url);
  foreach ($arguments as $value) {
    if (is_numeric($value)) {
      $node = node_load($value);
      if (og_is_group('node', $node)) {
        drupal_set_message('group id :' . $node->nid);
      }
    }
  }

From now, i can set to group member only could see this page.


How to change Date format without diving to core? I want to convert dates to Jalali format. The problem is I have to change some of the core files in /includes and /modules. Is it possible to do this without jumping right into the core?

I think your best bet is Calendar_Systems module that will not do the core changes but everything else needed on the frontend.


Importing database: Duplicate entry 'X' for key 'PRIMARY' I used this script to backup Drupal database from PHP - http://davidwalsh.name/backup-mysql-database-php , but removed all "DROP TABLE" stuff to be able to import it to empty database. However, when I'm doing

  mysql -u user -p database <
  db-backup.sql

I'm getting error "ERROR 1062 (23000) at line 18512: Duplicate entry 'xxx' for key 'PRIMARY'". This is about cache_path table, and specific path. I don't know how often it can happen but I'm wondering, what could cause it, and how handle it, in the best way.

The line that causes error looks like this:

  INSERT INTO cache_path
  VALUES("some/path","a:39:{i:0;s:8:\"node/432\";i:1;s:8:\"node/505\";i:2;s:8:\"node/475\";i:3;s:8:\"node/278\";i:4;s:8:\"node/424\";i:5;s:8:\"node/351\";i:6;s:8:\"node/332\";i:7;s:8:\"node/452\";i:8;s:8:\"node/382\";i:9;s:8:\"node/329\";i:10;s:8:\"node/181\";i:11;s:8:\"node/257\";i:12;s:8:\"node/274\";i:13;s:8:\"node/446\";i:14;s:8:\"node/182\";i:15;s:8:\"node/294\";i:16;s:8:\"node/183\";i:17;s:8:\"node/437\";i:18;s:8:\"node/184\";i:19;s:8:\"node/421\";i:20;s:8:\"node/192\";i:21;s:8:\"node/259\";i:22;s:8:\"node/414\";i:23;s:8:\"node/396\";i:24;s:8:\"node/375\";i:25;s:15:\"taxonomy/term/1\";i:26;s:20:\"taxonomy/term/1/feed\";i:27;s:7:\"node/29\";i:28;s:6:\"node/5\";i:29;s:7:\"node/30\";i:30;s:7:\"node/25\";i:31;s:7:\"node/26\";i:32;s:7:\"node/27\";i:33;s:7:\"node/28\";i:34;s:8:\"node/304\";i:35;s:6:\"node/4\";i:36;s:6:\"node/1\";i:37;s:6:\"node/2\";i:38;s:6:\"node/3\";}","1377033251","1376946851","1");

but removed all "DROP TABLE" stuff to be able to import it to empty database

That's where you went wrong. Leave the database dump file exactly as it is, and then import it.

mysqldump adds DROP TABLE IF EXISTS by default, so unless you've specifically told it not to do that, the changes you're making are redundant, even incorrect.

It's a good idea to truncate the cache_* tables before running the data export. That way you don't get lots of ephemeral data in your backup, and exports/imports are quicker. I don't know if it will solve your current problem (if you have no duplicate errors elsewhere in the SQL script then it probably will), but either way it's a good habit to get into.


Saving a field of type 'text_format' as a theme settings variable I try to add a text area with wysiwyg editor in the theme setting.

If i use '#type' => 'textfield', it works :

If I use '#type' => 'text_format', the text is saved but i don’t see it as default value :

If I revert back to '#type' => 'textfield', i can see this :

I guess it is related to the text_format form which is stored as an array ?

How can I use text_format in theme settings ?

Full code in mytheme.theme

function MYTHEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {

  $form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => theme_get_setting('mytheme_texte_presentation'),
    '#description'   => t("lorem ipsum"),
  );
}

Text format fields are considered to be a compound field (meaning that multiple values are stored for the one field -- the value and the format).

If you inspect the value of mytheme_texte_presentation, you'll find an array that looks something like this array => ['value' => '<val>', 'format' => 'html_restreint'].

If you look at the docs for text_format, you'll see that there is a #format attribute.

Your code should look something like this:

$texte_presentation = theme_get_setting('mytheme_texte_presentation');
$form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => $texte_presentation['value'],
    '#format'        => $texte_presentation['format'],
    '#description'   => t("lorem ipsum"),
  );

Note: This is untested code. You may need to tweak this a bit to make it functional.


Alternative to Google Adsense content injector module I want to "float" ads in the top right of my nodes for which Content Injector was nice enough in D6 moreover such ads convert well in my experience.

But for D7 is there any easy alternative? I know I can sub-theme and place the ads in appropriate positions.

It might not be quite as versatile, but the Block Inject module will allow you to embed adsense blocks within the node body.


How do I remove the arrows from the breadcrumbs? How do I remove ">>" from the breadcrumbs?

I need to remove those characters because in my site, the breadcrumbs appear like in the following screenshot.

This is the code that generates the breadcrumbs.

$temp = "" . $title . "
";
$breadcrumb = str_replace("
", $temp, $breadcrumb);
print($breadcrumb);

You can override theme_breadcrumb() function in your theme. As mentioned in the below code.

function yourthemename_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '
' . t('You are here') . '
';

    $output .= '
' . implode(' » ', $breadcrumb) . '
';
    return $output;
  }
}

Just write above code in your template.php and change >> to whatever you want.


Grant access to CCK referenced nodes I have one content type 'object' that references one or more nodes of content type 'image'.
I'm granting access to nodes with TAC Lite: a user can view only content with a particular term.
Since the term is present only in the 'object' content type, the images referenced are not displayed in the node page.
How can I grant view access to all referenced nodes?

I've tried with Node access node reference, but it grant access to the parent node if the user has access to referenced nodes.

You could dynamically add the the same tag to the referenced image nodes when the 'object' node is created (or updated). To do this, you'd implement hook_nodeapi() and check the $op parameter for either "insert" or "edit" (depending on when you want this operation to happen). Then you can pull out the node id's of the 'image' nodes being referenced and apply the terms. This way they have the same taxonomy based permissions at the 'object' node.

There may be other ways, but this seems like it should work for you. I actually do the same thing to set a CCK node reference value during creation. I don't have access to a coding environment right now, or I'd add code snippets.


get node by address field and part of name I have a content type which have a name field and address field.

I want to retrieve programmatically all the nodes in a specific city and wich contain in his name one or many keywords.

For example i want to search in "Paris" the node wich contain in name the word "beautiful" and/or "shop". Then i can retrieve theses results :
- "My beautiful shop of candies" in "Paris"
- "Fast shop" in "Paris"

The problem is that i don't know how to get nodes by a word containing in :/

Here is my current code :

$query  =  new EntityFieldQuery();

$entities  =  $query->entityCondition( 'entity_type', 'node' )
    ->propertyCondition( 'status', 1)
    ->fieldCondition( 'field_adress', 'locality', 'Paris', 'like' )
    ->fieldCondition( 'field_name', 'value', array('beautiful', 'shop', 'money') )
    ->execute();

dsm($entities);

I tried to change :

->fieldCondition( 'field_name', 'value', array('beautiful', 'shop', 'money') )

to

->fieldCondition( 'field_name', 'value', array('beautiful', 'shop', 'money'), 'CONTAINS' )

but I get this error :

  Warning : addcslashes() expects parameter 1 to be string, array given
  dans DatabaseConnection->escapeLike() (ligne 984 dans
  /Applications/MAMP/htdocs/fritr/includes/database/database.inc).

You could do this by building the query up in smaller chunks and using a loop to add the field conditions for the mulitple words .  I'm not sure how of how you'll be passing the data in but say you have an array of words in $words.

$query = new EntityFieldQuery();
$query-->entityCondition( 'entity_type', 'node' )
    ->propertyCondition( 'status', 1)
    ->fieldCondition( 'field_adresse', 'locality', 'Paris' );

foreach ($words as $word){
   $query->fieldCondition('name', 'value', $word, 'CONTAINS');
 }

$result = $query->execute();

This code isn't tested and I've written off the top of my head. https://api.drupal.org/api/drupal/includes!entity.inc/function/EntityFieldQuery%3A%3AfieldCondition/7.x


"messages status" div not showing up when submitting page comment "messages status" div not showing up when submitting page comment.

It's just a regular old page content type and "messages error" div shows up fine in same place... when I try to submit a comment and leave something blank.

But, if I fill everything in, then the comment goes through and shows-up, but it doesn't get me the expected "messages status" div (the div tag doesn't show-up there at all.)

After successfully submitting a comment, it goes to a URL something like this:
http://mywebsite.com/pages/2013/april#comment-4563

page.tpl.php - Looks good:  <?php print $messages ?>

It should say something similar to what another Drupal 6 site of my says:

  Your comment has been queued for review by site administrators and
  will be published after approval.

Someone else set the site up, so I have no idea when it stopped working... I'm going thru opening permissions and disabling various modules...

Does anyone have any clues or answers on why this would happen?

Any help, would be greatly appreciated... Thanks in advance!

I would look at the following permissions:

to see what is going on.  On first blush, I'm going to assume post comments without approval is checked for more roles than you want or expect.

You can also surf over to admin/content/node-type/CONTENT-TYPE and click on "Comment settings" to see if anything is set for that specific type of node.

If these don't give you any "AHA!" moments, look around to see if any other comment approval modules are in place on the system.

Also, a lot of page.tpl's in D6 wrap their various content areas with something like this:

<?php if ($messages): ?>
  <div id="messages">
    <?php print $messages; ?>
  </div>
<?php endif; ?>

which basically means if you don't have any content for that area, there is no need to print an empty <div> which probably explains why you aren't seeing anything (eg, there was no message in the first place).


How to set up the following newsletter My nodes are broken down by taxonomy, each taxonomy term comes with a different icon, I need to set up a newsletter that sends out a title, teaser and the right icon for each node. What is the easiest way to achieve this? Simplenews? ePublish? Do either of these modules easily integrate with Views so I can output the right fields?

Newsletter can do what you need. The description on the project page:

Multiple newsletters lists configurable on existing terms
Plain text or HTML out of the box.
Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
Centralized administration and configuration on a single page.
Users can customize the terms in the list they subscribe to.
Custom template per list.
Statistics (CTR and Open-Rate).
Drupal 7 only.

I'm using it on my site and it works like you've mentioned.


How to use Solr Index to display node in a Google Map For several months I am wondering how to achieve this task.

I want to display information from Solr index (preferably Search Api Solr ) directly in a map. The main goal is to have a map where is displayed some nodes, and to have the ability the use facet filters and fulltext filter.

Exactly the same as a typical use of  Search Api Solr (example: http://ygerasimov.com/ajaxified-solr-search-drupal-search-api-views-panels) but using a map instead of a table.

Something like this: http://vps10937.ovh.net/x/map/node, but with Solr features. This page is part of the Location Module and the Gmap Module.

Here is two examples (not drupal) close to what I want to do:

http://www.trulia.com/for_sale/New_York,NY/x_map
http://www.conflicthistory.com/#/period/1495-1500

Thank you

I have been able to accomplish this task following these steps:

Installed modules for search: search_api, search_api_location, search_api_solr
search_api_views, search_api_facetapi, Search API location views
Installed modules for "geosearch": geofield (to store lat, lon...), addressfield (make it easier for users to enter an address and don't worry about geolocation).
Installed modules for mapping: leaflet, leaflet_more_maps (for more maptiles options out of the box).
Solr server 4.7.1 (I've just downloaded today)

So, with all these things, my goal is to have a view with an exposed full text field and show the results in a map (and afterwards be able to facet this view).

I've started like this:

Create a content type with address field and geofield fields
Set geofield field widget to "Geocode from another field" (and geocode from Address field using google geocoder). Not multivalued fields allowed here.
Create a solr server and make sure it runs ok.
Create an index connecting with the solr server (Remember this name for later)
Add fields to the index, just making it simple:

a) nid

b) title

c) Save changes

d) Add related fields (collapsible fieldset right bellow save button)

e) We choose "Geofield" (Watch out here, if you share the geofield field between
two or more different content types, you need to add this field twice or more and it is not easy to distinguish them because they have same name in the UI)

f) Now we have added geofield as related field, we should have the option to choose "Geofiled » LatLong Pair" and as type "Latitude/longitude" as a field for indexing in solr
Disable the index, disable the server, enable the server and enable the index,
and some clear cache between them. Important to do this.
Once we have server and index enabled, just index all items.
If we now go to the solr interface, and run a query for all results, we should see
a field (among the others we have indexed) which is called something like "locs_your_field_name$latlon" (Notice here that older versions use ":" instead of "$" ). If you can't see it, review before steps.
Now we can set up a simple view:

a) Create a new view

b) Set up a name and description for the view

c) Select "Show" (content is default, we want to change this): The name of the index that you set before, Remember?

d) Create a page: "myviewpath"

e) Save

f) Select fields: "Indexed Node: Node Id" and "Indexed Node: Geofield"

g) Filter criteria: "Search: Fulltext search" -> Exposed filter

h) Format: Unformated list

i) Test and see if we have results, if not, something went wrong, review.

j) Format (again): "Leaflet Map"

k) Data Source: Indexed Node: Geofield

l) Title field: Indexed Node: Nid

m) Description: Indexed Node: Nid

n) Map: Choose from list the one you like the most

o) Map height: 400px

p) Save format

q) Save view. At this point, the map is not visible (in views UI), but if everything is ok...
Go to the path of your view: You should see all results in the map (if you have the default solr server configuration). If not, try to type some text and see if you get the expected results...

Hope this helps!


View Table grouping on Taxonomy terms I am having trouble grouping a view table style on taxonomy terms.  It is rendering like

TAGS: tall
ITEM        TAGS
One         tall
Two         tall
Four        tall

TAGS: tall, soft
ITEM        TAGS
Three       tall, soft
Three       tall, soft

and I would really like it to render

TAGS: tall
ITEM        TAGS
One         tall
Two         tall
Three       tall, soft
Four        tall

TAGS: soft
ITEM        TAGS
Three       tall, soft

Drupal7, by the way.

I've had this problem before too!  Very annoying.  ;-)  The reason that happens is that, by default, the list of tags are displayed as a comma-separated list when the node is tagged with more than one term.  The way you can change that settings in your view is to click on the field that is your term in the Fields section of the view and expand the 'Multiple field settings' which should exist for this field (since it's an input field that accepts multiple values.

In your case, it would be best to select that only the first value is displayed like so:

That should work for you.  You'll see that the content type will still appear under all of its categories if it is tagged with multiple tags, but they won't be grouped in long lists with commas.  :-)

Let us know if this works!


How to use the Features module in a 3 dev environnement? Working on a project,  making heavy use of Features, there is sometimes 3 devs for this application.

We have tried a few approaches, but when we merge our git branches it seems we often 'over-write' each other's feature changes.  Conflicts abound, breaking the feature module making it painful to use, it seems.

Features is really an awesome timesaver for configuration for one on projects, and I am quite sure there is a way to tackle this.

Is there a workflow or procedure that reduces risks of conflicts and overwrites?

Any clues on features is welcome.

Welcome to the land of Features Configuration Management, aka FCM! It is not only about Features, and not about Configuration Management (as introduced in Drupal version 8). Instead, it is a special case of Software Configuration Management, aka SCM. Mostly because Features can be considered as a code generator, whereas that generated code needs to be migrated through multiple environments. Read on for more details.

1 - Pros and cons of using Features

Advantages of using Features

Automate the deployment of changes applied to a Drupal development site to one or more target Drupal (pre-) production sites (instead of manual deployment).
Facilitates sharing (shipping) of ongoing Drupal development between Drupal developers / site builders (eg to make some View(s) created by a views expert available to a Drupal Themer working in another development site to theme that view).
Great integration with both GIT and Drush for shipping a copy of the code generated by Features (on the development site) to selected target (pre-) production sites.

Disadvantages of using Features

Avoiding Feature Conflicts and/or managing Feature Dependencies can be challenging!
It's not easy to start using Features on an existing (production) site.
Install/enable of the Features module is easy (just a module), but to learn to use Features correctly is a major challenge.

2 - Techniques for features packaging

Using Features it is up to your own imagination how to package (compose) the content of a feature. Here are some techniques that can be used for it.

A single super feature

This is a pretty simple packaging technique: everything is packaged together in a single feature (some call it the "God" feature ...). Seems easy, pretty forward, etc. But this technique also leads to "conflicts" (as explained below) more or less right away ...

A good usecase for this appears to be when creating a "Drupal distribution", where all users of it are assumed to use the same set of modules, configuration, etc. If however such distribution consists of multiple website functionalities (to not use the word "features" ...), it seems more appropriate to split such features in multiple features, as explained below.

Based on website functionality

This packaging technique creates a separated feature for each functionality of a website, such as:

Feature A = implement a "*Gallery".
Feature B = implementg a "*Blog".
Feature C = implement a "*Event Calendar".

Based on Drupal admin sections

This packaging technique creates separated features for each of the (major) admin sections of a Drupal website that is used to create the site, such as:

All required modules are contained in feature A,
All base field definitions are contained in feature B,
All content types are contained in feature C,
All permissions are contained in feature D,
All roles are contained in feature E,
All variables are contained in feature F,
All (custom) Views are contained in feature G,
All (custom) Rules are contained in feature H,
Etc.

The above list is virtually unlimited: in the end you could even think of it as 1 feature for each Drupal admin menu option ... if you want to go that far.

IMO it is also the most recommended approach to package features.

3 - Reducing the probability of conflicts in Features and/or GIT

Do not reuse fields

Quite a few conflicts seem to be caused by reusing fields among multiple content types. E.g. in content type A you have a field with machine name field_somefield, which is also used as field in content type B with the very same machine name field_somefield but which as another field type and/or some other field setting(s) that are different.

By not reusing fields among content types, you avoid running in this issue. Have a look at an interesting naming convention for the machine name of your content types and fields as shown in table of Wrapping Information Architecture and Documentation, which is part of the articles about "Relativity Model for Drupal". For more details on that refer to my answer to "How do I model content (types) from a database-centric point of view?".

Split features depending on who works on what

If multiple people are working on a single site, the amount of conflicts can be reduced by organizing (= creating separate) features based on who is working on what. An illustration of this could be as in this example:

Views goes in feature A,
Rules goes in feature B,
Charts goes in feature C,
Anything about Theming goes in feature D,

4 - Recommended Drupal environments

Everything above should help to somehow facilitate the usage of Features. However, to ensure that things will work as expected (designed), you also need to have an appropriate set of environments (logically related Drupal websites) for basically these reasons:

merge functionality provided by multiple features.
predict and resolve conflicts.
end-user testing of all merged features that are certified to not have any conflicts.

In the ideal world, these logically related Drupal websites should be configured, and used, like so:

Personal Dev Site - each website developer has a separated dev site. When some part of the development is ready to be shared with somebody else, an appropriate feature is created, which is shipped to the staging environment.
Sandbox Site - this is a Drupal environment which only contains Drupal core, used to unit test the completeness of a single feature. Should a feature, accidentally, have some unexpected dependencies (eg some module the feature depends on, which is not enabled in the Sandbox), then this is where that dependency will become clear.
Staging Site - here is where one or more features (created in a dev site) are delivered to. It could be just some hotfix for some production problem, or it could be where all development for a new release of the website is consolidated. If any conflicts between multiple features do exist, then this is the environment where they will first show up ... and need to be resolved somehow.
QA Site - after the Staging environment is considered stable, it's time to move on with the relevant features and make them available also at some higher level where they can be used for QA testing, acceptance testing, volume testing, etc. At this level you should be extremely careful in allowing any additional changes (if any). Because any such change may invalidate all prior testing efforts already completed in this environment.
Shadow Production Site - To prepare the activation in real production, you might want to first further promote the relevant features to an environment that is considered a copy (shadow) of your real production environment. If at this point during the migration process anything still breaks, then that is a red flag to revert some of your prior steps. Get it fixed, and try again, until all parties involved approve the changes.
Production Site(s) - If you completed all prior steps, then this step should be self explaining, and pretty easy. Depending on your needs, this could be a single site, or something equivalent to Drupal's Multi-sites whereas all the sites involved are running the very same versions of all features.
Baseline Site - In my experience, there are not many (if any at all) Drupal implementations where this type of site is used (also). It is simply a copy of the Production Site(s), but available to the Drupal developers, testers, etc that can be used to verify what the production sites look like, or to perform user training, etc. And any time a new development cycle is started, the components of a site that will be impacted (need to be changed) should be "copied somehow" using this Baseline Site as input, with as target a Personal Development Site.

Obviously, the above inventory of types of Drupal sites is like the ideal world. Depending on the size of your development team, and / or the available budgets to create and maintain them, not all of them may be used (or affordable). This inventory is modelled after best practises in the area of SCM, used in mostly all huge/global corporations (banks, airlines, etc).

5 - Related modules

Strongarm

The Strongarm module allows for exporting variables (of modules which store their settings in variables) with the Features module.

Node Export

The Node export module allows users to export nodes and then import it into another Drupal installation.

Role Export

The Role Export module allows roles to have machine_names and generates a unique role id (rid) based off of the machine_name. Roles can be exported with Features and get the exact same rid if imported on other sites.

Features Banish

The Features Banish module allows for completely excluding individual features components from the features UI and features exports. Here is a quote about it from its project page:

   This module is useful when there are features components that you want to make sure NEVER get exported. If you are using features for site building or deployment then you've probably ran into the issue of someone accidentally exporting timestamp variables like cron_last or update_last_check. You may also want to banish permissions for developer modules so they don't get caught up with the rest of the site permissions you want to export. Banished items will not show up in your feature module OR ANY OTHER FEATURES MODULE, so use with caution. For a central list of features that should never be exported, see https://www.drupal.org/node/2400531

BEAN

The Bean module makes your blocks exportable. Here is a quote about it from its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. This module only started as of D7, but it has been included with Drupal 8 core already. The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved).

Habitat

The Habitat module makes most sense in a Features-based workflow. Here is a quote about it from its project page:

  In a multi-environment setup (e.g. prod, test, dev, local) there are some modules that you'd like to always be enabled or disabled on certain environments. Each time you sync a database down though you have to re-enable/disable the same modules. Worse, you get lazy and keep development modules enabled on production.

  Habitat provides settings to enable or disable certain modules on each environment (habitat). Just set a variable with e.g. $conf['habitat'] = 'local'; in your settings.php file (the actual variable to use there is configurable for your current workflow). The disabling/enabling modules is done on hook_init.

6 - Recommended resources:

Community documentation about Features.
Part of this answer is based on the (amazing I think) Features debat.
Video tutorials:

Creating a Feature.
Reverting Features.
Updating Features.
Making features the right way.
Limitations of Features.

7 - Possible alternatives to using Features

If you're not able, or willing (yet), to use Features, then you may want to check to what extend the approaches/modules below may provide some type of alternative.

Manual Export/Import

These are the commonly known facilities (to avoid the word features ...) available via the admin UI, for modules such as Rules, Views, etc (incomplete list!).

Bundle copy

Some people consider the Bundle copy module as a possible alternative. It has export/import support for:

Node types.
Taxonomy.
User.
Field API fields.
Field groups.


Access field data from entity in block plugin I'm attempting to render certain fields within a block plugin but I'm not sure where to start as far as accessing the fields so I can render them.

I'm able to get the node ids after I perform the query using the following code.

    $query = \Drupal::entityQuery('node')
        ->condition('type', 'blog_post');
    $nids = $query->execute();

This retrieves the ids that I need based on the query but I don't know how to access custom fields like blog_summary.

I looked into some functions like getFieldDefinitions(). But I'm not sure how to make use of it. I attempted some things using getStorage but I assumed I wouldn't want to go that route since I'm not attempting to make any changes to the nodes I only want to access their fields.

Try this:

public function build() {
  $query = \Drupal::entityQuery('node')
    ->condition('type', 'blog_post');
  $nids = $query->execute();

  $build = [];
  foreach ($nids as $nid) {
    $node = Node::load($nid);
    $build[] = $node->blog_summary->view();
  }
  return $build;
}


Make the git repo part of the drupal site so I can commit my changes whilst testing I've got a git repo on my desktop with a couple of make files. I am currently building the drupal site in my htdocs folder by copying the distro.make file there, running the command:
 drush make distro.make geoslate_test --working-copy --no-gitinfofile

and then cding into the geoslate_test folder and running:

drush si vimn_geoslate --db-url='mysql://root:root@localhost/geo_test' --site-name=Geoslate

to install drupal.

I would like instead to have the git repo as part of the drupal site, so that I can commit my changes whilst testing on the site build install.

Any idea how I can do this?

I found that if I cd into the profiles folder on the Drupal site that has been installed as above, and then commit changes, and push them to git, it also works as if I was committing them from the folder on the desktop which I initially ran the git init on. I read something that said that Drush automatically knows that you are in the directory of a Drupal install, so perhaps this is the resolution.


How to update only one field using Views? Is it possible to update only one field using Views? Say, you use Views to list all property items. Property content type has one field called 'Position' with option values as 'Featured', 'Hot', 'Sold', 'Vacant', etc.. For each item in a row listed you have what looks like the following:

Views Display:

ID   Title     Type       Address       Total Size (sq Ft)     Position        Action
123  Bay View  Apartment  Moroco        1245                   (combobox)      Update

There are other fields for this content type that will not be included, hence, only those relevant fields are shown in this particular Views. So when you click 'Update' button the item will be updated accordingly, that is, only the 'Position' will be updated.

And maybe for other instances, a few fields - instead of one as above - can also be updated. The above is only an example with one field.

Any ideas?

You might try the module Editable fields It is an old module that hasn't been updated in a long time, but I did get it working recently on a new project.

Another option is to build your own with rules, and rules links

With rules links you can set a path that sets a rule to activate. You can have that rule update the content with whatever setting you wish.


Theming translation links I need to change translation links attributes, which have been defined in translation_node_view function in these lines:

$node->content['links']['translation'] = array(
  '#theme' => 'links__node__translation',
  '#links' => $links,
  '#attributes' => array('class' => array('links', 'inline')),
);

I'd like to override these attributes in my custom module.

Any help would be appreciated.

I found a solution by myself. May be useful for others I think:

/**
 * Implements hook_node_view_alter()
 */
function MYMODULE_node_view_alter(&$build) {
    if (isset($build['links']['translation'])){
        $build['links'] = array(
            'translation' => array(
                '#theme' => 'links__node__translation',
                '#links' => $build['links']['translation']['#links'],
                '#attributes' => array('id' => 'translation_links')
            )
        );
    }
}

* Now my links have their own ID, so I can customize them as I need with css
* If you need to custom only these links, I suggest to use MYTHEME_node_view_alter()


use drupal_add_js after external js scripts have already been loaded I have a simple function to call on a specific page template.
I'm calling it using this

<?php
    drupal_add_js("
        jQuery('.row).equalize();
    ","inline");
?>

and it's using an included js library called equalize.js. Which is included like so

<script type="text/javascript" src="mysiteurl/js/equalize.min.js"></script>

I receive 'jQuery(...).equalize is not a function'. but I'm assuming that's because

<script type="text/javascript" src="mysiteurl/js/equalize.min.js"></script>

is being called after my inline js. This only needs to be called on one page. Is there a way to force it to run after the external js file is loaded? Or is there something else I'm missing?

Note: When I run the inline js after the page is loaded in the console in the inspector it works fine.

I was able to resolve this issue by encapsulating the inline js in a jQuery(document).ready function. Like so

<?php
drupal_add_js("
    jQuery(document).ready(function(){
        jQuery('.row').equalize();
    });
", "inline");
?>


Commerce - How do you setup conditional shipping options that relate to a specific taxonomy term? My store sells heavy and lightweight widget items. I currently have 1 product type and have 1 term reference field that designates it as either light weight or heavy weight

Now in my flat rate shipping setup. I have 2 flat rate prices. One for light and heavy. I add a condition to each of these shipping methods to check if its either a light or heavy object, but I'm not sure how I can retrieve these taxonomy references in the rules setup of the component. I would imagine i would have to do a commerce_order:line-item, but after that im stuck and not sure where to go to grab the taxonomy terms.

Use the Commerce Extra Rules Condition module:

The module adds additional Rules conditions related to Drupal Commerce.

It currently adds:

  A condition for checking if a line item references a product with a
  specified Taxonomy term applied to it. A condition for checking if a
  line item references a product with specified Taxonomy terms applied
  to it. A condition for comparing the quantity of products in an order
  with a specified Taxonomy term applied to them against a specified
  value. A condition for comparing the quantity of products in an order
  of a specified product type or checking the quantity of products in an
  order excluding a specified product type.


Error - External URLs do not have an internal route name I can't access to my site because of this error:

  UnexpectedValueException: External URLs do not have an internal
  route name. in Drupal\Core\Url->getRouteName() (line 554 of
  C:\Users\user\Documents\Sites\camp\core\lib\Drupal\Core\Url.php).

  This is the function that I have in line 552 to 558.

public function getRouteName() {
if ($this->unrouted) {
  throw new \UnexpectedValueException('External URLs do not have an internal route name.');
}

return $this->routeName;
}

The last thing I have done it was update 2 nodes that I have created and a View of that content type.

The nodes I have changed the text (just text, didn't put URL or so) and added a photo storage locally

That content type has 2 fields, body and image

On view I deleted the field body and then added again

I have deleted the view, nodes and content type and I still having that error

I don't know if this help but I have installed these modules:

video embed field, views infinite scroll, superfish, pathauto, libraries, flexslider and entity reference revision.

Today I installed the module paragraphs but I uninstalled after the error

Any ideas?

This is the second time that happened to me with this site, the first time I lost some work because I have backed up an older version, but I don't want to lose some work again.

Hi

After a lot of research and try and error attempts I have found what was doing that.

My problem starts when I delete some view page that I have created, it seems the path of that page is still "alive".

If I create another page with them same path the site works fine

So to fix this problem:

- Delete the page view with some path, eg "contacts" (at this point I have that error)

- Create a new content and set the same URL name, in this case "contacts" (at this point the site is working 100%)

- Then delete the content created in the step above (site is still working 100%)

This seems the URL path its no deleted by drupal on the first step and thats why I have that error.


How to migrate using explode with occasional empty array We've made a migration from the City of Helsinki's Linked Events API, and during this work we've been seeing these migration messages:

  Array index missing, extraction failed

Here is an example of an event that works nicely:
https://api.hel.fi/linkedevents/v1/event/hko:14004/

And one that causes the error:
https://api.hel.fi/linkedevents/v1/event/matko:16134/

In the latter you see that offers is returned as an empty array. We're using the skip_on_empty plugin to handle those:

field_offers_is_free:
  -
    plugin: skip_on_empty
    method: process
    source: offers
  -
    plugin: extract
    index:
      - 0
      - is_free
field_offers_info_url:
  -
    plugin: skip_on_empty
    method: process
    source: offers
  -
    plugin: extract
    default: false
    index:
      - 0
      - info_url
      - fi

The problem is that never reaches the skip_on_empty plugin. I've been stepping through this in the debugger based on my findings I created an issue in Drupal Core https://www.drupal.org/node/2905929

When Get sets $multiple to true, processRow() in MigrateExecutable runs a foreach () on an empty array - resulting in the skip_on_empty plugin to be skipped.

Is there something wrong in our setup or did I uncover a bug? Any ideas on how to work smoothly around this?

I solved this by creating my own migrate plugin that sets the multiple flag to false if we get an empty array, like this:

/**
 * The Get plugin causes issues for us when it fetches and array that is empty.
 *
 * It sets multiple to true which prevents the skip_on_empty plugin from being
 * triggered.
 * @see https://www.drupal.org/node/2905929
 *
 * @MigrateProcessPlugin(
 *   id = "get_array_fix_multiple",
 *   handle_multiples = TRUE
 * )
 */

class GetArrayFixMultiple extends ProcessPluginBase {

  /**
   * Flag indicating whether there are multiple values.
   *
   * @var bool
   */
  protected $multiple;

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
      $array = is_array($value);
      $empty = empty($value);
      $this->multiple = $array && !$empty;
      return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function multiple() {
    return $this->multiple;
  }

}

Either the bug is in the get plugin or then skip_on_empty should support multiple.


How to increase exposed filter speed? I have three better exposed filter in views.when apply any filter it takes 4 to 5 secs to give a result.

You can use Views Cache to make better performance.

Click on Caching in right side of view edit page


Webform calculator (I need to delay the result) https://www.drupal.org/project/webform_calculator

Hello, is there a way to delay the calculation for performance purpose ?
The problem is that I have a TON of formulas being calculated every time I type inside the inputs, and this is making the whole thing very SLOW.

I need something like: "Wait 2 seconds after keyup and mouseup > show formula results"

Well, this is how I managed to delay the calculation results in
webform_calculator.js
line 12, 13, 14

setTimeout(function(){
  Drupal.webformCalculator.evaluateAllFormulas();
}, 3000);


Programmatically render menu on search view I'm trying to programmatically build a menu on my site, it works fine on all pages except a search view. This code I'm using is below:

        $config = array('menu_name' => $menu_name, 'level' => 2, 'depth' => 10, 'expanded' => true);
        $menu_tree = menu_tree_build($config);

When I do a var_dump() of $menu_tree it has a content key in the array which has all the menu items, but only if the page is a 'normal' node. If it's the search results view then that array key is empty.

Does anyone have any idea why this is?

I also have two custom functions to change the output of the menu however these don't seem to be called as if I do a var_dump("test") at the start of them it has no affect. The two custom methods are:

THEME_menu_tree__menu_footer_links_1()
THEME_menu_link__menu_footer_links_1()

I worked it out, turns out the problem is different to what I thought.

Because the search view isn't in the menu structure I need to add different values to the $config array. Firstly I needed to add "parent_mid" so it knew what menu item to use as the root for the menu tree & I needed to change the level to 1 to output the links I wanted. Although 2 was still outputting links, just the wrong ones for what I needed.

If you need to work out what the parent_mid is go to Admin > Structure > Menus > Your Menu & hover over the edit link for the menu item you want to be the root of the menu tree, the ID is in the URL. You can also get it programatically, like I did, using menu_node_get_links().


Drupal Commerce Market Place I cannot find a link to add seller/vendor/store in the Commerce-Marketplace module.

I am using Drupal Commerce Kickstart.

As far as I know, there is not a direct solution for this. I have searched google for this,couldn't find a solution. But I will share what I think is correct.

The store in commerce market place is actually similar to an organic group, where you can add members and products.
The store is implemented as an entity. If you go to admin/structure/entity-type/commerce_store/store and add a store, you have created a store.
Now, if you try to add a product, you can type the name of the store that you had created, which will auto-fill for you.

Regarding the vendors, you may have to  create a role and give permission to create stores for that role.

Let me know how that goes.


Add styles to a custom sidebar region in Zen I am using Zen as a theme.

I want to know how I can create a third sidebar and apply the styles in responsive.css to it.

I already know how to create a custom region and render it.

You create a sidebar region as same like other regions. And just edit the css and add the new region class there in existing sidebar css.

.sidebar1{
  background-color:yellow;
}
.sidebar1,
.sidebar_new{
  background-color:yellow;
}


How to hook into core's "log in to comment" link I'm running Advanced Forums on D7, and when an anonymous user views a forum post (lets say nid 101) there is link under the post that says "Log in or register to post comments".

The problem is it is supposed to point to 'user/login?destination=node/101#comment-form' but the url encoding causes it to become 'user/login?destination=node/101%23comment-form'

I looked inside core's comment module, under function theme_comment_post_forbidden  line 2387 says:

$destination = array('destination' => "node/$node->nid#comment-form");
return t('Log in or register to post comments', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination))));

but I think it should make the #comment-form a url fragment:

$destination = array('destination' => "node/$node->nid");
$fragment = 'comment-form';
return t('Log in or register to post comments', array('@login' => url('user/login', array('query' => $destination, 'fragment' => $fragment)), '@register' => url('user/register', array('query' => $destination, 'fragment' => $fragment))));

How I can create a hook to this and change the link?

I found the solution with the help of this SE post. Using MYMODULE_node_view_alter(&$build) and MYMODULE_comment_view_alter(&$build) in my custom module, I was able to change the values using:

$build['links']['comment']['#links']['comment_forbidden'] = str_replace('%23','#', $build['links']['comment']['#links']['comment_forbidden']);


How to disable the Submit button on a the delete page form? I made a form_alter and trying to disable the submit button by greying it out by using the #disabled option on the form api. I know i can just do a unset() on the submit button, but was wondering how to use the #disabled. I tried the following:

$form['actions']['submit']['#disabled'] = TRUE;

But that doesn't do anything it seems. Here' my krumo output:

Yes, you are understanding the behavior of the '#disabled' key correctly. I tried the code you describe and it "just worked."

function custom_form_node_delete_confirm_alter(&$form, $form_state) {

  dsm($form['actions']['submit']);
  $form['actions']['submit']['#disabled'] = TRUE;
  dsm($form['actions']['submit']);
}

My guess as to why the alteration is not creating the desired end result is that your function signature is not using the "&" with the $form variable. That character is needed for the $form variable to be "passed by reference" which allows for the changes to the variable to stick outside the function.


How to compare dates in a View? I'm trying to build a new View in Drupal 8. I want to display list of News. Each item has field_date where is date (without time) stored. And second field is body with basic text information.

I'm trying to set FILTER CRITERIA to display only items with date <= NOW(). It seems that it's impossible to enter this filter. There is no condition for it. Do you have idea how to enter this? This is filter what I see in modal window for new filter citerium

<select id="edit-options-operator" name="options[operator]" class="form-select">
  <option value="=" selected="selected">Je rovno</option>
  <option value="!=">Není rovno</option>
  <option value="contains">Obsahuje</option>
  <option value="word">Obsahuje jakékoliv slovo</option>
  <option value="allwords">Obsahuje všechna slova</option>
  <option value="starts">Začíná na</option>
  <option value="not_starts">Does not start with</option>
  <option value="ends">Končí na</option>
  <option value="not_ends">Does not end with</option>
  <option value="not">Neobsahuje</option>
  <option value="shorterthan">Délka je kratší než</option>
  <option value="longerthan">Délka je delší než</option>
  <option value="regular_expression">Regulární výraz</option>
  <option value="empty">Je prázdný (NULL)</option>
  <option value="not empty">Není prázdný (NOT NULL)</option>
</select>

(Sorry for Czech localization but you can still see key of each option :)

I thought that shorterthan we be right option, but it seems to be suitable only for string. I know that Drupal 8 is still in beta today but this problem must have some solution. I'm using already included core extension Datetime.

In Drupal 8.2.5 the option is available. See this picture:


Seperate /user/register fields and admin/people/create i extended the add user field by adding a role field as part of the fields that will be displayed when you click  create user in mydomain.com/user/register. With the addition of some rules, this helps me to assign automatic roles to registering users.

I however noticed that when you  add user from the admin menu in People>Add user, this roles fields are added to the already existing fields. This is undesirable because the Add user page already have a section where you can pick the role. This therefore makes the form to have 2 different section where you can pick roles.

I want to hide my custom role field in mydomain.com/admin/people/create but show it in mydomain.com/user/register. Please how do I achieve this

Probably hook_form_FORM_ID_alter on user_register_form then some logic like

function MYMODULE_form_user_register_form_alter(&$form, &$form_state) {

  // Is logged in user admin.
  if (user_access('administer users')) {

    // Hide myfield.
    $form['myfield']['#access'] = FALSE;
  }
}