how to dynamically set query parameter on menu item Hello I am a very experienced web dev who is brand new to Drupal and learning to build my first site in it.

I have a very simple site I am converting from pure code (html, css, jquery, angular, bootstrap, php) to drupal so that I can add a CMS backend to the site. On this site I need to track what ad campaign sent the user to the site to be stored with the users information later after they submit their email to be contacted again.

This is how it works currently on the non-drupal site: User clicks on a link on an 3rd party site that directs them to my-site.com/get-eBook.html?campaign=google. On get-eBook.html there is a menu item for /ebook-register.php, I use some PHP to grab the value of campaign from the URL and if it is not null I update the menu item to /ebook-register.php?campaign=google in order to pass the value along to the register page where it is used in a SQL statement and captured in the DB with the users email address.

Now I'm not sure how to accomplish the same thing in Drupal. I have my theme set up, I have two pages created (get-ebook and ebook-register) and I have my menu set up with the link to ebook-register. I however have no idea how I can grab the value of campaign on the get-ebook page and add that value onto the desired menu item being returned by the drupal core so that the value of campaign will be preserved when the user navigated from get-ebook to ebook-register.

Any ideas on how I can allow the menu to be maintained via the Drupal backend but still have the ability to dynamically add query parameters to the items after they're returned from the core?

The way I would do this would be overriding the menu link.

You can override a menu link by doing a theme override of theme_menu_link() however you don't want to modify the structure of the markup you want to modify the data being printed (in this case the link query string) so I would recommend overriding the variables of that function in hook_preprocess_HOOK() (in this case hook_preprocess_menu_link()).

Template variable overriding is often done in the theme, and you can do it in your theme's template.php file, however in your case I would recommend a custom module because this is functionality not visual display. If you put it in your theme's template.php and then change themes it will stop working, which is probably not what you want.

So it would be best in a custom module.

If you look back at the docs for theme_menu_link() you can see that the link is created using the l() function and looking at the parameters to the l() function you see that the $options parameter can contain "Additional $options elements used by the url() function", which you can see from the url() docs includes the query string, which is a non-encoded array of key/value pairs.

So from that you can tell that in your theme function preprocessor you need to modify/add your query string in $element['#localized_options']['query'] something like this:

$variables['element']['#localized_options']['query']['campaign'] = 'google';

You can also see that the URL of the link is in $element['#href']. Since you probably want to affect all links that point to that path I would suggest overriding the link options based on path.

Since you can access the current page's query parameters using basic PHP's superglobal $_GET you then have all the information you need to set your menu item.

You can do it like this:

/**
 * Variable preprocessor for the themeing of menu links.
 *
 * @see theme_menu_link().
 */
function MODULENAME_preprocess_menu_link(&$variables) {
  // If we have an ebook campaign code then add it to the ebook register
  // menu link.
  if ($variables['element']['#href'] == 'ebook-register.php' && !empty($_GET['campaign'])) {
    // Just add our query array element instead of setting query to a new
    // array to avoid possibly overwriting other query parameters.
    $variables['element']['#localized_options']['query']['campaign'] = $_GET['campaign'];
  }
}

One other thing worth nothing is that generally in Drupal you shouldn't have pages as custom PHP scripts like ebook-register.php.

Instead you should have a custom module that implements hook_menu() to make the path 'ebook-register' call a custom callback that then contains your page logic. See the drupal menu system docs for more information (D6 & D7 have the same menu system) and also the examples module's menu & page examples.


How to send an email using a field key? I am attempting to send an email to a field selected value using the Rules module.
The user selects a faculty member and saves the node. The rule should fire off and email based on the field's key. I have the field set up as:

  john@email.com|Doe, John

I am attempting to send to the key using [node:field-advisor-:key] as a replacement pattern. But I think it's still trying to send to the label.

I am still very new to Drupal so my vocabulary and skills are relatively limited.

Here is the exported rule:

  { "rules_email_to_adviser" : {
  "LABEL" : "Email to Adviser",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules" ],
  "ON" : { "node_insert--timeclock" : { "bundle" : "timeclock" } },
  "IF" : [
        { "user_has_role" : { "account" : [ "node:author" ], "roles" : {
        "value" : { "20" : "20" } } } },
       { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_advisor_" } }
    ],
  "DO" : [
    { "mail" : {
        "to" : "[node:field-advisor-:key]",
        "subject" : "Time Card Submitted for Review",
        "message" : "[node:author] has submitted a time card for your approval. \r\n\r\nPlease review the time card at: [node:edit-url]\r\n\r\nThank you.",
        "language" : [ "" ]
      }
    }
  ]
  }
}

Notes:

All of the faculty members (such as "John Doe") have accounts on the site.
If it would help (simplify things) to make the rule work, I'm OK with replacing the implementation of that field_advisor_-field by a more appropriate field (with similar functionality).

Part 1: Review the definition of your field

Assuming that all of the faculty members have an account on your site (as you confirmed in one of your comments), I recommend to replace the implementation of that field_advisor_-field. I.e. delete that field in your timeclock content type, and add a more appropriate field that looks like so:

Field Name = Anything you want, say with a machine name like field_timeclock_reviewer
Field Type = Entity Reference, with Target type = user and Number of values = 1 (pick any of the other options to define this field as you see fit).

By using this field, you don't have to maintain the data of that field as in your example with john@email.com|Doe, John (instead you take advantage of the already administered userids and their corresponding eMail IDs).

Note: to limit the list of users that can be referenced to only those users with a specific role (like "faculty"), you should use Views "Entity selection mode" for your entity reference field in the Entity Reference widget. But before you can select the appropriate "View" to do so, you should create a view (with the Views module) to create a list of all users with that specific role.

Part 2: Rule to send the eMail

After you adapted the setup of your field as described above, it is straight forward to write a rule for the Rules module to send such eMail that you're looking for.

Here is a sample of such rule (in Rules export format), which will send such eMail to the userid selected via the field field_blog_reviewer (= a field I added to my "Blog" content type that is defined as an entity reference to a 'user'), and this whenever a new node of content type "Blog" is saved:

{ "rules_notify_reviewer_about_outstanding_approval" : {
    "LABEL" : "Notify reviewer about outstanding approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_blog_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-blog-reviewer]",
          "subject" : "Blog Post waiting your approval",
          "message" : "[node:author] has submitted a new Blog post waiting your approval.\r\n\r\nYou can review it at: [node:edit-url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

If in the above exported rule you'd change "blog" to "timeclock" (before importing this rule in your environment), and after you also add that extra user_has_role condition (as in your question), you should be pretty close to getting it to work (with an eMail that is similar to what you wanted it to be).


Changing the view mode of EntityReferenceFieldItems programmatically I have a paragraph (I'm using the Paragraphs module) that contains an entity reference field that contains references to other pages.

The display settings are set to use a particular view mode, e.g. teaser. This renders an teaser image, title and link to the page.

I would like the editor to be able to set the view mode on a per-paragraph basis. I have created a "view mode" field in the paragraph with two options: teaser, and teaser-text-only.

How can I use the view mode set in the "parent" entity (the paragraph) to add a template suggestion when rendering the "child" entities (the pages)?

At this point it should be no problem to change the view mode in the render element of the referenced node. The node has yet to be built and will, hopefully, use the modified view mode.

You can try something like this in a paragraph preprocess hook:

function mytheme_preprocess_paragraph(&$variables) {

  if ($variables['paragraph']->hasField('field_view_mode')) {
    $view_mode = $variables['paragraph']->field_view_mode->value;
    if (isset($variables['content']['field_ref_node']['0']['#view_mode'])) {
      $variables['content']['field_ref_node']['0']['#view_mode'] = $view_mode;
      unset($variables['content']['field_ref_node']['0']['#cache']['keys']);
    }
  }

}

Edit:

To prevent that the node gets cached on it's own in the wrong view mode remove the cache key.


SMTP Error: Could not connect to SMTP host We have a new Drupal 8 site and are having issues with the SMTP module. The account we are using to send email works successfully on our Drupal 7 sites and in other cases, but we cannot get it to work successfully on Drupal 8. I have also tried another Non-SSL account and am getting the same two messages over and over in the error log.

  Error sending e-mail from smtp@website.com to email@email.com: SMTP Error: Could not connect to SMTP host.

  Error sending email (from smtp@website.com to email@email.com with reply-to not set).

I have found many similar questions, but not a working solution yet. Any help would be greatly appreciated, thank you in advance!

Doh! It turns out this was not a Drupal issue, but a Centos issue with SELinux. I was able to check SELinx settings by running the following commands

getsebool httpd_can_sendmail

which returned

httpd_can_sendmail --> off

and

getsebool httpd_can_network_connect

returned

httpd_can_network_connect --> off

I enabled them by running this

setsebool -P httpd_can_sendmail 1
setsebool -P httpd_can_network_connect 1

And the Drupal SMTP module worked beautifully after that. Hopefully this helps someone else as well.


Display taxonomy terms differently by content type Is there any way to display the taxonomy terms slightly differently depending on the content type they appear in? For instance, I have two content types that I'd like to have use the same vocabulary, but the terms represent slightly different things to end users.

Example: a node field asks an organization "how are you interested in connecting with a campus?" and answers include "lead an interactive workshop" and "participate on a panel". When a different content type asks a teacher "how are you interested in organizations connecting with you?" the answers include "have an organization lead a workshop" and "host a panel". Obviously those answers correspond 1:1, so I'd like to use the same vocabulary. But they need to present themselves slightly differently in each content type.

Since vocabularies are linked to nodes via fields you'd be best off handling this in hook_preprocess_node() in your theme file:

function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  // Only make the change if this is a certain node type
  if ($node->type == 'my_type') {
    // Extract the term IDs from the field
    $tids = array();
    foreach ($node->field_vocab[$node->language] as $value) {
      $tids[] = $value['tid'];
    }

    // This example adds the taxonomy terms to a simple list, you'll
    // want to replace this with whatever theme function you need
    $items = array();
    foreach (taxonomy_term_load_multiple($tids) as $term) {
      $items[] = l($term->name, "taxonomy/term/$term->tid");
    }

    // Replace field_vocab in the vars with the new content
    $vars['field_vocab'] = theme('item_list', array('items' => $items));
  }
}

That might need to be changed/added to depending on your needs but it should give you a place to start from. Once you've added the new hook to the template.php file make sure you clear Drupal's hooks so the registry will be updated.


How to set the user must login as member before purchase? How do I set the user must login as member before purchase?

I'm using Drupal version 7, with Drupal Commerce.

Use the Commerce Checkout Redirect for implementing this:

  This module redirects anonymous users to a page where they can login or create a new account when they try to checkout.


Solr Search with 2 text fields I have a drupal 7 installation with apache solr search: But I need to use a custom search like this:

2 TextBox fields with:
What -> Any word of the apache index.
AND
Where -> A term reference in the content type.

After looking for several forums and apache solr help, I made it like this...

Notes:

1 $form_state['values']['keys'] - The search text

2 $form_state['values']['localidade'] - The taxonomy term search value

function MYMODULE_search_block_form_submit($form, &$form_state) {

// Check if localidade is empty
    if (empty($form_state['values']['localidade'])) {
    // localidade empty
        drupal_goto('pesquisa/' . $form_state['values']['keys']);
    } else {
    // with localidade
    // check what is the tid of my term localidade
        $t1 = $form_state['values']['localidade'];
        $t2 = taxonomy_get_term_by_name($t1, "localidade");
        $t3 = array_shift($t2);
    // term no found
        if (empty($t3->tid)) {
            drupal_set_message('Não reconheçemos a localidade ' . $form_state['values']['localidade'] . ', por favor coloque uma localidade sugerida.');
            drupal_goto('pesquisa/');
        } else {
    // build search parameter with the term tid
            $t11 = 'pesquisa/' . $form_state['values']['keys'];
            $options['query']['search_param'] = 'f[0]=bundle:empresa&f[1]=im_field_localidade:' . $t3->tid;
            drupal_goto($t11, $options);
        }

 }

}


My images are not showing up after importing to Pantheon I finished creating my drupal site with WAMP and then imported the database. None of my images are showing up. I am assuming this is a file-path problem, but i'm not quite sure how to fix it?

For example, I have a image field in a content type, but it does not tell me where / how I can edit or change the pathing file.

By default, images uploaded through an image field are saved to the sites/default/files folder and not the database. Be sure that you have also imported your /files folder into your new site and the images should show up without needing any changes to file paths.


How to get one time URL when we are writing hook_mail_alter? My Question is already present here but the previously given answer for my question can applied to Drupal 7 and I can not use the same solution in Drupal 8.

I hope it is okay not put the same question once again.

Bingo! Found the Solution myself:

    function custom_module_mail_alter(&$message) {
      if (!empty($message['id']) && $message['id'] == 'user_password_reset') {
        $token_service = \Drupal::token();
        $language_interface = \Drupal::languageManager()->getCurrentLanguage();
        $account = $message['params']['account'];
        $one_time_url_token = '[user:one-time-login-url]';
        $one_time_url = $token_service->replace($one_time_url_token, ['user' => $account], ['langcode' => $language_interface->getId(), 'callback' => 'user_mail_tokens', 'clear' => TRUE]);
      }
    }


Block level configuration not available in reaction part of context I am new to context. I just want to disable a block for a particular URL. But i don't get block level configuration in reaction part of context. Anything else i have to do for it ?

In your original context that adds the block you can negate a path by using a Tilde along with your path (in the context condition).

e.g. ~your-path


different templates for print and deafult version of the node I've faced with a problem of differentiating node templates for print-version (I'm using "print" module) and default node's default template.

I have a <div> which should be present in node--node_type.tpl.php but not in print-version (it contains info that is not required when viewing the page not on the display).

Currently I'm solving this with adding

<?php if (arg(0) == 'node'): ?>
<div>.....</div>
<?php endif; ?>

But it seems to me that this kind an awkward way.

Can you offer any Drupal-alike and more convenient way to gain that?

Thank you.

load a print only CSS file and "display:none" for that div in it:


Different blocks on the same page, dependent on source link? Is it possible to have a page that shows (e.g.) one of three different blocks, depending on the originating page link? I'm thinking the only way to achieve this would be to use # or something similar at the end of the URL.

Example:

link one: mysite.com/mypage#one
link two: mysite.com/mypage#two
link three: mysite.com/mypage#three

And then create the three blocks, with the visibility settings set appropriately.

Is this a robust solution that would work with URL aliases etc.?

Cheers,
James

If you do it programmatically you can always parse url and display different content for different anchor or other param. You can always use one block for display content according to conditions.

Take a look to Context or Rules modules, maybe you find easier solution


Reverting/updating "FILE_DISPLAY" in Features My site is running Drupal v7.30 and Features v7.x-2.2. I can't revert or update file_display components in features. There are additional definitions under the Default column that appear to be define by the Media (7.x-2.0-alpha3) module in hook_file_default_displays_alter(). How do I go about properly keeping my features not in a perpetual Overridden state?

There is a bug with media and the media modules.

There is some patches already that you could try

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


After changing a webform multi-select field to single-select, submissions made pre-change show only the first selection I've created a webform in Drupal 7 with a component drop-down list.  I selected 'multiple' for multiple selections.  Now, I need to unselect 'multiple' giving users just one choice of the drop-down list.

Now, when viewing the submission data, the past data w/ multiple choices only show the topmost choice.  How can I have the past data show the multiple choices despite I'm allowing only one choice in the component?

You can keep the field set to single choice, and use hook_webform_submission_render_alter() to display the values as if it was still a multi-select field.

You can use the hook in a module or the template.php of a theme. If you are thinking about implementing it in a theme, keep in mind that the Webform Results view is displayed through the Administration theme. So, the hook must be implemented in the default administration theme for it to work in that view. By implementing it in a module, you shouldn't have to worry about which theme the submission results are being shown.

You will need the nid for the webform, and the form Key for the select field. The nid is in the url of the webform's edit page. The form key can be seen in the webform's Form componentspage.

The following code is implemented in the "my_module" module, for a webform with a nid of "100", and a field with the form key "my_select_field".

/**
 * Implements hook_webform_submission_render_alter().
 */
function my_module_webform_submission_render_alter(&$renderable) {
  if ($renderable['#node']->nid == '100' && isset($renderable['my_select_field'])) {
    $renderable['my_select_field']['#multiple'] = 1;
  }
}

The isset($renderable['my_select_field']) in the if statement may seem redundant, but it's there to prevent an exception if someone changes the form key for the field.


Migrate custom source plugin not found I have a fairly simple D6->D8 migration, and I need a custom source plugin for one of my node migrations. As far as I can tell, I have everything written and structured properly, but when I click on the migration group in the admin UI, I get a message that my source plugin doesn't exist.

Here's the relevant part of my node migration config:

In /my-module/config/install/migrate_plus.migration.video.yml:

id: video
label: Video
migration_tags:
  - Drupal 6
deriver: Drupal\node\Plugin\migrate\D6NodeDeriver
migration_group: node
source:
  plugin: mrctvVideoSource
  node_type: video
process:

and my source plugin in /my_module/src/Plugin/migrate/source/mrctvVideoSource.php:

namespace Drupal\migrate_mrctv\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Row;

/**
 * Source plugin for MRCTV video nodes.
 *
 */
class mrctvVideoSource extends SqlBase {

  /**
   * @MigrateSource(
   *   id = "mrctvVideoSource"
   * )
   */
  public function query() {
    return $this->select('view_videos', 'vv')
                ->fields('vv', array_keys($this->fields()));
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'video_data' => $this->t('Video Data'),
      'thumbnail_data' => $this->t('Thumbnail Data'),
      'show_ads' => $this->t('Show Ads'),
      'raw_s3_file' => $this->t('Raw S3 File'),
      'nid' => $this->t('Node ID'),
      'vid' => $this->t('Version ID'),
      'title' => $this->t('Nond Title'),
      'node_created' => $this->t('Created'),
      'node_changed' => $this->t('Changed'),
      'node_uid' => $this->t('Node User'),
      'node_body' => $this->t('Body'),
      'teaser' => $this->t('Teaser'),
      'revsion_uid' => $this->t('Revision UID'),
      'log' => $this->t('Revision Log'),
      'timestamp' => $this->t('Revision Timestamp'),
    ];

    return $fields;
  }
}

From what I can tell, I have everything named and annotated properly and in the correct locations, but I'm obviously missing something.  What is it?

Thanks.

UPDATE: Per Mike Ryans'suggestion below, I changed the id of my plugin (after clearing cache) from 'mrctvVideoSource' to 'mrctv_video_source', both in the migration yml file and the id annotation in my plugin definition (is there anywhere else I need to change it?). But now, after uninstalling my module (and having to manually delete the config records in the config database again, config_devel doesn't seem to be clearing anything out), my node migrations are not even listed on the Migration page. Sigh. Still troubleshooting...

I think you need to have your annotation outside of the class

/**
 * Source plugin for MRCTV video nodes.
 *
 * @MigrateSource(
 *   id = "mrctvVideoSource"
 * )
 */
class mrctvVideoSource extends SqlBase {


How to programmatically create a title for a new node? I want the title field of each new node of the Agenda content type to be constructed automatically from a date field in that same node.

I have variously tried setting the #default_value and #value on the $form array in hook_form_FORM_ID_alter() but without effect.

How can I achieve this?

Here's how to do it with an entity builder callback.

<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

//Implements hook_form_FORM_ID_alter()
function agenda_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    $form['title']['#access'] = FALSE;
    $form['#entity_builders'][] = 'agenda_node_builder';

}

function agenda_node_builder($entity_type, NodeInterface $node, $form, FormStateInterface $form_state)
{

    $date_of_meeting = $node->field_date_of_meeting->date->format('Y-m-d');
    $node->setTitle('Agenda for meeting on '.$date_of_meeting);

}

Notes:

I found that the callback had to be set up in hook_form_BASE_FORM_ID_alter() rather than hook_form_FORM_ID_alter in which case it didn't get called.
Didn't get to the bottom of this but it's probably something to do with the fact that alter hooks are called in the following order: hook_form_alter(), hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter().
Nodes #entity_builders offer a Node entity object for modification before being stored when the form is eventually submitted.

Thanks to @Berdir for the pointers.


An AJAX HTTP request abnormally terminated in autocomplete textbox I have autocomplete textbox which populate the suggestion based on search text.
Steps

User type in search text box
User press enter instead of waiting for AJAX autocomplete to respond

It comes up with the following error.

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: path/allcontent/autocomplete
StatusText: error
ResponseText:  ReadyState: 4

I read Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors, but it didn't help.
This is the callback code.
Autocomplete Textbox
function search_user($form) {
        $form['text_usersearch'] = array(
            '#type' => 'textfield',
            '#title' => t(''),
            '#autocomplete_path' => 'searchuser/autocomplete',
            '#size' => 30,
            '#attributes' => array('class'=> array('auto_submit'),'style'=> array('float:left')),
        );

$form['submit_user'] = array(
            '#type' => 'submit',
            '#value' => t('Find'),
            '#attributes' => array('class'=> array('submit_user linkbuttonAction'),'style'=> array('float:left;margin-left:10px')),

        );

Autocomplete menu register
$items['searchuser/autocomplete'] = array(
     'title' => 'Autocomplete for User',
     'page callback' => 'user_autocomplete_search',
     'access arguments' => array('access content'),  //or whatever permission makes sense
     'type' => MENU_CALLBACK
      );

Menu callback
function user_autocomplete_search($string) {
        global $user;
        $arrUserMatch = array();

        $matchCode = '%'.db_like($string).'%';
        $arrUserTitle = SelectMatchingUserTitle($matchCode,10);

        foreach ($arrUserTitle as $userId=>$userName)
        {
            $autotext .= check_plain($userName);
            $arrUserMatch[$userName] = $autotext;
        }

        drupal_json_output($arrUserMatch);
    }

Form submission handler
function search_user_submit($form, &$form_state) {

        $searchval= $form['text_usersearch']['#value'];

        if($searchval=='')
            return;
        else
           drupal_goto('user/'.$searchval);
}

JavaScript autocomplete
$(window).load(function(){
                Drupal.jsAC.prototype.select = function (node) {
                        this.input.value = $(node).data('autocompleteValue');

                        if(jQuery(this.input).hasClass('auto_submit')){
                              this.input.form.submit();
                        }};

        });

i am using the following code to auto complete the name of the partners (store owners) in a search box in a form to edit a store's detail (not all form elements used are shown here):
the auto_complete call back returns the list of all the partners in the database.
(here one partner owns one store)
you could try and workout something similar:

the submit button links to a submit handler that updates the database.

function partner_store_form($form, &$form_state, $sid = 0) {
      $edit = NULL;
      if ($sid != 0) {
      $query = db_select('store', 's')
        ->fields('s', array('partner_pid'));
      $query->leftJoin('partner', 'p', 's.partner_pid = p.pid');
      $query->condition('s.sid', $sid);
      $query->addField('p', 'name', 'p_name');
      $edit = $query->execute()->fetchObject();
      }
      $form['pid'] = array(
        '#type' => 'textfield',
        '#title' => t('Partner Name'),
        '#size' => 30,
        '#required' => TRUE,
        '#default_value' => isset($edit) ? $edit->p_name . "  [Id:" . $edit->partner_pid . "]" : '',
        '#maxlength' => 96,
        '#autocomplete_path' => 'partner/autocomplete'
      );

      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($edit) ? t('Edit') : t('Save'),
        '#submit' => array('partner_store_form_submit')
      );
    }

    ----------

    $items['partner/autocomplete'] = array(
        'title' => 'store autocomplete',
        'page callback' => 'partner_store_autocomplete',
        'access arguments' => array(CONST_PERM_LIST_PARTNER),
        'type' => MENU_CALLBACK,
      );

    -----------------

    function partner_store_autocomplete($string) {
      $store = array();
      $query = db_select('partner', 'p');
      $return = $query->fields('p', array('pid', 'name'))
        ->condition('p.name', '%' . db_like($string) . '%', 'LIKE')
        ->condition('p.remove', 0)
        ->execute();
      foreach ($return as $field) {
        $store[$field->name . "  [Id:" . $field->pid . "]"] = check_plain($field->name);
      }
      if (empty($store)) {
        $store[''] = t('No Such User');
      }
      drupal_json_output($store);
    }


Search API and Domain Access: Filter user per domain I've got a site with multiple domains using Domain Access.
I want to display a search form on each site that searches for users on that site.

I'm using a modified version of the code here (that code works fine when searching for nodes) but it doesn't work.
When searching it always return an empty result.

Here's my code:

/**
* Implements hook_entity_property_info_alter().
*
* Adds an entity property for the domain access of the user.
*/
function custom_search_users_entity_property_info_alter(&$info) {
  $properties = &$info['user']['properties'];

  $properties['custom_search_users_domain_access'] = array(
    'label' => t('Domain Access Information'),
    'description' => t('The domains to which the user has access.'),
    'type' => 'list<integer>',
    'getter callback' => 'custom_search_users_get_domain_info',
  );
}

function custom_search_users_get_domain_info($data, array $options, $name, $type, $info) {
  return (!empty($data->domain_user) ? $data->domain_user : NULL);
}

/**
* Implements hook_search_api_query_alter().
*
* Adds a filter for the current domain.
*/
function custom_search_users_search_api_query_alter(SearchApiQueryInterface $query) {
  $domain = domain_get_domain();

  $query->condition('custom_search_users_domain_access', $domain['domain_id']);
}

So basically what I've changed in my code is the use of $data->domain_user instead of $data->domain to comply with the user object.

Anyone got any idea of why this doesn't work?

I think your approach is just fine, but you forgot to index your field. You've to check the field you created on the field page (admin/config/search/search_api/index/**your_index**/fields)

Once checked, you'll be able to index your extra field and by so, filter on domain.


#validate not overriding the submit function I'm creating a form in my own module (call it mymodule) and using a #validate property to clear the form. In my form definition, after calling hook_menu and hook_form,

function mymodule_myform($form_state){
$form['main']=array(
    '#type'=>'fieldset',
    '#title'=>t('Information'),
    '#collapsible'=>TRUE,
    '#collapsed'=>FALSE,
);
$form['main']['title']=array(
    '#description'=>t('Enter title.'),
    '#type'=>'textfield',
    '#size'=>50,
    '#default_value'=>'default',
);
$form['submit']=array(
        '#type'=>'submit',
        '#value'=>'Submit',
);
    $form['clear']=array(
        '#type'=>'submit',
        '#value'=>'Reset form',
        '#validate'=>array('mymodule_myform_clear') //redirects to the _clear function defined below
);
    return $form;
}
    function mymodule_myform_clear($form, $form_state) {
        unset($form_state['values']);
        $form_state['rebuild']=TRUE; //clears the form
    }

    function mymodule_myform_submit($form, &$form_state) {
        $values=$form_state['values'];
        die('the value you submitted: '.$values['title']);

Both functions get called when the Reset from button is pressed. Why is the #validate property not doing its job?

Like Clive said resetting $form_state['input'] is the solution, however I'd rather handle both actions in the submit function:

function mymodule_myform_submit($form, &$form_state) {

  if($form_state['clicked_button']['#value'] == $form['clear']['#value']) {
    $form_state['input'] = array();
    $form_state['rebuild'] = TRUE;
  } else {
    $values = $form_state['values'];
    die('the value you submitted: '.$values['title']);
  }

}


How to make the cart menu display the number of items added? How to make the cart menu display the number of items added?

Example If I added one item, the cart menu will display "one".

Module: Drupal Commerce

Commerce Ajax Add to Cart

  Using this module you can ajaxify the add to cart operation. The
  updated cart will be displayed without page refresh and a popup
  message will be shown after you add an item to cart. You can customize
  the look of the blocks using its template files.


Using "Add another" field widget on non-fields (extra_fields or Entity API properties) I would like to have a multiple-value property attached to an entity.

Currently, all of the properties are handled with field_extra_field and then stored in a single database table so we don't add the overhead of lots more tables. We don't need all of the neat features of Field API like versioning, so this works.

However, we do need one feature, the multiple value handling. Is there any way to get this without making a real field?

The Examples project has an "ajax example" submodule that shows how such a thing can be done with #ajax in a form. Should get you far.


How do I go about creating a paid subscription product with Drupal Commerce? I am trying to set up a paid subscription to an email list using Drupal Commerce with payment via PayPal.

One of the way I came up with is upon completion of an order, a user will be redirected to a subscribe page and her role will be updated to view the form.

I am looking for pointers to functions, existing modules or any advise on how to achieve this.

Thanks,

~ahimsauzi

Is the mailing list internal or using an external provider like MailChimp or Constant Contact? If you're giving the user access to an external provider's form that will work but it may also allow them to work around it (for example if they want to share it with their friends).

The most secure way would be to use an API call/period import (for external services) or direct update (for internal mailings) using a conditional action or module that's triggered by completed orders.

Edit for further details: Mailchimp does indeed have an API - http://apidocs.mailchimp.com/ - and a Drupal module at http://drupal.org/project/mailchimp so the current functionality is half-way there. I would go the last step and create a custom module that adds subscribers to Mailchimp when they complete their order. At that point it's still a one-time thing, so for bonus points on recurring payments you could keep track of the subscribers and remove them from Mailchimp using the API if they stop paying.

It would take a little coding but it's a realistic setup. I can't see anything you can do without any coding unless the Mailchimp module allows you to set up a page that can then be limited to the role of users who paid (and then you still have an extra manual step).


One view per taxonomy vocabulary without a contrib module? What do I need to set in a D8 view, to have one view per taxonomy vocabulary without any contrib module?

Drupal 8 already uses the (now-builtin) Views for listing pages of content belonging to a certain taxonomy term.

That's a single view for all taxonomy terms:

You can edit the view and make necessary changes you need
http://example.com/admin/structure/views/view/taxonomy_term


just installed 7.12 - but got stuck - how to access the backend and login good day dear drupalers,

just installed 7.12 - but got stuck - how to access the backend. i have no glue.

see the page: http://www.boysday.org - i do not know how to proceed. how can i see the backend.

btw. i do not know the passwd. and the admin-login-name.
and i do not know the link to the login page:
i was in a hurry while i installled all.

see the result on http://www.boysday.org :

Page not found
The requested page "/" could not be found.

question 1: can the data (login name and passwd) be accessed via the backend!? Can i obtain the data to access the backend of the freshly installed D 7.12 while i look at the backend of the site - with phpmyadmin.

question 2: if i have the data - where to go - which link should i follow to acess a login-screen?

look forward to hear from you

greetings

btw: there was a lot of noise during the installation - have a look at this folllowing data: - what do you say...!?

http://boysday.org/install.php?profile=standard&locale=en&op=start&id=1

Warning: opendir(modules/simpletest/tests/themes/test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/field/modules/list/tests) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/update/tests/themes/update_test_basetheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/update/tests/themes/update_test_subtheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/block/tests/themes/block_test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/simpletest/tests/themes/test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/field/modules/list/tests) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/update/tests/themes/update_test_basetheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/update/tests/themes/update_test_subtheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/block/tests/themes/block_test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).

what do you say...!? ,look forward to hear from you!!

You won't be able to get the password from the database, but you will be able to get the email address for user 1 and then request a new password by email.

Have a look in the users table for the email address for the entry with a uid of 1. Then go to http://mysite.com/user/password, pop in that email address, and wait for instructions to be emailed to you.

After you've re-gained access to the site you can log back in again at any time by going to http://mysite.com/user. The admin backend will most likely be at http://mysite.com/admin, unless someone has changed it (this is unlikely).

The errors you got during install are because of a UNIX limit on the number of open files/file descriptors in the system. Take a look at this article for some suggestions on how to increase that limit so you don't run into the same error again.

It might be that you need to raise this limit and then re-install the site again...I'm not sure if the errors you've received will have stopped the site from being installed properly or not.


Taxonomy exposed filter with parent hierarchy only I have a taxonomy vocabulary with terms in hierarchical order. If I use an exposed filter, with level depth, all terms are listed, which are > 6,000. I want only the parent terms, which are only around 30.

I found here the following code (I adapted it to my case). It is an answered question, but obviously it does not apply efficiently to my case, because though it does what is suppose to do, it goes through every item and as a consequence is extremely slow (several seconds). Is there a better way that does not directly make a db_query to the taxonomy database tables or use a hook (PHP) ?

function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-search-page-page'{
    foreach ($form['term_node_tid_depth']['#options'] as $term_key => $term) {   // Check if this isn't the 'ANY' option
      if($term_key !== 'All') {
        // Check if this is a child by looking for '-' as first char in string
        $term_value = reset($term->option);
        if($term_value[0] == "-") {
          unset($form['term_node_tid_depth']['#options'][$term_key]);
        }
      }
    }
  } // if
} // function

I had a situation like this, i done it by giving a custom options array to the exposed filter in hook_form_alter().

 function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "views_exposed_form" && $form['#id']=='your-form-id' ){
 $tid_options = get_tid_options();

 $form['your-field-name']['#type'] ='select';
 $form['your-field-name']['#size'] = null;
 $form['your-field-name']['#default_value'] = '';
 $form['your-field-name']['#options'] = $tid_options;
   }
}

function get_tid_options() {
  $cc=array();
  $tax=taxonomy_vocabulary_machine_name_load('machine-name');
  $vid= $tax->vid;
  //Code to find parent terms here according to your vocabulary structure.
  $child_terms = taxonomy_get_tree($vid);
  foreach($child_terms as $values)
  $tid=$values->tid;
  $name=$values->name;
  $cc[$tid] = $name;
 }
return $cc;

}

Use taxonomy_get_parents or taxonomy_get_parents_all to find parent terms.

May be this will help you..


Moving forum out of the main database I have a Drupal 6 site with an increasingly bloated forum. I am wondering whether it is possible I can move the forum out of the main site's database to a new database, possibly hosted in a new server.

So  I guess my question is a special case of distributing a single Drupal database over several servers.

One option is to have a multidomain setup where forum.yourdomain is your forum installation and www.yourdomain is your main portal. Then you could have a single sign on for both domains.


Add custom payment widget to a node? I have a widget that allows the user to book and pay on a site. I used:

function capewinefarms_preprocess(&$variables, $hook)

And ended up with something like this:

$variables['book_now_widget'] = '
bla bla bla
';

Which I then output in the template using:

{{ book_now_widget }}

The problem is that instead of seeing:

 bla bla bla

in bold text, i see:

bla bla bla

Because the widget is "self-contained", it needs all the javascript and html and everything to be outputted exactly as is, and not be formatted. It seems twig is somehow doing this.

Any idea as to how to get around this? Or any insight into why this is happening? Or perhaps an even better question might be: how do I do this the most correct way?

I suppose I can do it as a block, but then I would have to attached a JS file, and I can't do this, because it all needs to be self contained as it is also re-used on a mobile app.

Any ideas?

1.) What is happening

Twig sanitizes all variables before displaying them. Because it assumes, that the style attribute is from user input and is considered to be unsafe. You can pass most html as #markup, but not the style attribute.

2.) You asked about the most correct way to do this is.

This would be to put all html markup in templates.

3.) How to get around this

If you don't want to build a custom twig template for this, you can use an inline template instead:

$variables['book_now_widget'] = [
        '#type' => 'inline_template',
        '#template' => '
{{ var1 }}
',
        '#context' => [
          'var1' => 'bla bla bla'],
];


Restructure Language Prefix I'm building an international site and am running into trouble with the language detection. I need to have urls structured like the below examples for SEO purposes, but nothing I've found will allow for that. I wrote a little module that hooked into pathauto to prepend the code to the alias, but it didn't seem to be recognized... I'm using Organic Groups and Domain Access to manage the multiple countries, and Entity Translation and i18n for the languages. I also have Global Redirect in place to help keep out duplicate content links.
One requirement is that for some countries the default language should not be prefixed at all.

Has anybody had experience with urls like this? It seems like it should be possible without hacking into the core...

Country     |   Language    |   URL

Austria     |   German      |   www.domain.com/at
Belgium     |   Dutch       |   www.domain.com/nl-be
Belgium     |   French      |   www.domain.com/fr-be
Canada      |   English     |   www.domain.com/en-ca
Canada      |   French      |   www.domain.com/fr-ca
........
Global      |   English     |   global.domain.com/en
Global      |   French      |   global.domain.com/fr

I was able to accomplish this by creating a new language negotiation provider. It was mostly a matter of just copying the hooks and callbacks with only minor changes and a lot of trial and error. There wasn't much documentation that I could find on it...
The only thing is that the first part of the url MUST be a language, though it can also be a directory.


How can I re-install a module? I am creating on Drupal 8 module. I have used a custom table to store the data collected from forms.
Somehow during installation, tables are not created due to an issue in the install file. Now I have fixed the issue, and I want to install the module again.

How can I re-install a module?

From this and this discussions, I know the Disable module functionality has been removed.

Is there any other way to re-install a module so that its database tables are created?

The Devel module can also help here.

It makes a "Reinstall modules" page available at /devel/reinstall, which lets you re-install modules in bulk.

It's also worth mentioning Drush; dis (obviously) doesn't work any more, but pm-uninstall and en still do. And if you have Devel installed, you can invoke a reinstall with

drush dre module1 module2


After migration the login form no longer submits, why? I have been working on a Drupal 7 site on localhost (via WAMP) for some time now. Recently I wanted to migrate this website onto a new machine and continue working on it there. The steps I took:

I exported the MySQL database (SQL file)
I did a copy of the entire website (everything in the "www" directory)
I installed WAMP on the new machine
I pasted the entire website into the new "www" directory
I imported the previous database through PHPMyAdmin

Now when I go to localhost the website appears as per on the old machine, but when I try to log in using the previous user accounts it does not work. Specifically, when I type the username and password into the login form and hit the login button, nothing seems to happen. The loading icon appears in the tab but then the fields simply get emptied; there is no message saying incorrect log in details or anything, even if I use login details that I know aren't correct.

In the database the user accounts are clearly there, along with all of the other content. If I click on any links to the previous content I get taken to the content without any issues. Any suggestions on what could be going wrong here?

Please have check with your php.ini file as per old system & your new server by calling php phpinfo(); and look in the "Loaded Modules" for mod_rewrite.

Please refer this link it may helps you.


Command "generate:module" is not a valid command name I have this problem when I run command drupal generate:module. I don't know why, despite everything I did was suggested on the documentation for Drupal Console.
I don't see all the possible commands, when I run drupal list.
Available commands:
  about                      Displays basic information about Drupal Console project
  chain                      Chain command execution
  check                      System requirement checker
  exec                       Execute an external command.
  help                       Displays help for a command
  init                       Copy configuration files.
  list                       Lists all available commands
 debug
  debug:chain (dch)          List available chain files.
  debug:settings (dse)       List user Drupal Console settings.
  debug:site (dsi)           List all known local and remote sites.
 develop
  develop:contribute         Download Drupal + Drupal Console to contribute.
 generate
  generate:site:alias (gsa)  Generates a site alias.
 quick
  quick:start                Download, install and serve a new Drupal project
 settings
  settings:set               Change a specific setting value in DrupalConsole config file
 site
  site:new                   Download a new Drupal project

I have faced the same problem this works 100 %  :

open the shell and  cd to projectFolder
run this command :

   composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader

then run this command :

   composer update drupal/console --with-dependencies

run drupal list command again, and you'll find the list of all commands.

! this steps must be repeated with each project.


How to create wrapping menu tabs with CSS in Omega I'm using the menu api (MENU_LOCAL_TASK) to create tabs in Drupal 7. In Omega, I can't figure out how to wrap the tabs in css so that they are responsive. I'm new to Omega. This was easily accomplished in other themes.

It appears that the default system.menus.css in Drupal sets the white-space property to:

white-space: nowrap;

The default value for white-space is normal.  So, if you set the white-space property on your menu's UL to white-space:normal they will wrap when your screen size gets smaller.

I placed the following in my global.css.

ul.primary {white-space: normal; }


How to make my site's categories appear in Google results? I would like my site's categories to appear in the Google results.
For example the bbc.co.uk has the categories "News","Learning English", etc.

Is there any module for this? Has this to do with RDF, microformats, or rich snippnets?

Drupal is fantastic for building SEO sites but still I think you can not do this.
Google does this.
The official source is:
http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=47334


Upgrading to core 8.8 results in a path alias error I have been trying to upgrade a site from Drupal 8.7.7 to 8.8, and following the release documentation, I upgraded the core and pathauto module at the same time.
So my composer.json has the core set to ^8.8, and pathauto to 1.8.
After running drush updb I get the following error in the console:
 [error]  ParseError: syntax error, unexpected '::conf' in module_load_include() (line 73 of /var/www/html/docroot/core/modules/shortcut/shortcut.install) #0 /var/www/html/docroot/core/includes/module.inc(99): module_load_include('install', 'shortcut')
#1 /var/www/html/docroot/core/includes/install.inc(88): module_load_install('shortcut')
#2 /var/www/html/docroot/vendor/drush/drush/src/Commands/core/UpdateDBCommands.php(41): drupal_load_updates()
#3 [internal function]: Drush\Commands\core\UpdateDBCommands->updatedb(Array)
#4 /var/www/html/docroot/vendor/consolidation/annotated-command/src/CommandProcessor.php(257): call_user_func_array(Array, Array)

When I visit the front-end of the site I see the following:
Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: Unable to replace alias "path.alias_whitelist" with actual definition "path_alias.whitelist". in Symfony\Component\DependencyInjection\Compiler\ReplaceAliasByActualDefinitionPass->process() (line 57 of /var/www/html/docroot/vendor/symfony/dependency-injection/Compiler/ReplaceAliasByActualDefinitionPass.php).

Any idea how can successfully upgrade from Drupal 8.7.7 to 8.8?
Note: I still have a backup of the site and db, so an explanation on the upgrade would also work.

Pathauto 8.x-1.6  is the only version working with both Drupal 8.7 and 8.8. So first update Pathauto to this version, then update core and then update Pathauto to the current version. Run drush updb in each step. See the change record http://drupal.org/node/3089457.


How to import massively taxonomy terms? I have taxonomy terms installed and there I have article categories listed.

I have a lot of categories and articles. Now I need to import more categories from .txt file.

What is the best way to do this? I don't want to create these categories one by one.

I use in every of my projects the Taxonomy Manager module, among its features you can find:

mass adding of new terms
dynamic treeview
mass deleting
moving of terms in hierarchies


How do I configure front page? I have a new installation and I have "No front page content has been created yet".  How do I configure this front page?  How do I give a new user the ability to create their own blogs whilst also preventing them from having full control of the system?

Build Your Own Content Type

Create a Blog Content Type:

Admin > Structure > Content Types > Add Content Type (yoursite.ca/admin/structure/types/add)
Put "Blog" as the name of the content type
Adjust the opitions, (Submission form settings, Publishing options, Display settings, Menu settings), accordingly
Add the fields you want. If you want Tags, you could add a Taxonomy reference field

To allow users to make blogs, but not anything else:

go to Admin > People > Permissions (yoursite.ca/admin/people/permissions)
scroll down to the Node Section
select permissions, normally Blog: Create new content and Blog: Edit own content at least, for the role you want, (or AUTHENTICATED USER, which is every logged in user)

Use Core Content Type

There is already a core content type called article that has the following fields:

Title
Body
Image
Tags

Instead of making your own content type, you could just use this one.

To allow them to make blogs, but not anything else:

go to Admin > People > Permissions (yoursite.ca/admin/people/permissions)
scroll down to the Node Section
select permissions, normally Article: Create new content* and Article: Edit own content at least, for the role you want, (or AUTHENTICATED USER, which is every logged in user)

Remove front page message

A couple of options. The most elegant is to make a landing page and set that page as the "welcome" page at Admin > Configuration > System > Site information (yoursite.ca/admin/config/system/site-information)

Other options:

a module
CSS (Set display: none on the element)
A view. Follow these instructions.
Or scroll to the top of the mentioned link and read the forum. There are a ton of alternatives.


Theming a webform file upload widget I'm trying to replace the upload and remove buttons in a webform file upload widget with visual icons.

I'm having trouble for a number of reasons but the most confusing is this:

I don't see where in the markup the "Browse..." and "no file selected" text is coming from? I've tried altering the $variables['element']['upload_button']['value'] in hook_preprocess_webform_element and I didn't see any change in the value of the button or description.

If I remove type="file" and change the type to text, the "no file selected" note disappears too.

I have no idea what's going on.

For reference here's what I'm going for (left is after file upload, right is before file upload):

I'm using Drupal 7, Webform with Civicrm, and AutoUpload.

It is more likely a Javascript / jQuery related questions rather then Drupal.

The button label and text is defined by the browser which you cannot tweak in Drupal. But with Javascript / jQuery, you can override and take over event for creating your own file upload button.

Since jQuery is included in Drupal, a jQuery library should be suitable for you. jQuery File Upload is one of the best library for this purpose.

I found there are 2 contrib modules. They are jQuery File Upload and jQuery Upload FAPI.


Custom redirect for form-edit displayed in Views header I have a content type called 'Checklist' which I bring forward using Views, in it's node-edit form.

I wrote PHP code within the header in order to do this, here it is:

<?php

    $view = views_get_current_view();
    $arg0 = $view->args[0];

    $nodeToLoad = $view->result[0]->nid; //I get the node to load from Fields within my view
    module_load_include('inc', 'node', 'node.pages');

    $node = node_load($nodeToLoad);
    dsm($nodeToLoad);
    $edit_page = drupal_get_form('page_node_form', $node);

    $edit_page['additional_settings']['#access'] = FALSE;
    $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';
    print drupal_render($edit_page );

    function redirect_submit($form, &$form_state){
        $form_state['redirect'] = 'www.google.com';
    }
?>

Now what I want is to add a custom redirect upon saving this particular form.

I've tried this to no avail:

    $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';
    print drupal_render($edit_page );

    function redirect_submit($form, &$form_state){
        $form_state['redirect'] = 'www.google.com';
    }

Is it possible to this within the Views header?

Notes:

I have also done this with the Rules module but I'd like to learn
if it's possible to do with PHP code in the Views header so I don't
split functionality in 2 parts of my project.
This can also be easily done using a custom hook but again, if it's
possible to do this within the Views header then that's the trick I'm looking
for.

Thanks.

You could to use hook_form_FORM_ID. Something like this:

function mymodule_form_page_node_form_ater(&$form, &$form_state, $form_id){
   if(current_path() == 'page/where/my/view/is'){
     $form_state['redirect'] = 'page/to/redirect';
   }
}

If you don't want to use a hook, you can do something like this:

 $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';

Then,

 function redirect_submit($form, &$form_state){
  $form_state['redirect'] = 'path/to/rediect';
 }

Still it is bad practice to inlcude php in your views header. You should implement a custom area handler.

How to create a view area handler
https://api.drupal.org/api/views/handlers!views_handler_area.inc/group/views_area_handlers/7
https://oliverhuynh.wordpress.com/2011/06/23/custom-views-handler-drupal-7-template/


Ubercart email notification to store owner when order submitted I am new to Ubercart (we are installing and configuring on a Drupal 6 site) and have all of the store built out. I am attempting to set up a notification email to the store owner when an order is placed. I would think this is a built in configuration for ubercart... however for the life of me I can't find it.

Is there an Ubercart extension module which does this? Or should I configure this through Rules? I know there must be an existing and proven method for this in Ubercart somewhere.

You can use "Conditional Actions" to achieve this.

Its available under Store Administration / Conditional Actions.
I believe there is a preconfigured conditional action for your request in Ubercart. Maybe you just need to enable it.

If not just create your own.


og membership role is not displayed in views I'm using organic group module and I have 3 og membership types:

'member'
'non-member'
'visitor'.

I created an view which shows me all user group listing under one group which includes users role also but it is not displayed.

In view I added an Relationships as 'OG membership: OG membership from User ' and added filed for the same.

To work with user-roles in a view, you also need the relationship "OG membership: OG Roles from membership", where you have to set the relationship to your previously added "OG membership from user"-relation.

After that you are able to display the user's role or filter by user-roles. Hopefully this information was helpful for you.


Altering select elements to include data-img-src I am trying to create a content type with select list options that are replaced by images that you can pick.

Plugin here http://rvera.github.io/image-picker/

How would I go about altering the option element to include the data-img-src option?

<option data-img-src="img/01.png" value="1">  Page 1  </option>

Any help would be appreciated.

Looking at:

http://api.drupal.org/api/drupal/includes%21form.inc/function/form_select_options/7

It appears there's no way to add your own attribute to the select option from the form builder.

You may need to override theme_select to call a custom select_options handler instead, that checks some of the form data and adds the attributes to the option element.

http://api.drupal.org/api/drupal/includes!form.inc/function/theme_select/7


How do I implement hook_page_alter() in a module? I'm trying to add a piece on content to the $page['content'] variable, but it's just not working and the examples are not helping me. My code is the following:

function my_modulename_page_alter(&$page) {
    $page['content'] = $extracontent . $page['content'];
}

dpm() doesn't allow me to see the available variables. What am I doing wrong?

Try using hook_page_build(&$page). hook_page_alter(&$page), which is called directly after it, is meant for themers to use after all the modules are finished with their business.

I just implemented function MODULE_page_alter(&$page), and it worked in the module as expected.
Did you clear the cache so the module is registered?


Drupal 6, adding a admin menu? I have a new module I made called kameleon_create_report, and I want to add a menu item to Reports. So I created my .module

<?php
function create_report() {
    print "test";
}

function kameleon_create_report_menu() {
    $items['admin/reports/orderreport'] = array(
        'title' => 'Order Report',
        'page callback' => 'create_report',
        'weight' => 1,
        'type' => MENU_LOCAL_TASK
      );
}
?>

And the info

; $Id$
name = Create Report
description = Report generator for orders
core = 6.x

But it's not showing up, even after a refresh.

You're missing one of either access callback or access arguments:

From the hook_menu() docs:

"access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments'

Sorry to paste so much but it's all relevant, the last sentence in particular.

Choose a permission that applies to your site and added it to your menu item:

function kameleon_create_report_menu() {
  $items['admin/reports/orderreport'] = array(
    'title' => 'Order Report',
    'page callback' => 'create_report',
    'access arguments' => array('access content'), // This is almost certainly NOT the permission you want to use, choose one with restricted access.
    'weight' => 1,
    'type' => MENU_LOCAL_TASK
  );

  return $items;
}

Also as Attiks points out you've forgotten to return $items from the menu hook.

Finally, simply refreshing the page won't work when you add a menu item (they are cached), so you need to clear Drupal's caches to see the new item.


Lightbox2 doesn't appear in the page I want to add Lightbox2 from http://lokeshdhakar.com/projects/lightbox2/ to my page, but following instructions (adding a JavaScript, and a CSS file) doesn't work.

I thought I did all correctly, but when I click on the image, it doesn't show any popup.
What's wrong with it?

There's also a Lightbox2 Drupal Module that integrates with various other modules. And you don't need to update your Drupal's jQuery.

Here's the documentation since I don't really know how you're intending to use Lightbox2 on your website.


Feeds CSV import error I am trying to import a CSV from a url using the feeds module, I set everything up but when I start the import I get the following error:

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: XXXXX StatusText: OK ResponseText: Fatal error: Unsupported operand types in XXXXX/sites/all/modules/feeds/includes/FeedsConfigurable.inc on line 149

I have traced that error to this code, specifically the last line:

  public function getConfig() {
    $defaults = $this->configDefaults();
    return $this->config + $defaults;
  }

Any idea why I am getting this error?

I removed the default mappings because they were for an RSS feed, with GUID title etc....Could this have something to do with it? Are those required?

Are you running the alpha-4 or the current dev version of the feeds module? There have been a number of tickets discussing the same error condition you are having with node_save on import that coalesced around this issue on Drupal.org with a resulting patch committed to the current dev branch. You can try downloading the current dev branch of feeds (almost a year older now than alpha-4) or applying the patch at #25 in the above issue if you don't want to accept all of the updates since the last alpha release.


How to add link internal or external to an image in a view for a slideshow? I need a slideshow and sometime the images need to have a link. This link might be external or internal and it is posted by users. I use rewrite results in my view. However, sometimes the picture does not have a link. So this does not work for me.

I am using Drupal 7, Views, link and slideshow, picture module. My content type has the following fields:

field_slideshow_image
field_link_in_picture
text_slideshow

I try used another modules but I need to use the picture module to make my pictures responsiveness.  Other modules require that use the Formatter in views and picture module uses its own format.

I solved using theming in the view. I use the template in the image field. I ended up with a template like views-view-field--field-slideshow-image.tpl.php.

  <?php
//dpm($row); only work if devel module enabled

$url='';

if (!empty($row->field_field_link_in_picture_)){

    $url=($row->field_field_link_in_picture_[0]['raw']['url']);

}

if (!empty($url)) {
     echo "" .$output .""; //print image with link
}
else {
    print $output; //print image
}

?>

If someone knows a better way to do this please feel post it here. If I am not doing something in the Drupal way please let me know or you have another way to accomplish this. I would love to hear it :)

If you know little  about theming views you can check this video to understand better
Theming Views


Importing nested XML using Feeds XPath Parser I have some XML formatted as such:

<item>
    <title>Name</title>
    <id>12</id>
    <upgrade>
        <id>13</id>
        <level>2</level>
    </upgrade>
    <upgrade>
        <id>14</id>
        <level>3</level>
    </upgrade>
</item>

Ultimately from this example I want 3 nodes:

Title: "Name (1)" GUID: 12
Title: "Name (2)" GUID: 13
Title: "Name (3)" GUID: 14

I'm quite happy to do 2 runs of the file if necessary. I have one importer at the moment which sets up the "Name (1)" items. This works perfectly.

I have a second importer set up which I can successfully create the secondary "upgrade" nodes but only if I use \item\upgrade as the context, at which point I lose the title element so the nodes come through as " (2)", " (3)" etc.

If I use \item as the context like the initial importer, I can't seem to loop through the upgrade XML nodes.

Answered on drupal.org

Import will need to be done using the context \\item\upgrade.

Then to target the title from the parent node, use ..\title.


StringOverrides doesn't change the text in DCommerce "Add to Cart" Button Seen a lot of references to the hook_form_alter function on how to apply this, but many of the posts are aimed at more seasoned developers. I know enough to know that I need either a custom module to change these, but I don't know where to find the form id's on the buttons to change.

I was also pointed in the direction of the StringOverrides module, but this doesn't effect the changes I want on the buttons, only where the terms I want appear in plain text, as opposed to what I'm learning is hard-coded into the Commerce Modules.

So...a) how do I find the form ids to make a module to change these buttons? and b) how to get String Overrides to actually change the text on the buttons?

The fields I was trying to change ended up being hard-coded into drupal commerce, such that string Overrides, and even the Commerce Cart Overrides modules didn't help me get done what I needed to do completely.

So...I applied the hook_form_alter() functions in the bartik theme, because I couldn't get them to work in a stand alone module, although from what I read this would be better practice and then you don't have to remember what you changed where if you want to change themes etc.

So, combination approach got done what I needed in the end. Have to say, overall documentation is pretty opaque for a relatively easy fix and from googling, a relatively around a common problem.

Code snippet that might help:

function bartik_form_alter(&$form, &$form_state, $form_id){
dpm($form_id);
dpm($form);
if (commerce_form_callback($form_id, $form_state) == "commerce_cart_add_to_cart_form"){
$form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value']=t("Add to Inquiry List");
}
if(strpos($form_id, 'views_form_commerce_cart_form_default')===0){
$form['actions']['submit']['#value'] = t("Update List");
$form['actions']['checkout']['#value'] = t("Submit List");
}
if(strpos($form_id, 'commerce_checkout_form_checkout')===0){
    $form['buttons']['continue']['#value'] = t('Proceed to final list submission.');
    }
if(strpos($form_id, 'commerce_checkout_form_review')===0){
    $form['buttons']['continue']['#value'] = t('Submit your inquiry list');
    }

}


what's are these "@name" and "@site-name" token-things in email_example.module and how do they work? In the dgo.to/example module's email_example.module's hook_mail() function there's this line:

      $message['body'][] = t('@name sent you the following message:', array('@name' => $user->name), $options);

I haven't seen @thing used that way before?  How does that work?  What convention is that?

Please refer to the official D8 Sanitizing Output Documentation.

From the documentation page

There are three available placeholders in Drupal 8:

@variable: When the placeholder replacement value is a string or a MarkupInterface object
%variable: When the placeholder replacement value is to be wrapped in em tags.
:variable: When the placeholder replacement value is a URL to be used in the "href" attribute

You can learn more about these placeholders in the FormattableMarkup::placeholderFormat() documentation.

EDIT FOR DRUPAL 7:

See this documentation https://www.drupal.org/docs/7/api/localization-api/dynamic-strings-with-placeholders

The variables/tokens available for use as replacements is dependent on the context of the surrounding code and whether or not the script is called via Apache or from the command line.


Display blank date in hook_form I am creating a custom page with hook_form and using the datatype
'#type' => 'date,

I would like to make that field required.

AND, I want it to initially display blank.

Without #default_value specified, the default is today. How do I, in effect, make the default_value NULL?

You can use a #pre_render function on that field to unset the values and add an empty option on the 3 select boxes.

$form['start_date'] = array(
    '#type' => 'date',
    '#title' => t('Date'),
    '#description' => t('Your field description ...'),
    '#required' => true,
    '#pre_render' => array('_YOUR_MODULE_form_pre_render_date'),
);

function _YOUR_MODULE_form_pre_render_date(&$element)
{
    // Don't put empty values if a date has already been set
    if (date('Ynj') !== implode('', array_values($element['#default_value']))) {
        return $element;
    }

    // Loop through each field, add empty option and unset value
    foreach (array('year', 'month', 'day') as $field) {
        if (!isset($element[$field])) {
            continue;
        }

        unset($element[$field]['#value']);
        $element[$field]['#default_value'] = '0';
        $element[$field]['#options'] = array(
            '0' => '',
        ) + $element[$field]['#options'];
    }

    return $element;
}


Drupal 7 Form API file field - not recognizing the imported file function test_data_import_form($form, &$form_state) {
    $form = array();

    //$form['#attributes'] = array('enctype' => 'multipart/form-data');

    $form['import_data'] = array(
        '#type' => 'file',
        '#title' => t('Upload data file'),
        '#size' => 22,
        '#required' => TRUE,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#validate' => array('test_data_import_validate'),
        '#submit' => array('test_data_import_submit'),
    );

    return $form;
}

Please see my form code above. I am trying to import a file through this form, but the file I am trying to import is not recognized as it is throwing "Required field error". Please help me with this.

I tried #file_managed instead of the file, and then I am able to upload the files into the application. But, this option stores the file in managed_file table in the database with a temporary storage.
The file details are not visible in the dsm() (devel module).


How to implement global messaging system in drupal for multiple sites? I have more than 100 sites that need to be maintained. So I am looking for way to put up a notice message for this group of sites. For example: We are having maintenance scheduled for tomorrow 10 PM. The message will be persisting for a time being for all the sites.

Here I am assuming that there should be a central node from where we can push a message to all sites at once and delete when required.

So, I am looking for some help if there is already existing set of tools or way I can implement the workflow.

  I have tried Drupal Remote Dashboard module, the module seems to
  offer site monitoring from master node (site), but it doesn't seem to
  offer the global messaging option.

The nice thing in the "Drupal Remote Dashboard" module that you can run cron on your sites, so I would suggest that you build a custom messaging module that pull messages from master site (using cron to fire that).
- you can use services module to push your messages out


D7: Batch resave menu items Is there a way to resave all items in a particular menu batch-style?

I'm trying to avoid saving each menu item manually, there are so many of them...

There isn't a menu-specific function (that I know of) but you can use the aptly named menu_rebuild() function to rebuild the entire menu cache in one go.


Remove All Unwanted js and css files from theme I create a website based on Drupal. When I look at the JavaScript and CSS files loaded from Drupal, I see many unwanted files loaded. I want to force Drupal to load only those files added to the .info file and remove everything else. I think I can achieve it by using hook_js_alter() but I want to know if there is a better solution.

Drupal only has one sanctioned mechanism for removing specific assets, regardless of the motivation for doing so.

For CSS:

hook_css_alter

For JS:

hook_js_alter

To remove all style and scripts except .info style and script use below codes:

function hook_css_alter(&$css) {
    $themes=list_themes();
          foreach($css as $key=>$item) {
            if (!in_array($key, $themes['yourthemename']->stylesheets['all'])) {
                unset($css[$key]);
            }
        }
}

function hook_js_alter(&$js) {
    $themes=list_themes();
    foreach($js as $key=>$item) {
        if (!in_array($key, $themes['yourthemename']->scripts)) {
            unset($js[$key]);
        }
    }
}

If the theme/module is custom, then obviously you can just remove the offending code manually if that makes more sense.


Programmatically setting a webform submission to draft in presave I am trying from within a hook_webform_submission_presave() programmatically set a webform submission to draft.  We are creating an event registration system with webforms and some events require approval.  The thought is if an event requires approval we would set submissions to draft and admins could then "approve" them by making them no longer drafts.

Maybe there is a better way to handle this functionality and i'm open to ideas though I am not sure why this cleaned up hook below doesn't set submissions to draft mode.

function lebow_events_webform_submission_presave(WebformSubmissionInterface $webform_submission) {
  $current_data = $webform_submission->getData();
  $current_data['in_draft'] = TRUE;
  $webform_submission->setData($current_data);
}

Turns out I need to do this to save draft, the setData is only used to set element data.

$webform_submission->set('in_draft', TRUE);


What hook should I use to attach a script to a content type? I have this function from a standalone php script that redirects the user based off the user agent. In the process of merging this into Drupal and the script only needs to execute for a specific content type. Not 100% sure what is the best hook to use: hook_node_presave(), hook_load() or hook_node_view()?

Or should I run this as a template pre-process since this script requires the JS window.location embed?

Part of the code attached:

$web_user_agent = $_SERVER['HTTP_USER_AGENT'];
$current_page = $_SERVER['REQUEST_URI'];

if (!$web_user_agent = '[User Agent Placeholder]') {

    die;

} else {

    echo('<script type="text/javascript">

    if(self==top) {

            window.location = "'. $redirect_url .'";

    } else {

    }
    </script>');
    die;
}

It depends on how you want to approach it. Clive's question is still relevant, Javascript redirects are neither great or optimal. However, if it must redirect based on a User Agent, Javascript might be the only option.

I would advise you to do the agent detection on the client side, as the server value may not always be accurate. Your code above won't work.

To load a script based on content type, you can do:

function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'mytype') {
    $variables['#attached']['js'][] = array(args);

    // or

    drupal_add_js('path/to/script.js');
  }
}

Your script itself also needs to be in a closure:

/**
 * @file
 */
(function () {

  "use strict";

  // All the JavaScript for this file.

})();

If jQuery or the Drupal scope is needed:

/**
 * @file
 */
(function ($, Drupal) {

  "use strict";

  // All the JavaScript for this file.

})(jQuery, Drupal);

See the docs page for more:

https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7
https://www.drupal.org/docs/develop/standards/javascript/javascript-coding-standards


How do I build a user table with aggregated article data? I'm new to Drupal, and I want to make an overview over aggregated user data related to the articles they have written.

I basically want to build a table like this:

------------------------------------------------------
| user | articles published | articles with comments |
------------------------------------------------------
| bob  |                 12 |                      3 |
------------------------------------------------------
| sue  |                 34 |                      0 |
------------------------------------------------------
| kim  |                  0 |                      0 |
------------------------------------------------------

What is the best way to make a table like this? Is this something I need to make my own module for?

Would it be possible to aggregate this with an existing module?

Welcome to the Drupal StackExchange !

You can achieve this with some custom php code and couple of queries.

<?php

   $articles_publishers = db_query("SELECT DISTINCT u.uid FROM {node} n LEFT JOIN {users} u on n.uid = u.uid where n.type = 'article'");
   foreach ($articles_publishers as $articles_publisher) {
     $publisher = user_load($articles_publisher->uid);
     $username = theme('username', array('account' => $publisher));
     $articles_published = db_query("SELECT count(*) FROM {node} where uid = :uid and status = 1 and type='article'", array(':uid' => $articles_publisher->uid))->fetchField();
     $articles_published_with_comments = db_query("SELECT count(*) FROM {node} n INNER JOIN {comment} c ON n.nid = c.nid where n.uid = :uid and n.status = 1 and n.type='article'", array(':uid' => $articles_publisher->uid))->fetchField();

     // Theme the information with above results

     print "Username :" . $username;
     print "articles published :" . $articles_published;
     print "articles with comments :" .  $articles_published_with_comments;
   }

?>

use above code in a module custom block or Add Block with php option to display the information.

Hope it helps.


Taxonomy terms disappearing I'm working with Drupal 8 Taxonomy terms. I'm managing them in the backend through the default taxonomy pages.

I'm doing this for a project where I need to label rows in a custom added table.

This all worked pretty fine until suddenly, just out of nowhere, the terms disappeared. I added terms, and when I returned to the list page of the specific taxonomy library, they where gone. They were still in the database, and \Drupal\taxonomy\Entity\Term::loadMultiple() still returns them.

I've done a lot of digging, but I'm out of ideas. I need some pointers to continue my search.

I found the issue. The taxonomy terms where stored without the taxonomy_term_hierarchy information. This info is needed for the list of terms in the admin list to determ the relations between the terms.

This was caused by me, I've removed the hierarchy field from the form. This caused Drupal to not save this information at all. There are no default values or something like that here.

https://www.drupal.org/files/drupal7-db-schema.png


How to create Drupal 7 clean pager links? In my last project my client aksed me to do clean pagers in his website. However drupal 7 handles pagination using ?page=1 but I need page/1 insted of that. Do someone have experience of creating clean pager links using pager alter and .htaccess. I see lot's of modules but they are not working properly. I tried with clean pagination, smart paging modules but they did not work properly, Then I tried to do it by custom way through htaccess file and altering pager link, but can't get success.

http://someexample.com/hello-node/?page=1 to
http://someexample.com/hello-node/page/1

Any help will be appreciated.

Hi please check the following link Clean Pagination, Hope this will help you.

  Clean Pagination is a very simple module that allows you to enable clean URL pagination for specified pages. The way Drupal typically works, if you had a view with the URL 'my-view', subsequent pages would normally use a query to pass the page number, as in 'my-view?page=2'. When Clean Pagination is being used for a page, it will create a url like 'my-view/2'.


Change a div content after click on another div I would like to achieve, if is possible, change the content of a div with another content of the same type. For example I have two nodes whose content type are "news" but i want them to render on the same page after clicking on their links.

Tried to achieve with jQuery but i have an undefined error.

This is my code:

  $(document).ready(function() {
    var selector = '.title-noticia a';

    $(selector).click(function(e) {
      e.preventDefault();

      $.ajax({
        url: $(this).attr('href') + '?ajaxrequest',
        success: function(data) {
          $('.region-content').replaceWith(data);
        }
      });
    });
  });
})(jQuery);

But it doesn't seem to work, is there any way to achieve that without the use of AJAX links API? (It's to slow for me).
Thanks in advance!!!

UPDATE 1:

After some research, i managed to make it work (on the console), but the content doesn't replace on the page view.

This is my new code:

(function ($) {
  Drupal.behaviors.mybehavior = {
    attach: function (context, settings) {

      $('.title-noticia a').click(function(e) {
        e.preventDefault();

        $.ajax({
          url: $(this).attr('href'),
          type: 'post',
          data: {
            view_name: 'articulos_actualidad',
            view_display_id: 'page_2'
          },
          dataType: 'json',
          success: function (response) {
              $('.region-content').replaceWith(data);
              Drupal.attachBehaviors(); //Check on the console
          }
        });

      });
    }
  }
})(jQuery);

But the only result i have is:

XHR finished loading: POST "http://www.example.com/somerenderedpage".

So it literally works but i cannot see the results on the page.

Hope you can help me. Thanks!

UPDATE 2:

I will post what i want to achieveI have a headache :) trying to make it work. What i want to achieve is to display the content of the selected link on a div. So i made a graphic so you can understand.

When i click on link 1, i want to display on the main div the content of the link 1, the same with link 2, 3 and X.

Is there any way to achieve that? tried with jQuery AJAX but the performance is poor, the same programatically making an ajax call.

I know i can do something like an slideshow but with content, but i cannot figure it out. Could you lend me a hand please? I will appreciate it. Thanks!

You need to conform to the coding standards and make it anonymous so it doesnt conflict with jQuery.

(function ($) {
  Drupal.behaviors.mybehavior = {
    attach: function (context, settings) {
      var selector = '.title-noticia a';

      $(selector).click(function(e) {
        e.preventDefault();
      }

      $.ajax({
        url: $(this).attr('href') + '?ajaxrequest',
        success: function(data) {
          $('.region-content').replaceWith(data);
        }
      });
    });
  });
})(jQuery);

See more: https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

Your behavior will be called automatically, so there is no need for $(document).ready.


How to create a chart about the number of node views per day (since last week)? I want to show my users a chart that lists the node views hit for that day (Content statistics: Views today), something like this:

So the user can see how many views each node of his had in each day of last week!

I'm using the Charts module for making the charts, using the Google charts API as the charting engine (library) and it works just fine.

Issue is, that I have no idea if it's possible to list last 7 days date in Views at all or not, let alone integrating it with Charts.

Any suggestions about how to do so?

Using the Charts module
Step 1: Create the tabular format of the view
First to address the "if it's possible to list last 7 days date in views at all or not" part of your question, you really need to first work on getting the view created correctly. That's also what's recommended in the Bonus tip within Steps to create charts using the views UI, i.e.:

You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first. ...

Step 2: Add the chart to your view
Do not try to start this step if you didn't first complete the prior step.
There is an issue which might help to answer this question, or at least to understand the challenge here. I.e. Graph node input over time (support date formatting on a continuous axis).
In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.
Using the Quant module
If using the Charts module you can't get it to work (or don't want to consider the suggestions above), then you may want to look at the Quant module as an alternative. Here are some excerpts from its project page:

... provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.
Provided charts:

Content creation
Comment creation
Content creation by type
Aggregate content creation
User creation
Page views (requires Statistics)
User shouts (requires Shoutbox)
User point transactions (requires User Points)
Group creation (requires Organic groups)
Group joins (requires Organic groups)
Invites sent (requires Invite)
Invites accepted (requires Invite)
Statuses shared (requires Facebook-style statuses)
Private messages (requires Private message)

Especially the "Page views* chart that is provided might be close to what you're looking for.
Using the Visitors module
If you're looking for info related to visitors of a website (registered users is a subset of them ...), the Visitors module might be a valid alternative to consider also (and/or addition to the above modules). In this case, all you have to do is to enable the module and review the various out-of-the-box reports (which include charts created with the pChart library).
The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module.
In this specific case, you probably would want to look at the Days of week report (and chart). Note that, as a bonus, you can specify the desired date filter (from / to) also.
Refer to the Visitors community docu for some more details.
Extra reporting features can be enabled via these sub-modules:

The Visitors GeoIP module, to also report about countries and cities.
The Visitors Browscap module, providing statistics on visiting browsers.

Evaluating other charting modules
If none of the above modules would work in your case, then you might want to look at the "Comparison of Charting modules" documentation.
Disclosure: I'm a (co-)maintainer of all modules mentioned above (and original author of the comparison),
I hope this does not violate the site's policy on self-promotion.


'Create Node' form as part of panelized page How can I add 'create node' to a panelized page?
I basically want to have the 'create x CT' form at the top, with a view of submitted nodes below.  What's the best way to achieve this with panels?  thanks

You have to add a Context Node add form to your panel and afterwards, you can select the appropriate edit form in the 'Form' section when you add content to the panel.


It is possible to revert a single item of the component programmatically? I've feature module which have thousands of entries and I'd like to investigate which item is taking the longest time.

Currently all my features takes over 5h to revert, and I assume it's mainly because of rules config components which there are over 700 (10-20sec each rule, so it's like 2-3h for rules alone) in a single module, and over 200 exported entityforms (which also is slow). This is already after fixes, because before it was taking over 8-10h (before the MySQL stopped with gone away error), but this was due to the bug with infinite loop (some Entity+Rules conflict), so disabling entity_rebuild_on_flush variable at least worked in terms of finishing the process. This is especially trouble when you're reverting your features during each deployment or building your local environment on daily basis which takes 5h.

So my plan is to revert only rules which I need (e.g. via hook_update).

I'm aware that you can use features_revert to revert a single component:

features_revert(array('module' => array('component')));

however it takes forever and I would like to know if it is possible to revert only single entry (e.g. foo_my_rule_x) of a component (e.g. rules_config), in other words - a single line of feature module, for example:

features[rules_config][] = foo_my_rule_x

and not anything else, using a standalone code or drush.

In order to revert, you need to remove a single component from the database, so the configuration from the code can be loaded instead.

So to revert a single rule, load the rule and delete it, e.g.

$rule = rules_config_load("my_rule");
$rule->delete();

This can be placed in hook_update().

Check Add drush rules-revert patch which provides such functionality for the drush command, e.g.

drush rules-revert my_rule

In addition, to revert all rules by not using Features module (which will take much quicker), you can try:

if ($rules = rules_config_load_multiple(FALSE)) {
  foreach($rules as $rule) {
    if ($rule->hasStatus(ENTITY_OVERRIDDEN) && !$rule->hasStatus(ENTITY_FIXED)) {
      $rule->delete();
    }
  }
}

So by deleting the rules from the database, they're loaded from the code.


Setting permissions via drush make; auto-copy settings.php? I'm using drush make to build out an installation profile, and it's working great, however, settings.php doesn't get created and files has the wrong permissions.

Is there any way to automate this further by creating settings.php and chmod'ing files?

Thanks!

make sure you go through all the options available at drush help make . This option should help you :

  --prepare-install   Prepare the built site for installation. Generate a properly permissioned settings.php and files directory.


Conditional Custom Text Filter plugin I have created a custom text filter plugin by extending FilterBase class. The process() function looks like

 public function process($text, $langcode) {
    // Get the current node to determine if it has the glossary field and if
    // that field is enabled.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node && $node->hasField('field_glossary') && $node->field_glossary->value) {

      // Get all the terms in the Glossary vocabulary.
      $terms = $this->getTerms('glossary');

      // Make all the replacements.
      $new_text = $this->doReplace($text, $terms);

      // Create a filtered text object with the updated text.
      $result = new FilterProcessResult($new_text);
      return $result;
    }
    else {
      // Don't do the replacement.
      $result = new FilterProcessResult($text);
      return $result;
    }
  }

I am letting editor to choose to turn off/on text filtering via plugin by creating a flag field as used in code $node->field_glossary->value. The problem comes when I need to check the field value on non-node page, as on node page I can get the node object and check the value but for other entites like blocks how can I get the source entity for text?

That's not so easy, because the filter is normally not aware from which field it is called from.

The token filter module does this trick:

/**
 * Implements hook_preprocess_HOOK().
 */
function token_filter_preprocess_field(&$variables) {
  if (isset($variables['element']['#object']) && $variables['element']['#object'] instanceof ContentEntityInterface) {
    $entity = &drupal_static('token_filter_entity');
    $entity = $variables['element']['#object'];
  }
}

The parent entity of the field is stored in a static variable and can be used in the filter:

  public function process($text, $langcode) {
    $entity = drupal_static('token_filter_entity', NULL);
    if (!is_null($entity) && $entity instanceof ContentEntityInterface) {
      // use entity
    }
  }

http://cgit.drupalcode.org/token_filter/tree/token_filter.module?h=8.x-1.x

This may not be the best solution for most cases. If possible look for a better place for the code where you have direct access to the entity. For example in hook_entity_view_alter().


Limit results of the entity reference I have been trying to find the solution to this problem. I am referencing a serial of nodes with entity reference, but I just want to display the latest 3 nodes. Is there any way I can limit the results of the entity reference? I need to have unlimited Number of values but just need to display the last 3 for that case. I am not using views.

I am using Drupal 7

Thanks :)

You can always use the Views: Filter by an entity reference view option from Entity selection mode and then create a view and set the number of items to 3.