How do I make the output of field X look like Y? I have a field of type X, and it's output is not quite the way I want to it to be. I would like it to look like Y instead. How can I do that?

I usually solve this type of problem by implementing a custom field formatter, which is what controls how a field is rendered.

Below is sample code to implement a basic single delta field formatter. It is used on normal "text" fields, and will simple output todays date, with a single setting for in what format to output the date.

Since this particular example does not actually use the field data, it's important to know that you need the field to have some value, or Drupal will ignore it.

// Declare a new field formatter.
function hook_field_formatter_info() {
  return array(
    'custom_current_date' => array(
      'label' => t('Current date'),
      'field types' => array('text'),
      'settings' => array('date_configuration' => 'm'),
    ),
  );
}

// Form API callback for the formatters settings form
function hook_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array(
    'date_configuration' => array(
      '#type' => 'textfield',
      '#title' => t('Date configuration'),
      '#default_value' => $settings['date_configuration']
    ),
  );

  return $element;
}

// Output a message showing what the current field settings are.
function hook_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  return 'Date config is ' . $settings['date_configuration'];
}

// Actual field output goes under the #markup key. Add a loop instead of the
// leading 0 to support multi-value fields.
function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];

  return array(0 => array('#markup' => date($settings['date_configuration'])));
}


Using Ctools, how do I render a managed_file from system form? I'm adding some fields to Drupals site-information form. Textfields and managed_file fields. Images are uploaded there and not in my panel panes edit form.

Now I want to make the additional fields I've added, or just the whole form be rendered in a custom panel content_type. I have no issue getting the textfields themselves using

$block->content .= filter_xss_admin(variable_get('phonenumber', ''));

however I also need to render my managed_file. How would I go about doing so?

Okay, it's not my day today :D

Here's how to do what you were asking:

// Load the managed file. You need this so you can get the URI.
$file = file_load(YOUR_FILE_ID);
// Generate the output.
$output = theme('image', array(
  'alt' => t('Your image alt title'),
  'title' => t('Your image human title'),
  'attributes' => array('src' => $file->uri),
));


How to allow access to page variant (Page Manager) if user belongs to list The Situation
I have an ECK entity called "Event" in my Drupal 7 site.
I have an entity reference field on Event that collects users who flag the Event with a non-global flag called "Sign up" via a rule.
I use Page Manager to control how an Event entity is shown to the users.
My context:
Edit relationship "User from Event (on Event: List of attendees [field_attendees]"
Event: Entity being viewed
Identifier: User from Event Attendees [field_attendees])
Keyword: event_attendees
Delta: 0
Here is the Selection Rule:
User: compare    logged_in_user is User from Event Attendees [field_attendees]
The Problem
As you can see, one of my Page Variants has a selection rule that checks if the logged_in_user is on the list of attendees but it doesn't work because the selection rule takes a "delta" and that means that it takes a hard coded integer to select one of the list. And if I leave this empty, it automatically takes "0" i.e. the first one in the list. There seems to be no option to set the delta to include all or any.
The Question
How can I create this selection rule to check if this user is 'on the list'?

Currently I'm using a selection rule that checks if the logged-in user has "flagged" the Event with a Signup. This works but checking if the logged-in user is on the list would be a waterproof solution.


How to create Taxonomy Term using Services? I've a vocabulary called Tags. I need to create Taxonomy terms under this vocabulary using REST service.

So What is the JSON format to create taxonomy term. Similarly what is the JSON format to update taxonomy term?

I'm using POSTER plugin (for Firefox) to post data.

Here are the parameters.

URL: [your path]/[end-point]/taxonomy_term.json

Content Type: application/json

Actions: POST

Here are the JSON formats.

To create Taxonomy Term

{
    "vid": "1",
    "name": "My First Tag",
    "description": "Term description",
    "vocabulary_machine_name": "tags"
}

To update Taxonomy Term

{
    "tid": "14",
    "vid": "1",
    "name": "My First Tag Edit",
    "description": "Term description changed"
}

Here tid is taxonomy id and vid is vocabulary id of the Taxonomy.

Hope it helps someone.


ahah and fieldset 'collapsed' state On my drupal 6 site I have the following fieldset in one of my forms ($cur_div_wrapper_name is a variable I have set to be "share_opp_with_rep_div"):

$form['add_rep_share_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Share with Rep'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
);

As you can see, the fieldset is collapsible and has a state of collapsed by default.

Inside of this fieldset I have two selects.  One of these selects ("share_with_rep") changes it's values when the other select ("share_with_rep_region") is changed.  I utilize ahah and the ahah_helper module to make this work.

$form['add_rep_share_fieldset']['share_with_rep_region'] = array(
    '#type' => 'select',
    '#title' => t('Region'),
    '#options' => $regions_lov,
    '#default_value' => $default_share_opp_region,
    '#ahah' => array(
        'event' => 'change',
        'path' => ahah_helper_path(array('add_rep_share_fieldset')),
        'wrapper' => $cur_div_wrapper_name,
    ),
);

$regions_lov is a variable containing an array of options for this select.

$form['add_rep_share_fieldset']['share_with_rep'] = array(
    '#type' => 'select',
    '#title' => t('Sales Rep'),
    '#options' => $rep_user_lov,
    '#default_value' => $default_share_opp_rep,
);

$rep_user_lov is a variable containing an array of options for this select.

The user has to un-collapse the fieldset in order to see the two selects.  When I change the "share_with_rep_region" select the other select ("share_with_rep") changes automatically.  This works fine.

My problem is that the fieldset does not keep it's un-collapsed state after changing the "share_with_rep_region" select, and the user has to click on the fieldset again to un-collapse it and choose a value for "share_with_rep".

Does anyone know if it's possible to pull the collapsed state of the fieldset and remember it so the user does not have to click it again to view the contents after changing the "share_with_rep_region" select?

Thank you!

I'd do something along the lines of checking the value of share_with_rep_region before defining the collapsed state of your fieldset. i.e.:

// whatever the default value of the select is before
// the user has interacted with it in any way
$default_value = '';

// set collapse true
$collapse = TRUE;

// assuming you're passing $form_state into your form definition, if not, do so
if ($form_state['storage']['add_rep_share_fieldset']['share_with_rep_region'] !== $default_value) {
    $collapse = FALSE;
}

$form['add_rep_share_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Share with Rep'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#collapsible' => TRUE,
    '#collapsed' => $collapse,
);

I hope this shows the basic idea behind what I'm trying to say: $collapse = true by default, IF the user has interacted with the form in any way, $collapse = false


How to limit the words in search api autocomplete suggestion? I have a requirement to limit the words to show up in row of autocomplete suggestion. Now its showing titles but problem is titles are too long and suggestions are covering entire width of the screen. So any way to limit it? I checked with HOOK_search_api_autocomplete_suggestions_alter hook but not getting what is the attribute to limit this feature. Any help will be appreciated.

Try below code, and you can trim $label as you want.

/**
 * Implements hook_search_api_autocomplete_suggestions_alter().
 */
function HOOK_search_api_autocomplete_suggestions_alter(array &$suggestions, array $alter_params) {
  $used_labels = [];
  /** @var Drupal\search_api_autocomplete\Suggestion\Suggestion[] $suggestions */
  foreach ($suggestions as $key => $suggestion) {
    $suggestion->setUrl(NULL);
    $label = $suggestion->getLabel();
    $suggestion->setSuggestedKeys($label);
  }
}


Drupal 6 on php 5.5 compatibility I have running 20+ Drupal 6 sites on php 5.4 without large issues, but what about php 5.5?

I am doing it.  The only problem I found was with Panels, but this post fixed it.  Also, I had to turn down the default error reporting, but I've not had the site crash.


Views Data Export Permissions Problem I have Views Data Export installed, which creates a CSV file attached to every node. This file has all of the data from a field collection field arranged as a CSV.

The only user that should be able to download this CSV file is the admin (user 1) and the user that created the node.

In Views Data Export, I can select Role as a permission, and assign it to all "Managers", but that means each "Manager" can download other Managers data if they get the URL right. Anyone wanting to maliciously steal data, or sneak a peak at how much their colleagues are earning can simply guess the URL of the CSV file.

How would I restrict this download to the author of the node?

I have tried installing Path Rules, and creating a Rule that checks that the path of the CSV ends with CSV, and then runs a condition to check that the Nid of the currently logged in user matches one created by the author, but the download happens automatically regardless. There doesnt seem to be a path check before it is downloaded.

Stuck here scratching my head, would welcome even the slightest suggestion, or just a fresh pair of eyes! Thanks.

OK, some progression...

I delved into creating a views custom access like so...

Added files[] = couples_page_custom_access_plugin.inc to a custom module info file

Added the following to couples_page_custom_access_plugin.inc

<?php

  /**
   * Access plugin that provides property based access control.
   */
  class couples_page_custom_access_plugin extends views_plugin_access {

    function summary_title() {
      return t('Couples Page Check User is Author');
    } // summary_title()

  /**
   * Determine if the current user has access or not.
   */
    function access($account) {
      return couples_page_custom_access($account);
    }

    function get_access_callback() {
      return array('couples_page_custom_access', array());
    }

  }

Then added this to a custom module...

  function couples_page_custom_views_plugins() {
    $plugins = array(
      'access' => array(
        'test' => array(
          'title' => t('Couples Page Check User is Author'),
          'help' => t('this is a custom access plugin'),
          'handler' => 'couples_page_custom_access_plugin',
          'path' => drupal_get_path('module', 'couples_page_custom'),
        ),
      ),
    );
    return $plugins;
  }

  function couples_page_custom_access($account = NULL) {
    global $user;
    $access = false;
    $account = user_load($user->uid);
    $node = node_load(arg(1)); // Get the nid from the URL of the CSV file.

    // If the UID of the currently logged in user matches the UID of the node author return true.
    if ($account == $node->uid) {
      $access = true;
    }
    return $access;

  }

But its not really working. If I set $access = true it works, and $access = false, it doesnt, so I know the plugin is working. It must be the logic in the last bit here...

function couples_page_custom_access($account = NULL) {
        global $user;
        $access = false;
        $account = user_load($user->uid);
        $node = node_load(arg(1)); // Get the nid from the URL of the CSV file.

        // If the UID of the currently logged in user matches the UID of the node author return true.
        if ($account == $node->uid) {
          $access = true;
        }
        return $access;

      }

Perhaps I am not getting the author uid of that node correctly? I will look into it.

I found the problem.

I was using user_load() in an earlier example, and was still using it rather than the uid.

The final access check should be...

function couples_page_custom_access($account = NULL) {
    global $user;
    $access = false;
    $node = node_load(arg(1)); // Get the nid from the URL of the CSV file.

    // If the UID of the currently logged in user matches the UID of the node author return true.
    if ($user->uid == $node->uid) {
      $access = true;
    }
    // Else check if the current user is admin so we can download what we like.
if (in_array('Admin', $user->roles)) {
  $access = true;
}
    return $access;

  }

I also added a check to return true if the current user is an Admin.

I really hope this helps someone else, and saves the time it took me to get to this!

Still, every days a school day!


Rule to send out content of newly created forum-topic or comment I have a rule that will send me an email with the username of the person that creates a new comment or forum-topic. However, I would really like the URL and actual content to show up in the email. How can I accomplish this in that order of importance. Because right now I have to click on content on the site and look for the newest items to find the new content.

Using rules, you can send the URL of the updated content as per the solution provided by @mohit_rocks, but I was not able to find a solution to send the content / body (full / teaser) in the mail, using rules.

If you wish to send the content of the body too, you'll need to take help of the Notify module.

Steps to enable the send mails with the content of forum/topic in mail with the help of notify module:

Download and install notify module.
Under admin > people > permissions, set give the permission of access notify to the user role you wish the mails to go to. Note: The users of these roles need to enable the notification to enable receiving of the mails. You can keep this role limited to admin and let admins decide who receives the mail by following next step.
Go to admin > config > people >notify and enable notification for forum content type:  If you set time less than the time of your cron run, still the mail will be sent on cron run.
Go to user > uid > notify (replace uid with the the user id of the user). Admins can go to admin > people select edit against any user, and go to Notification settings tab and check the following options:   You can check the Title + Body + Fields under Detailed settings section to send the values in fields as well.
To check the list of users who will receive the mails, go to admin > config > people > notify > users:
That's it! Now the selected users should start receiving the notifications mails with content!

Note: If you have revisions enabled for the content type, and want to be notified when the content is edited, then check this feature request I've made at the module's issue queue. I've also created a patch for the same. If you have such requirement, then you can test the patch. If you post your findings on the issue, it'll be appreciated!


Rule set username after changed user email I need an email registration system only in my drupal site.

I installed the module email_registration and I created a module like this http://www.grasmash.com/article/using-your-email-address-your-drupal-username to set the username like the own email address.

Now my user has: name: fra@ore.com email: fra@ore.com
But if the user changes is email address the username doesn't update. So if fra@ore.com changes his email to fra@ore2.com the username remain the same.

I tried to update the username by the Set a data value of Rules module After updating an existing profile but I dont know how set this action... Can you help me??

You can look at this:
https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_save/7

It will run after a user is created and if a user is edited.   You can update the data as required.


How do I translate the weekday in a date? I created a view from a JSON file; the dates in that file follow the 2020-07-28 20:00 format. I do a rewrite of the date to <span>{{ value_1|date("l d/m/Y") }}</span> and I get Tuesday 28/07/2020, but I want to get the weekday in Dutch.
Is there code for this?

Use the below example as a temporal solution, I'm not sure if this is the proper way. The approach is to split the problem.
{{ value_1|date("l")|t }} {{ value_1|date("d/m/Y") }}

Regarding the next link, the proper use of translation on twig is using "t" filter.
How do I translate strings in Twig templates?


Force existing users to complete profile after adding required fields I inherited a Drupal (D7) site with existing users. Now I want to add new fields to the user profile, but they will be required.

New users will have to fill out these fields when registering. Existing users will have to fill out these fields when trying to save their profile.

But what I would want is for existing users to be redirected to their profile page after logging in. Of course, I would also like to display a message on that page that they need to complete their profile with this new information.

Is this possible in Drupal?

I fixed this with the Rules Module.

First, I set the necessary fields in the user profile as required. That fixes it for new users that want to register.

Then, a little more complex, I used the Rules module for the existing user, with the following setup:

Event: user has logged in
Actions:

page redirect (to user/[account:uid]/edit)
show a message on the site (to clarify why the user was sent here)

Conditions:

One OR group with the following conditions:
Data value is empty (with site:current-user:field-lastname)
Data value is empty (with site:current-user:field-firstname)
etc.

This works perfectly. The only minor point is that when I add a required field, I also have to add a condition to the OR group manually.


How to join a path to a file in code, "windows safe" Given a hook (e.g. hook_theme()) and a path where something has to be looked up (e.g. templates), what is the cleanest way to deal with this?

I have the following directory structure:

sites/all/modules/mymodule

mymodule.module
templates

mymodule.tpl.php

When I define that path in code, I use the following code.

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    "mymodule"  => array(
    "variables" => array(),
    "path"      => $path . "/templates",
    "template"  => "mymodule"
  );
}

I want this code to work on Windows too, without having to do checks for OS inside that function.

Just use / as path separator: It will work on Windows, and any other OS.

PHP defines the DIRECTORY_SEPARATOR constant, but that constant is not used from Drupal core code, and Drupal works on Windows too.
A note on the parameters accepted from basename() says:

  On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).


How do I get the timezone form reference on a date field? In Drupal 7 I have a date field in a content type that has the Time zone handling option set to "Date's time zone".  Setting this option will render a drop down list of time zones in your date field.

I am trying to replace the list of core time zones with a smaller list for just the United States.  I found this post which works perfectly for overriding the timezone drop down list on the user profile page.  However, I have not been able to figure out how to get a reference to the timezone select list on a date field.

The timezone reference on the user profile field is:

 $form['timezone']['timezone']['#options']

If you print the $form variable to the screen you can clearly see the time zones in the above reference.

What I can't figure out is where the timezone options are in the form variable for a date field.  I would expect them to be in somewhere in

 $form['field_event_dates']['und'][0]

I do see a default value for the timezone at

 $form['field_event_dates']['und'][0]['#default_value']['timezone']

but I can't find "options" in there.

Any ideas where the "options" for the time zone are set in the form variable?

Use hook_date_timezone_process_alter in your custom module to do the magic, see below example and adapat if for you needs

function MODULENAME_date_timezone_process_alter(&$element, &$form_state, $context) {
  // add some logic here
  // keep only the needed values
  // dsm($element['timezone']['#options']);
  $element['timezone']['#options'] = array(
    'Africa/Abidjan ' => 'Africa/Abidjan',
    'America/Detroit' => 'America/Detroit',
  );
}


Rules to clear commerce cart on adding new item of a different product type I've several product type with corresponding product displays. The scenario is a case where there is only a product type per time on the cart. That is, you cannot  have multiple product types at the same on the cart. Hence, each time a new item is to be added, check if it is of the same type as the existing items in the cart. If it is add, if not clear cart before adding the new item.

What rule setting can help me in achieving this. Thank you.

Found answer to my own question. I discovered the conditional rules module and came up with this rule component for each product type:
{ "rules_empty_cart__consumer_g" : {
    "LABEL" : "Empty cart - consumer g",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "commerce_cart", "commerce_order" ],
    "ON" : { "commerce_cart_product_prepare" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-product:type" ], "value" : "store_item" } }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "commerce_order_contains_product_type" : {
                "commerce_order" : [ "commerce_order" ],
                "product_type" : { "value" : {
                    "product" : "product",
                    "book" : "book",
                    "food" : "food"
                  }
                },
                "operator" : "\u003E=",
                "value" : "1"
              }
            },
            "DO" : [
              { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } },
              { "drupal_message" : { "message" : "cart cleared!" } }
            ]
          }
        ]
      }
    ]
  }
}

What this does is it every time an item is to be added to cart it checks if there at least one item in the cart that is not of the same product-type as the product that is about to be added. If there is, the cart is cleared before the item is added, if not the cart remains unchanged and the new item added to the existing list on the cart.
For this check to happen irrespective of the type, a similar rule is created per product type.


How can I add a sub-array structure in my results? $_POST I'm building a form. In that form I have a lot of checkboxes. Normally, It's possible to make an array of some checkboxes (with name attribute).

<input type="text" name="reservatie[0][1]" />
<input type="text" name="reservatie[0][2]" />
<input type="text" name="reservatie[1][1]" />

Normally I would have this result with print_r($_POST);

Array(
    [reservatie] => Array(
        [0] => Array (
            [1] => value
            [2] => value
            )
        )
        [1] => Array
        (
            [1] => value
        )
    )
)

I tried to add the name attribute, but the $_POST takes the structure of $form. But how can I add a sub-array structure in my results?

foreach($result as $time) {
                    $form['reservatie'][$item->id][$time->id] = array(
                          '#type' => 'checkbox',
                          '#return_value' => 1,
                          '#default_value' => 0,
                          '#prefix' => '<td>',
                          '#suffix' => '</td>',
                          '#attributes' => array('name' => 'reservatie[0]['.$time->id.']')
                    );
                }

This is what I get:

array(42) {
  ["date"]=>
  string(10) "01/07/2016"
  ["reservatie[1][1]"]=>
  int(0)
  ["reservatie[1][2]"]=>
  int(0)
  ["reservatie[1][3]"]=>
  int(0)
  ["reservatie[1][4]"]=>
  int(0)
  ["reservatie[1][5]"]=>
  int(0)
  ["reservatie[1][6]"]=>
  int(0)
  ["reservatie[1][7]"]=>
  int(0)
  ["reservatie[1][8]"]=>
  int(0)
  ["reservatie[1][9]"]=>
  int(0)
  ["reservatie[2][1]"]=>
  int(0)
...
)

I managed to solve my own problem. It was a problem with the #tree.
I have to set #tree in the parents to true..

So if you want an array with the following structure:

array {
    ["parent"]=>
     array(4) {
        [1]=>
        array(9) {
          [1]=>
          int(1)
          [2]=>
          int(0)
          [3]=>
          int(0)
          [4]=>
          int(0)
          [5]=>
          int(0)
          [6]=>
          int(0)
          [7]=>
          int(0)
          [8]=>
          int(0)
          [9]=>
          int(0)
        }
    }
}

I had to configure #tree for the parents (2 here), and not only for the children

['parent']['#tree'] = true
['parent'][1]['#tree'] = true

I figured it out after trying and reading https://www.drupal.org/node/48643 (Archived, but it worked for me ;) )


How to notify users from within a module I'm building a custom module for a project and would like to display a notification/warning to the user once something happens. For instance, my module would trigger a Mailchimp action. Once I get the Ok from Mailchimp, I'd like to show a message to user, something like using Devel's dvm or dpm function.

How can I accomplish this (preferably without additional modules)?

Thanks in advance.

PS: I could use Devel, but I'd rather disable it in production env.

drupal_set_message() is what you're looking for.

Sample usage:

drupal_set_message('Mailchimp action is successfully executed.');


I can't enable SimpleTest due to open_basedir restriction being in force I can't enable SimpleTest due to an open_basedir restriction being in force for my Drupal7 installaton which resides on a Linux server running PHP 5.2.12. I found the directive under my PHP.INI file but it is already commented out there.

When I try to enable SimpleTest in my Modules config, I see the following error:

"The testing framework requires the PHP open_basedir restriction to be disabled. Check your webserver configuration or contact your web host. (Currently using PHP open_basedir restriction Enabled)"

What can I do to overcome this? A search on the web so far has not been overly helpful.

Sorry that i don't comment... have not enough points

Be shure u have the right php.ini, on some systems reside more then one.

Check with a phpinfo() file, after config change reload and look at the phpinfo() page if it is really disabled.


Save the #default_value of custom fields when editing comments I added a field select list comments in a hook_form_alter. When you select and save the comment, I do not know how to preserve the value of this field when editing this comment.
My Code

function comment_author_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'comment_node_zayavka_form') {
    $query = db_select('node', 'n')
      ->fields('n', array('type', 'uid', 'title', 'nid'))
      ->condition('n.type', 'brigada_type', '=');
    $result = $query->execute();
    $brigade_list = array();
    foreach ($result as $value) {
      if ($user->uid != 1) {
        if ($value->uid == $user->uid) {
          $brigade_list[$value->nid] = $value->title;
        }
      }
      else {
        $brigade_list[$value->nid] = $value->title;
      }
    }
    $form['select_brigade'] = array(
      '#type' => 'select',
      '#title' => t('Select brigade'),
      '#options' => $brigade_list,
      '#description' => t('Please select the team that was sent to you with reference to this application.'),
      '#required' => TRUE,
      '#default_value' => variable_get('comment_field_brigade_selection', 0),
    );
  }
}

I finally solved my problem, has created a field using field_create_field and attached it to the essence of my comment present the type of material
My code for the solutions in the Custom Module:

/**
 * Реализация hook_enable().
 */
function comment_author_enable() {
    foreach (_comment_author_select_field_create() as $field) {
        field_create_field($field);
    }
    foreach (_comment_author_select_field_instances() as $instance) {
        $instance['entity_type'] = 'comment';
        $instance['bundle'] = 'comment_node_zayavka';
        field_create_instance($instance);
    }
}
function _comment_author_select_field_create(){
  $fields['brigade_select'] = array(
    'field_name' => 'brigade_select',
    'label' => t('Select an option from the list'),
    'type' => 'list_text',
    'cardinality' => '1', // change this to -1 to enable ctrl+select
    'foreign keys' => array(),
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'module' => 'list',
    'settings' => array(
      'allowed_values_function' => '_comment_author_options_list',
    ),
  );

  return $fields;
}
function _comment_author_select_field_instances()  {
    $instances['brigade_select'] = array(
    'field_name' => 'brigade_select',
    'label' => t('Select brigade'),
    'description' => t('Please select the team that was sent to you with reference to this application.'),
    'default_value' => NULL,    // add a default value here that matches your key => index values
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'list',
        'settings' => array(),
        'type' => 'list_default',
        'weight' => -1,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => -1,
      ),
    ),
    'required' => 1,
    'settings' => array(
      'user_register_form' => FALSE,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => '-1',
    ),
  );
  return $instances;
}
function _comment_author_options_list(){
global $user;
$query = db_select('node', 'n')
    ->fields('n', array('type', 'uid', 'title', 'nid'))
    ->condition('n.type', 'brigada_type', '=');
 $result = $query->execute();
 $brigade_list = array();
    foreach($result as $value){
        if($user->uid != 1){
            if($value->uid == $user->uid){
             $brigade_list[$value->nid] = $value->title;
            }
        }else{
        $brigade_list[$value->nid] = $value->title;
        }
    }
    return $brigade_list;
}


drupal_add_js() 'setting' not being set on form submit I have a form and on that form the #submit action it calls a function that saves some data.   Now what I need to do is  I need to pass some data back to the website confirm page to be used by JavaScript. To do this I used drupal_add_js() 'settings' but this does seem to work? The data never gets set.
From what I've read I think it might be something with the form redirecting during the submission process and the JS is getting lost?

it might be something with the form redirecting during the submission process and the JS is getting lost?

Yes, you are absolutely right! Normaly, after form submitting user is redirected with drupal_goto() function. Messages which set with drupal_set_message() are stored in $_SESSION so they are not lost, but drupal_add_js() doesn't use session.
You can prevent redirect in your submit function:

// In this case your form hanler will be able to see flag $form_state['submitted'] and
// other data from previous form processing to indicate that form was submitted.
$form_state['rebuild'] = TRUE;
// Will work.
drupal_add_js(array('myModule' => array('test' => 'test-value')), 'setting');

Or with:

$form_state['redirect'] = FALSE;
// Will work, too
drupal_add_js(array('myModule' => array('test' => 'test-value')), 'setting');

But I would have used $_SESSION as it is more flexible.

$_SESSION['js_settings'] = array('myModule' => array('test' => 'test-value'), 'setting');

Then you have to process $_SESSION yourself in accordance with your site logic.


Setting field values according to user input in a custom form? i am using FAPI to create nodes through a custom form. the code below creates the nodes and assign them with a title and a body, so if i wanted static field values everything was perfect. my problem is, i want the value of $body_text to be determined by the user's input in the "order" textfield. i tried doing something like -

$body_text = $form['name'];

but that didn't work.

this is the code i'm using -

<?php
function nodeform_menu() {
  $items = array();
  $items['nodeform/form'] = array(
    'title' => t('My form'),
    'page callback' => 'nodeform_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function nodeform_form() {
  return drupal_get_form('nodeform_my_form');

}

function nodeform_my_form($form, &$form_state) {

  $form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => '
Initial markup for box
',
  );

    $form['order'] = array(
    '#type' => 'textfield',
    '#title' => t('My order'),
    '#default_value' => 'Products',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'ajax_example_submit_driven_callback',
      'wrapper' => 'box',
      'name' => 'submit1',
    ),
    '#value' => t('Submit'),
  );

$body_text = $form['order'];
$node = new StdClass();
$node->type = 'page';
$node->status = 1;
$node->title = "name";
  $node->language = LANGUAGE_NONE;
  $node->body[$node->language][0]['value']   = $body_text;
  $node->language = LANGUAGE_NONE;

node_save($node);
  return $form;
}

can anyone help me understand how to do this? i tried googling and reading the FAPI guide's but couldn't figure it out... plus, this is the first time i am using FAPI so in-spite the code is working, if anyone have any insights on this code (such as coding it more properly) i would also very appreciate that.

You should put node creating into form submit function. In your case it should be nodeform_my_form_submit. You can read more about it here under "Submitting Forms". Btw, you can use
drupal_get_form as page callback function and with that skip using separate function.


Make collapsible table rows I'm looking to make a Drupal 7 table with collapsible rows. I'm really looking to do what was asked in https://stackoverflow.com/questions/801082/how-to-implement-collapsible-table-rows-in-javascript

I'm just trying to bend Drupal 7 into shape to do it. Do far, I have created a table which has the extra "section" rows, and I've assigned an HTML class and id to the rows that are to be collapsed. My problem is the Javascript and CSS required to do this.

My rows are created something like this:

foreach($results as $row) {
  ...
  if($row_needs_section_header) {
    $section_number++;
    $rows[] = array(
      'data' => array("Section $section_number"),
      'class' => (array('class' => 'collapsitablesection')),
      'id' => "collasitableheader$section_number",
    );
  }
  $rows[] = array(
    'data' => array(
       $column_1,
       $column_2,
       ...
    ),
    'id' => "collapsitable$section_number",
    'class' => array('class' => 'collasitable')),
  );
}

This seems to generate suitable HTML, with each of the rows that are to be collapsed being in an "id" with the section number in it, and also having a class of "collapsitable".

I'm now trying to replicate "misc/collapse.js", but instead of working with fieldsets, make it work with my special table rows. I'm at something of a loss with this. Has anyone got any ideas about where to go next?

You can use the nextUntil() jQuery function like this:

(function ($) {
  Drupal.behaviors.collapsibleTable = {
    $('tr.collapsitablesection').toggle(
      function() {
        $(this).nextUntil('tr.collapsitablesection').hide();
      },
      function() {
        $(this).nextUntil('tr.collapsitablesection').show();
      }
    ).click();
  };
})(jQuery);

Put this in the script.js of your theme if it has one, if not add a new one, see the documentation: Using the theme's .info file (Drupal 6 & 7).


Inline entity form ajax I am trying to update some field options in an inline entity form with ajax. This should happen, when someone selects a value in an other field.

I already have some code which "works", but the problem is that you can edit multiple items and there seems to be a problem with the wrapper_id, because it is for all items the same and the entityForm function is called multiple times.

So what is the best way to do this?

What about adding wrappers to the fields?

In your hook_form_alter:

$form['field_name']['#prefix'] = '
';
$form['field_name']['#suffix'] = '

';

Check https://www.webomelette.com/drupal-form-api-prefix-suffix


How can I use LottieFiles to render animations? I created an Lotti animation and rendered it as a .json file. Is it possible to use this file in Drupal? Almost every other site builder from Squarespace to Webflow allows this file type of animation. Anyone have experience using it?

Sure it is. See the LottiFiles sample. First, you need to add the  Lotti player library yourself first.

https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js

Learn about adding Adding stylesheets (CSS) and JavaScript (JS) to a Drupal theme in the docs.

And second, find a way to place the Lotti markup on the page somewhere.

<lottie-player
    src="https://assets4.lottiefiles.com/packages/lf20_32NcN8.json"
    background="transparent"
    speed="1"
    style="width: 300px; height: 300px;"
    loop controls autoplay>
</lottie-player>

I'd probably have a field for that where you only paste the animation file URL or upload the animation file which then gets wrapped by the corresponding markup via a custom field formatter.

<lottie-player
    src="{{ field_lotti.entity.url }}"
    background="transparent"
    speed="1"
    style="width: 300px; height: 300px;"
    loop controls autoplay>
</lottie-player>


How to make a rule select all users of a role? I have a certain content type in which I have a user entity reference select list that is invisible to users/editors.

The idea is that the creator of the request has to choose a role of employees to who he sends this node, and then the other users can either accept or reject it, and only if ALL employees reject, the node would actually go to a rejected state, unlike the usual way of working with workbench.

To do this, I have the invisible user-entity reference field. Now I want to achieve the following:

When creating the node, after save, I want the reference field to automatically select all the users of the chosen role
By clicking a button 'reject', I want to remove the current user from the selected list.
When no users are selected, the node gets rejected.

Option 2 & 3 are easily done with rules. However, phase 1 is where I'm struggling. So I have the complete list of users, but now I have to "select" them, which I can do with rules by using "add to list". However, the selector only gives me the options "entities" and "site", in which site only includes "current-user", "current-page" and "feed-node".

How can I make it select all users of a certain roles?

It appears to me that there is a straight forward solution to have your rule process all those users of a certain role (as in your question): you could an approach to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of users that you want to be processed (= those users of a certain role).
add a loop to perform a Rules Action, probably similar to the rule you already have in place, for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Add role to user after joining organic group with rules I'm trying to add a user role to a user who has become a member of a group. The workflow is like this:

User requests to join group.
Request is approved by group administrator.
User is a member of the group.
User gets an additional role.

I've tried to make a rule which would be able to do this, but although all the settings seem correct after joining the group the user doesn't get the additional role. See below a screenshot of my rule settings:

Now your Rule runs after user requests membership. But you should run it after OG membership was approved.
I prepared Rule which adds role “member” after membership was approved or if it was added by admin (auto-approved). Here is export (4 is id of my drupal role “member”):

{ "rules_after_add_user_to_group" : {
    "LABEL" : "After add user to group",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "test" ],
    "REQUIRES" : [ "rules", "og" ],
    "ON" : [ "og_user_insert", "og_user_approved" ],
    "IF" : [ { "data_is" : { "data" : [ "og-membership:state" ], "value" : "1" } } ],
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ]
  }
}

Screenshot:

Tip: you can enable Rules debug (page admin/config/workflow/rules/settings) to see when your rules are executed.


How to remove Storage API without data loss I'm working on application based on Drupal 7.39 that use the Storage Api module version 7.x-1.8 with FTP container.

I'm trying to achieve is to remove this module and use the normal flow to save assets (I think that all assets will be saved in app/sites/default/files).

I downloaded all files from FTP container in app/sites/default/files folder.

I tried to disable the module, but I noticed that images fields served by the plugin are not available anymore. The association in content pages are still present but I only see a broken link.

How can I update all the fields served by the plugin to use files that are in app/sites/default/files? In other words I want to remove the plugin and all his associations to files. Is that possible? Can I migrate these associations?

Thank you.

UPDATE

As Jonathan Rhodes suggests me, here's the procedure to update uris.

$queryString = "SELECT * FROM db.file_managed WHERE uri REGEXP '^storage-a*'";

try {
    $db = new PDO("mysql:host=localhost;dbname=db;charset=utf8", "root", "root");
    $query = $db->prepare($queryString);
    $query->execute();

    $rows = $query->fetchAll(PDO::FETCH_ASSOC);

    $func = function ($element) use ($db) {
        $uri = $element['uri'];
        $uriReplaced = preg_replace('/^(storage-.*)(:\/\/.*)/', "public$2", $uri);
        $queryUpdate = "UPDATE db.file_managed SET uri = :uri WHERE fid = :fid";
        $query = $db->prepare($queryUpdate);
        $query->execute(['uri' => $uriReplaced, 'fid' => (int) $element['fid']]);
    };

    echo count($rows);
    array_map($func, $rows);
} catch (PDOException  $e) {
    echo "Error: " . $e;
}

echo 'ok';

You'll probably need to manually update the files_managed database table and change the uri to use the public:// schema.


A page with custom parameters I have a page to do this:

Boats/
Boats/Veterans
Boats/Nine
Boats/Used

Where ['Veterans', 'Nine', 'Used'] would be the parameters passed into the URL!
I would like to use my page customize

  page--boats.tpl.php

This is a page theme. Currently, I have a white page.

How can I do?

I think you are asking about hook_menu().

what you need is to create an item which has a base of boats, and takes an argument.

function mymodule_menu() {
  $items = array();
  $items['boats/%'] = array(
    'page callback' => 'mymodule_boats',
    'page arguments' => array(1),
  );
  return $items;
}


Flag not updating on user profile? I'm using panels to display user profiles and each profile has a 'follow' flag (non global).
I've used a view called 'follow-users' to capture few users and one of the field within that
View is the same 'follow' flag link.

When someone flags a user within 'follow user' view the flag on user profile still stays unflagged

Can anyone please help to figure out why it’s happening?

Thanks

I would take a look at the flag set up in each of your displays, and make sure you are using the same Flag - it's an easy oversight if you have multiple types of Flags and can cause this sort of behaviour.


hiding taxonomy terms on term page I'm struggling theming the taxonomy-term page and since i'm not really getting anywhere, i now embedded two blocks (created with views) in my taxonomy-term.tpl.php. Now, that views is showing everything the way I want it, I don't want the term page itself output its data.
That's why I'm trying codes like

<?php hide($content); ?>

But that won't do the trick. How can I just show the Blocks from Views instead of the content taxonomy provides itself?

Thanks!

Use Display Suite to manage your display and show/hide fields for Taxonomy terms. You can actually display nothing. Then add the blocks in there.

Second option is alter taxonomy term page.tpl.php - a function that you need to add in template.php within your theme directory.

This is a function for templating pages for content types or terms. Second part defines page--taxonomy--term.tpl.php suggestion. It worked for me.

<?php
/**
* Add / modify variables before the page renders.
*/
function YOURTHEMENAME_preprocess_page(&$vars) {
// custom content type page template
  // Renders a new page template to the list of templates used if it exists
  if (isset($vars['node']->type)) {
// This code looks for any page--custom_content_type.tpl.php page
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
    if(arg(0) == 'taxonomy' && arg(1) == 'term') {
        $tid = (int)arg(2);
        $term = taxonomy_term_load($tid);
        if(is_object($term)) {
           $vars['theme_hook_suggestions'][] = 'page__taxonomy__'.$term->vocabulary_machine_name;
        }
  }
}
?>

I hope it helps. A while ago, I've been looking for this solution for days!


Firefox is caching ajax form values from previous submit after if I press the browser back button I've implemented a custom multistep AJAX form like:

STEP #1
Question 1: A or B (radiobutton Ajaxified) -> AjaxCallback: step + 1

STEP #2
Question 2: C or D (radiobutton Ajaxified) -> AjaxCallback: step + 1;

STEP #3
Question 2: E or F (radiobutton Ajaxified) -> redirect to other page (ajax command)

Everything works as expected but after being redirected to the new page if I click the browser back button in firefox the form shows the first step with the option [A] selected of the first step. This does not happen in Chrome.

I'm running Firefox 54.0.1

Does it make sense to anyone? How could I fix it?

Thanks in advance!

It seems chrome makes a refresh of the page and firefox a cache. Seeing this question the reasons are answered here

You can try disabling caches using http headers: https://stackoverflow.com/questions/13640109/how-to-prevent-browser-cache-for-php-site


How to add multiple js files in hook_field_widget_form()? When I load two JS files using drupal_add_js() as can be seen in the code marked "After", it does not show alert() text on page load and also when I click on the button created in the form to load fancybox (popup) it shows

$.fancybox is not a function

When I just add taxonomy_fancybox.js it shows alert, so my question is
How can I make sure both fancybox.js and taxonomy_fancybox.js are loaded.

Before

/**
 * Implements hook_field_widget_form().
 */
function taxonomy_fancybox_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  drupal_add_js(drupal_get_path("module", "taxonomy_fancybox") . '/taxonomy_fancybox.js');
}

After

/**
 * Implements hook_field_widget_form().
 */
function taxonomy_fancybox_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  drupal_add_js(drupal_get_path('module', 'fancybox') . '/fancybox.js');
  drupal_add_js(drupal_get_path("module", "taxonomy_fancybox") . '/taxonomy_fancybox.js');
}

taxonomy_fancybox.js has

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

      alert('enters');

      $('#edit-select-terms').click(function (e) {

        e.preventDefault();

        $.ajax({
          url: '/ajax/fetch-vocabularies/',
          success: function (data) {
            $.fancybox(data);
          }
        });

      });

    }
  };
}(jQuery));

Seems you missed step 3. from the README.

  Download the fancyBox plugin and extract the entire directory into    sites/all/libraries. (You may need to create this directory). The path
  to    fancyBox should be
  sites/all/libraries/fancybox/source/jquery.fancybox.js.    (the module
  uses the minified version, so actually jquery.fancybox.pack.js).

The second JS then doesn't fire anymore as the first JS virtually raised an exception already (due to the non-existent 3rd party library).


How to alert views output using custom module I am using hook_views_pre_render() in order to calculate some values based on my $view->result and I can see how I can manipulate the arrays and I'm achieving some success with being able to drupal_set_message() my variables to the screen. However, I'm trying to actually alter the HTML output in the view - is this possible through the custom module?

I currently have a multi value field and in my Views table, I have a field for students which lists my students (nodes) in an unordered list - I'd actually like to only show the first student name and add "+ 8 more" (if there are 9 students altogether). While I can sort of drupal_set_message my variables - I'm unsure how you'd actually send this information to the view itself? Do you have to store the variables in the custom module and then send them to tpl.php files in Views?

I know this is possible using a pre made module but I'd rather know how it works myself.  I'm just struggling to see how you output these things into the view itself using a custom module.

Here is an image:

Cheers,
Garry.

hook_views_pre_render() gets the $view object passed by reference. This means that if you change the $view object inside your hook_views_pre_render() function, it doesn't need to be returned or saved or re-executed or anything. The view object itself, the same one that is rendered, is the one you're altering.


Does having too many cck fields negatively affect site speed and performance? I building a site that could potentially utilize 50 different content types. The most of the content types have more than 40 CCK fields, including multiple field_collections entity_reference.

How can i take care about performance of site Specially for CCK fields level ?

Yes. The more fields you have, the more load you should expect on your database server; that's a given.

What it means in real terms depends on your hardware, configuration and usage - you'll need to benchmark your site in that actual environment to come to any meaningful conclusion. If you get one request a day, for example, your pages are cached, and you have a brand new shiny server, then you probably won't need to think about changing anything.

If you get thousands of requests per second, all your pages are non-cacheable, and your server isn't great, then you might have to think about re-structuring that data so it's more performant (e.g. creating custom field types to combine data from multiple other field types into a single table).

In short, there's no general answer to what you're asking. You need to see what problems your application develops under load, if any, and deal with them then. Premature optimisation is rarely a good idea.

All of that said, Drupal's main defence against this kind of thing is caching. There's a great post here: How do you improve Drupal performance?


How to disable billing address in Drupal Commerce while using Paypal WPS I'm setting up a very simple online shop for a charity. They'll use Paypal WPS and don't want to collect customer's billing address as those will be entered in Paypal anyway. Is there a way to remove the billing address from Drupal Commerce.

I'm only using PayPal, so the aforementioned answer doesn't apply.

If you do not need Billing Address section at all, it should be as simple as dragging Billing Information under disabled from any of checkout/review step.
Go to page 'admin/commerce/config/checkout' in order to disable Billing Section.

If you want Billing Address section to vanish conditionally based on payment method opted(in case you have multiple way of payment) then it is already answered here by Ryan himself.


External link in views slideshow I have a views slideshow where an image is linking to the node. Now I want one of the slides to link to an external site.
How do I get this to work?
Maybe I can rewrite the output for the image field in a tpl.php file, but I don't know how to do it.
Any suggestions is appreciated. Thanks

If you are in Drupal 7, all you need is using Link and Linked field modules


Whats causing Drupal to freeze when creating/editing a mini-panel? I'm quite new to drupal.

Drupal has been freezing for me when I try and create or sometimes edit a minipanel. Once I select the panel layout and start adding content it just remains in the lightbox 'grayed' state and wont let me click or do anything. It's almost like it's trying to load but I've left it for an hour and it's completely frozen.

I've tried on Firefox and IE10 and get same issue. Also upgraded my drupal from 7.23 to 7.24 today so a completely new core is running but still hangs like this.

I haven't fully explored everything yet in drupal so I don't know if other sections will do this. So far it's just the minipanels section.

Does anyone have any suggestions? Thanks.

By the description of your problem, it seems to being caused by a Javascript error.

Try to check with Chrome DevTools, Firebug or the debug tool of your preference on the browser, go to "Console" tab and look for Javascripts errors or maybe on the "Network" panel to check for XHR (ajax) problems.


Programmatic list of Webform elements? I am building a D8 module that, for configuration, needs a list of webforms and their fields (just the entity reference fields, but I am not picky)

I can get the webforms with this:

  $webforms = \Drupal::entityTypeManager()->getStorage('webform')->loadMultiple(null);

But once I get the returned elements (Drupal\webform\Entity\Webform::__set_state), how can I fetch the elements in the webform referenced?

By trawling through the code, I found this handy function in the Entity code, and it works perfectly:

 $elements = $webform->getElementsDecodedAndFlattened();

This gives a nice array of the elements in the webform itself.

If you want the results of a submission, grab that entity and use:

$data = $entity->getData();

I hope this helps


Create custom block module with sorting of block content I am using Drupal 7.
I want to create a module which shows All the latest posts in Group with sorting options for the posts(a dropdown for sorting posts in block with various options).
I am using organic group module for group management.

I have created a block module which can fetch the content for the particular group, but I am not able to manage sorting drop down form.

Does any one have idea, how to display form in block output and then sort that form.

I am also using file attachment with posts in group. So my sorting parameters includes no of files in post, postdate(i can get using views), Most viewed, Most comment,

Note: I want to build custom module because first I tried with Views module, but I am not able to get various sorting parameters which i need for sorting

You can do it with views + some minimal coding in your module: Make the view as you need, use a custom block to put 4 link with 4 different query arg: mysite.com/node/1?no_files=1, mysite.com/node/1?post_date=1 etc.
For the dropdown you can use ctools jump menu feature, it's a simple drupal_get_form with this parameters.

If the dropdown is ok, let's modify the view's result based on query_arg: See hook_views_query_alter.

To get how do you need to change the query, I'm used to create the same view with all different filter what I need, and put file_put_contents('/tmp/log', var_export($query)); into your _view_query_alter implementation. If all different query of views are in log, it's easy to figure out, what do you need to modify in $query.

To order your views by file attachment exists, just add a filter named Field: Your
File Attachment to the view, and use the operator Is Not Empty (NOT NULL). (As I understand, in this one case, you want to filter the query, not to sort.)

Most comment sorting need the sort criteria: Content: Comment count, Most viewed is not so exact, it depends, what do you use to tracking content viewing.


Creating a sortable field I have a custom field declared and I am trying to make it sortable. The field holds date values already formatted ie: 06/10/12. How could I make this sortable? I thought this code would work but the header on the table doesn't become hyper linked even.

     function uc_order_views_data() {
      $data['uc_orders']['data'] = array(
        'group' => t('Order') . ':data',
        'title' => t('Ship Date'),
        'help' => t('The date to ship the order.'),
        'field' => array(
        'handler' =>'uc_order_handler_field_ship_date',
          'click sortable' => TRUE,
         ),
         'sort' => array(
           'handler' => 'views_handler_sort',
         ),
         'filter' => array(
           'handler' => 'views_handler_filter_string',
         ),
      );
     }

I do have the ability to send through a UNIX epoch timestamp instead if that would help me make this sortable so long as I can sort by the epoch but render it as a formatted date.
The fact that this is an extension of ubercart bears no factor on the result. Treat this question as if it were just a simple implementation of the views module, which in essence it is.

I finally figured out the answer. Only took me a week.

Under the view settings there is a "Format" option, and beneath that there is a "Settings" link. Upon clicking there are options to make your new fields sort-able or not to the user. Adding 'click sortable' => TRUE just exposes that radio button!

Good grief that was causing me some headaches! I was beating myself up on the code when it was a UI setting withing Drupal.

Something else to consider is the actual sorting. There are many different handlers for sorting fields. This particular field is a date. In order for this to work, the date needs to be stored as a UNIX time epoch. There are flags that I did not pass that can allow you to choose the granularity of the sort, (seconds, minutes, days, months, years).

This is what my code ended up looking like to make the date sort actually work as expected. When I stored the date as a UNIX time epoch.

/**
 * Implements hook_views_data().
 */
function uc_order_views_data() {
  $data['uc_orders']['data'] = array(
    'group' => t('Order:data'),
    'title' => t('Ship Date'),
    'help' => t('The date to ship the order.'),
    'field' => array(
      'handler' =>'uc_order_handler_field_ship_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort_date',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_date',
     ),
  );
}

Now, lets take a look at the uc_order_handler_field_ship_date handler. You want to be sure that if you are not using the standard sort handler, that you extend the proper handler. If this date was not buried within some serialized data, I wouldn't even need this class and the default views handler would be sufficient.

class uc_order_handler_field_ship_date extends views_handler_field_date {
  /**
   * Overrides views_handler_field_date::render().
   */
  function render($values) {
    $data = unserialize($values->uc_orders_data);
    if (isset($data['fedex_calendar_ship_date'])) {
      $date = $data['fedex_calendar_ship_date'];
    }
    else {
      $date = "-";
    }
    return date('n/j/Y',$date);
  }
}

For more information on all of the sort handlers available see:
http://api.drupal.org/api/views/handlers%21views_handler_sort.inc/class/views_handler_sort/7


Can any function be used as a hook? I'm looking to override format_size(), but I'm not sure if this is possible in a module.
If I implement myModule_format_size() or in a theme myTheme_format_size() will the hook be called?

No.
Not all functions invokes a hook in other modules. As we can see in http://api.drupal.org/api/drupal/includes%21common.inc/function/format_size/7 there is no module_invoke_all is called.

Here is how we define module_invoke_all

  Invokes a hook in all enabled modules that implement it.

function module_invoke_all($hook) {
  $args = func_get_args();
  // Remove $hook from the arguments.
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

  return $return;
}


Views Send with multiple email fields I've just got Views Send to work. I have a custom node type, with two email fields. One field contains a~single email address, the second field can contain more email addresses. Using Views Send, I can send mail to either field (even when one field can contain more email addresses).

The question is, can I use Views Send to send an email to both fields at the same time? Now I can only select one field containing emails. Sometimes it is necessary to send the same mail to both fields.

Yves

I had a look at this interesting module and I am afraid I didn't see a way to do this. I tried Views rewriting, to collect all email addresses from first and second email field into a third one. Standard Views presented the new dynamic field fine... But, this is not supported by the Views Send module. It seems like it would need the data available in the database, and not dynamically generated.

If you want to have that working in an easy way, you could try adding a Computed Field to your content-type. This computed field would then store all the emails from your first and second field. And this concatenated string would be available to Views Send.

Would that be a way out for you? If so, here is an 'draft' version for the code to put in the "Computed Code (PHP)" textarea:

$field_main = field_get_items($entity_type, $entity, "field_main");
$field_additionals = field_get_items($entity_type, $entity, "field_additional");

if(isset($field_main[0])) {
  $emails[] = trim($field_main[0]["value"]);
}

foreach($field_additionals as $field_additional) {
  if(trim($field_additional['value']) !== '') {
    $emails[] = trim($field_additional['value']);
  }
}

$entity_field[0]["value"] = implode(', ', $emails);

Voila! Your computed field is readily available in your Views and Views Send containing all the emails from both fields.


Drupal not sending emails from contact form For some reason my Drupal website does not sends email from contact form. Can you help me where could be a problem?

It also does not send emails to administrator for newly added comments.

Just to mention, that only email it sends is when registered user requests for new password.

Thank you in advance!

There could be many reasons but here are a few things to check.

Check your logs. Watchdog may tell you the source of the error. For D7, it's at /admin/reports/dblog
Test other mail functions like the reset password link.
Make sure you have a valid email address set: The site email address (used when sending notification emails, and the default for most all modules that send emails) can be set via the Site Configuration > Site information page (admin/settings/site-information).
Check your permissions if you are sending email from a module like webforms.
If you have SSH access to your server, test the mail settings from there.

<?php
    $to = "your@email.com"; // REPLACE
    $subject = "Test mail";
    $message = "Hello! This is a simple email message.";
    $from = "noreply@eample.com";
    $headers = "From:" . $from;
    mail($to,$subject,$message,$headers);
    echo "Mail Sent.";
Make sure to replace the "to" address, save it as mail.php, and run it using "php mail.php". If you get email from that, then the problem is specific to Drupal, and if not, then your server isn't sending email at all and you should contact your host.

See more at: http://drupalconnect.com/blog/how-debug-drupal-not-sending-email#sthash.Jkxx7ui6.dpuf


D7 : Views exposed form with three taxonomy term fields as filters (checkboxes) Any help would be very much appreciated please.

I have a content type named restaurant and I have three taxonomy term fields (cuisines, neighborhoods and occasions) in it. I've created a view to expose these 3 fields as checkboxes for users to search restaurants accordingly.

Cuisines and Neighborhoods are required fields in the node, but not occasions. The problem is that if there is a restaurant that has not been tagged with an occasion, that restaurant will not show in the search results because in my filter criteria, I've selected "is one of" > all the terms in occasions.

I need help to turn this occasion filter as an optional one, where a node that has not been tagged with an occasion will appear when the user select a cuisine or neighborhood where this node is listed in.

I believe that this can be done via hook_views_query_alter but I don't know how.

In your view I would not select any of the occasion field items and allow all the items with or without this field to populate. If the user wants to drill down into restaurants with this information you can have them use the select menu or whatever mechanism to choose the specific occasion. I think that starting off with no filter on the occasion field might be the way to go.


How do I migrate a custom field from WordPress? I'm working on migrating a fairly large blog type site from WordPress into Druapl 7. The WordPress Migrate module has imported the basic blog content very well (title, body, tags, etc), however there were custom fields set up in WP that do not import.

Looking at the xml file, there's really just one extra piece of info I need. A line for a video file (which is a code for a youtube video).

Here's how the code for this looks in the XML file:

    <wp:postmeta>
        <wp:meta_key>Video_File</wp:meta_key>
        <wp:meta_value><![CDATA[8ENbMuVQCYE]]></wp:meta_value>
    </wp:postmeta>

I have decent PHP experience, but the only customizing I've done in Drupal are relating to themes. Can I write a little addition to the WordPress Migrate module to insert this extra piece of info? Since the module migrates everything else nicely can I create a new little module that would go through the same xml file, find the matching node (by post date/time, title, some distinguishing piece of info from the xml file) and then add in the video info (assuming I would first create another row in the DB table)?

I'm at a bit of a loss, and since I need to bring in close to 1000 posts (most of which have the video code), I really need to fine a solution that doesn't involve me editing every single node by hand to add in the dang code.

I should also mention I currently don't have a CCK field in Drupal for the video code... that just dawned on me, so I'm off to create one and then re-migrate a portion of the blog (I downloaded it in multiple xml files for testing).

Update: Created that CCK field, re-imported the blog, and sadly it didn't work :) Not that I thought it would to begin with (nothing is ever that easy).

Update: I've been attempting to modify the WordPress Import module with little success thus far. This meta field is just some text, so I'm hoping to figure out where to add in the info I need to have it process correctly. I'm sure I need to tell it which cck field to insert the new data, just have to find it!

Another Update:
Working on adding a WP plugin to export all the content as a CSV, then going to use the Feeds module to attempt to import everything.

My backup is going to be to use the wordpress_migration module to import the basic stuff (title, body, tags, etc), then write a custom php page to add the video links... I'm basically thinking to find the title in the node table, grab the nid, then create the entry in the video_field in the db table. At least that's how it's currently laid out in my head, whether or not that works in real life remains to be seen.

Course hopefully Feeds works just fine and I won't have to try the backup!

Neat. It looks like wordpress is storing a small fragment of the youtube url in the DB. I'm not sure how the the cck video field stores content -- probably in its own field, and it probably has to be set for "Youtube" before you attempt a migration.

Once you figure out where the youtube ID will be stored in a drupal field. See the documentation on how to extend worpress migrate:

  Extend the appropriate class, such as the WordPressBlogEntry class with your custom behavior - add field mappings in __construct(),
  manipulate the body ($row->content) in prepareRow(), etc.
  Extend the WordPressBlog class, and override migrationClasses to point to your custom classes:

<?php class MyCustomBlog extends WordPressBlog {
public function migrationClasses() {
    $classes = parent::migrationClasses();
    $classes['WordPressBlogEntry'] = 'MyCustomBlogEntry';
    $classes['WordPressPage'] = 'MyCustomPage';
    return $classes;
} }

In your custom migration class you would then define the migration of a field using a Mapping as something like:

 // dest (a field in the node) <- source
 $this->addFieldMapping('youtube_url', 'source_yt_value');

In your custom migration class you will of course have access to the typical helper methods used in migrations to "prep" the data (retrieve the youtube url from that CDATA crud), and translate it into a valid video blurb for drupal.


Drupal 7 custom module for menu I am developing a custom module that will have the functionality to show a particular menu link active on the desired path. For this I have implemented hook_form_FROM_ID_alter() hook for menu_edit_item(). In the edit form of each menu item there I have provided options similar to block modules page visibility options

Active on all pages except listed
Active only on listed pages
Active depending upon given php code

But I need to match the path listed with any existing path. Do I need to implement other hook or create more functions to implement this or this functionality should be implemented in hook_form_FROM_ID_alter(). I have also created a database table for this that stores

menu link ID
Visibility (i.e. flag to the option chosen by the user 0, 1, 2)
Pages (i.e the paths given by the user in the textarea eg: node/4,
etc)

Thanks for your help in advance

This is an existing module which does part of what you want to do. The module is Menu item visibility. I recommend looking at how it works and extending it (it says it's extendable) to add the extra pieces you are requesting: visible per page, or visible on PHP code. It probably has hooks you can use to complete your business logic.

In fact, this issue talks about adding "per page" or "php code" conditions essentially.


It is possible to set up a menu item with hook_menu that points to an existing path? The accepted answer here by marcvangend explains how to it with hook_menu_alter.  His method works, even if you skip step one (the block View).

But just out of interest: Can you do this by means of hook_menu?

So far, I've tried to put the following in hook_menu:

$items['node/%node/delete'] = array(
  'title' => 'Delete',
  'access callback' => TRUE,
  'type' => MENU_LOCAL_TASK,
);

However, that did not have any effect.

(Just to make clear, I just want the "Delete" tab, pointing to this existing path node/%node/delete.  I don't want to put a view on it.)

You can only use hook_menu() if you're defining new paths, ideally, paths that are provided by the module implementing the hook.

If you want the Delete link to show up as a tab, hook_menu_alter is definitely the way to go, and adjusting the context value is what does the magic - as per Step 2 from marcvangend's post. If you want to change the "access callback" as per your snippet, then you can do that in hook_menu_alter() too, although I'm not sure why you'd want to let anyone delete pages?


Should all files/folders in an installation be owned by the web server user? As in the title, should all files/folders in a Drupal 8 installation be owned by the web server user, e.g. the default www-data user for Apache?

As far as I know, the answer is yes at least in principle, so that all files/folders should have www-data as both owner and group, and more so because of logistics/minimalism/ease of management.

Is that correct or are there other considerations?

Securing file permissions and ownership is the canonical reference for this topic, and is still relevant for Drupal 8.

If we are going under the assumption where we are talking about who owns these files, then we can also assume you have root on the machine and configure the entire environment the way you need.

Having "www-data" (or equivalent) own the entire DOCROOT of any website is an unnecessary security attack surface.  If there is a security breach (either through code or the webserver), then an attacker can change code on the site.

If you have root, then you don't need to explicitly use the UI for uploading or updating modules.  This is the only real reason to have www-data own the site.

The linked article has all of the details, but I always recommend

A normal user owns everything in DOCROOT, except for sites/default/files (or wherever your files are for your sites), the private, and tmp directories (and if possible private and tmp outside of DOCROOT).
Apache runs with a proper umask so that group write is on for files
The data directories have 2775 permission on them, so group ownership is retained
Your normal users is also in the www-data group, so drush / drupal console work as expected

The script in the linked article handles most of this; I usually create custom ones for my sites that do the same thing.


Is it possible to add help text to addressfield module fields? I would like to add some help info to address field fields from Address Field Module (http://drupal.org/project/addressfield). Is that possible, or do I have to use Javascript?

When editing the field settings there should be a Help text field where you can enter "Instructions to present to the user below this field on the editing form".

If you want to provide additional instructions, use the Markup module to add a "field" containing the additional instructions. To keep the address field and the markup field in the same fieldset, use the Field group module to group the two fields into a single fieldset group.


A different template based on a taxonomy term in views I'm using drupal 8.

I use the view provided by default: "taxonomy term".

I would like to make a presentation of the page (and not only of the node) different according to the term of taxonomy.

I tried with this code (in .theme) and template suggestion :

use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

But it does not work because (i think) it is a view.

I tried with the views template suggestion but it works only for the whole page and not for each taxonomy term.

Does anyone have the solution ?

You can define each template by using template
page--taxonomy--term--xxx.html.twig
where xxx is your term id.

In your code, $term->getVocabularyId();
will return machine name of vocabulary, not the term id. It mean all term of this vocabulary will use this template.


programmatically saving a node doesn't add any record to dblog When I call node_save to save a node, no record for "a new node has been saved.." is added to watchdog.

Is this normal? If yes, how do I also add a watchdog record? (without calling the watchdog function directly)

The reason that the save operation is not logged during node_save is because it is done during the node form submission process by node_form_submit which internally uses node_save.

Please refer this elaborate and well-written response of saving the node using drupal_form_submit answered by user Francisco Luz. Pasting the code for the sake of completion here for saving an article resulting in both the watchdog logging and the drupal_set_message of the acknowledgement.

global $user;
module_load_include('inc', 'node', 'node.pages');

$node = (object) array(
  'uid' => $user->uid,
  'name' => $user->name,
  'type' => 'article',
  'language' => 'und',
);
node_object_prepare($node);

// Get default values from attached fields.
$fields = field_info_instances('node');
$form_state = array();
foreach($fields['article'] as $field_name => $values) {
  $form_state['values'][$field_name] = array('und' => array());
}

// Add the $form_state field values.
$form_state['values']['title'] = 'my title';
$form_state['values']['body']['und'][0] = array(
  'value' => 'my body',
  'format' => 'full_html',
);
//$form_state['values']['field_MYFIELD']['und'][0]['value'] = 'blah blah';

// Without this line, not quite sure why, it wont work.
$form_state['values']['op'] = t('Save');

drupal_form_submit('article_node_form', $form_state, $node);

// Tell watchdog if any of the fields fail validation.
$errors = form_get_errors();
if (!empty($errors)) {
  foreach ($errors as $field_name => $message) {
    watchdog('MYMODULE', '%field: %message',
      array('%message'=> $message, '%field' => $field_name));
  }
}

I did run this once with devel php console and it logged the node during the node creation. Hope this helps.


How do I include a custom class file in a module? In Drupal 7 module development, I could include a custom inc, api, or php class file using the file[]= directive in the module.info file or the drupal_load_included() function.

With D8 using PSR, what is the proper way to package up a "plain ole PHP object" and reference it in DefaultController.php? Think something like: $a = new POPO();.

Is just giving the PHP file containing the class a namespace sufficient? How does the controller (or module in general) know to reference or scan for that class?

You don't use file[] = ... anymore. Instead, classes are autoloaded. For example, I have a module with the following file structure:

views_hybrid/

views_hybrid.info.yml
views_hybrid.module
src/

Plugin/

Field/

FieldFormatter/

HybridFormatter.php

HybridFormatter.php defines a class called HybridFormatter.

In my .module file, if I start typing in my IDE (NetBeans in this case) HybridFormatter it autocompletes to \Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter:: because it is autoloaded. Since I don't want that whole path littering my module, at the top I have placed the line,

use Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter;

along with use directives for other classes I am including for use with my module.

The namespace is defined in HybridFormatter.php like so:

namespace Drupal\views_hybrid\Plugin\Field\FieldFormatter;

class HybridFormatter extends FormatterBase { ... }


The database is not bootstrapped in another docker container The following problem occurs when running certain Drush commands, such as drush en features which outputs:

  Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
  The drush command 'en features' could not be executed.
  Drush was not able to start (bootstrap) the Drupal database.
  Hint: This may occur when Drush is trying to:

  bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See drush topic docs-aliases for details.
  connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

  Drush was attempting to connect to:

  Drupal version: 7.58
  Site URI: http://default
  Database driver: mysql
  Database hostname: mysql
  Database port:
  Database username: default
  Database name: default
  PHP executable:  /usr/bin/php
  PHP configuration: /etc/php/7.2/cli/php.ini
  PHP OS: Linux
  Drush script: /var/www/vendor/drush/drush/drush.php
  Drush version: 8.1.17
  Drush temp directory: /tmp
  Drush configuration:
  Drush alias files:
  Drupal root: /var/www
  Drupal Settings File: sites/default/settings.php
  Site path:  sites/default

This problem has been reported previously, but in different contexts, not in the specific setup I am working with, which consists of separate docker containers on a linux hosting server.

Apache 2
ElasticSearch
Workspace
PHP
MySQL

All the docker containers are running, as well as the (development) website that is built with drupal, which does connect to the database. Drush had previously been used for setting things up, but something seems to have broken during the development process. Drush had been added to the project using composer, as suggested on Install a site-local Drush and Drush Launcher.

The error seems independent of the directory where the command is executed. Moreover, the settings.php file exists at the path mentioned in the output above and contains the correct database configuration.

Finally, drush sql-cli returns the following message.

  sh: 1: mysql: not found
  SQL client error occurred.

Do you have any idea on what the problem might be?

Ok, this is solved now, thanks to leymannx and hansfn. I had to also install mysql-client in the workspace container, where drush was being executed from, in addition to the mysql-server running in its own container; mysql-client must have previously been present in the workspace container for a different reason, but some containers were stopped and restarted at some point, so any container-specific installations must have disappeared.


Adding content to Drupal database I'm running a rather large Drupal 6 site and I need to include additional information in the database, things that run independently of Drupal. Is it best to create a separate database and connect to it from the files I need to access the info from, or is it just safe to add a custom table to the Drupal database and add whatever I want in there?

Thanks!

In theory, it's no problem to add tables to the database. It won't hurt Drupal. That said, I wouldn't recommend it. If things already are separated and there is no important reason to use a single db, just keep them separated for flexibility and performance in the future.


Custom classes for menu links How can I add custom classes for links into main menu in Drupal 8. This is template for my main menu called menu--main.html.twig

{% import _self as menus %}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

        {% for item in items %}

            {{ link(item.title, item.url) }}
            {% if item.below %}
                {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
            {% endif %}

        {% endfor %}
    {% else %}

        {% for item in items %}

            {{ link(item.title, item.url) }}
            {% if item.below %}
                {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
            {% endif %}

        {% endfor %}
    {% endif %}

  {% endif %}
{% endmacro %}

And I need to achieve this result:

Úvod

O škole

Aktuality

Pedagógovia

Dokumenty

História

Informácie o štúdiu

Fotogaléria

Kontakt

My problem is that I don't know how to set custom class for  tags. Is there any way how can do it using link() function. In Drupal 7 is l() function but attributes aren't similar. l() has also third attribute with possibility to add options. Is it true, that link($title, $url) accepts only 2 parameters? Because I can't find the way how to send options for link($title, $url). I don't insit on link() function, so if there is some better way please let me know. I'm open to new ideas :)

Thanks

Just incase someone stumbles upon this, Martin's solve above breaks URL fragments as it overrides the URL options completely. The better approach is here:

{{ link(item.title, item.url.setOption('attributes', {'class' : 'main-nav__link'})) }}


custom function to delete determined content type's nodes never finish I am trying to make a custom module which delete all nodes of a content type and then import new nodes of this type from a .txt (maybe I will use feeds import for this).

In the first step of my module, I had found this code to delete nodes:

function nodes_import_delete() {
  // Gather all the pivot content that might have been created while this
  // module was enabled.  Simple selects still use db_query().
  // http://api.drupal.org/api/function/db_query/7
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(':type' => 'apunte'));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }

  // Delete all the nodes at once
  // http://api.drupal.org/api/function/node_delete_multiple/7
  node_delete_multiple($nids);
}

My problem is this function never finish when is executed and I don't know why.

apunte is my content type which I want to delete all nodes.

May be the server execution is taking long time to delete nodes.Try to increase your server execution time or change the code to batch process or pass limited nids to the  delete function.


Using variable_get() still returning a form with the default value? So, I have a form with a default value 'You have not enabled TFA' that is editable for the user. This works, and user input is recorded in the database, but when the form is returned it shows the default value again, and I think it would be better to return the form with the inputted values.

Here is my admin.inc file:

function my_module_admin_settings_form($form, $form_state, $nid = 0){
  $form = array();
  $form['subject'] = array(
    '#title' => t('Subject Line'),
    '#descirption' => t('Default email subject line.'),
    '#type' => 'textfield',
    '#size' => '50',
    '#required' => TRUE,
    '#default_value' => variable_get('subject', 'You have not enabled TFA'),
  );

...

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

Here is the code for variable_get function (for reference):

function variable_get($name, $default = NULL) {
  global $conf;

  return isset($conf[$name]) ? $conf[$name] : $default;
}

Can anybody see what is going on?

If I understand your question correctly, your values are not saved.

This is because you either need to handle storing variables (using variable_set()) in your submit callback, or use system_settings_form() to do this for you.

The latter approach is generally used for administrative settings, unless you need some additional processing or storing part of the settings somewhere else.

Do note that with system_settings_form() you don't need to add the form actions - they will be added for you.

Here's an example:

function my_module_admin_settings_form($form, $form_state, $nid = 0){
  $form = array();
  $form['subject'] = array(
    '#title' => t('Subject Line'),
    '#descirption' => t('Default email subject line.'),
    '#type' => 'textfield',
    '#size' => '50',
    '#required' => TRUE,
    '#default_value' => variable_get('subject', 'You have not enabled TFA'),
  );

  // Add more fields.

  return system_settings_form($form);
}


Modify widget in Entity Reference field select box? I am using an Entity Reference field to refer to users in another content type. The default widgets for the field use the User Name as the label for the dropdown, but I'd like to change that to another field from the user profile entity (ideally combining 'first name' and 'last name' fields). I've looked at Entity Reference Views, but it isn't released and I could not get it to work based on available docs.

Entityrefence 7.x-1.x-dev allows you to use results from a View in the select box, which will allow you to do what you need.

create/edit a view, add a new display of type "Entity Reference" to it, setting properly the fields you want to be shown;
edit the entityreference field, find "entity selection mode", set it to "views: filter by an entity reference view" then select the proper "view used to select the entities" option created on previous step.


Building a Custom Search block I have to search the entered text in a drupal table and if there is a match for the keyword get all the fields corresponding to that keyword. I have executed the query and I have the fields to be printed in a array called $column_name.

How can I display these fields to the user in the form of a table?

function module_form_submit($form, &$form_state) {
$text = $form_state['values']['text_field'];
$query = db_select('table_name', 'n');
$query->fields('n', array('field_1','field_2','field_3'));
$query->condition('n.field_0', $text, '=');
$column_name = $query->execute();

I created two forms and called the second one only after the first form is submitted. To create a table i used table theme.

if (!empty($form_state['values']['text'])) {

 //db_query here to search the key word
 $text = $form_state['values']['text'];
$header=array(t('patient id'), t('patient name'));
$row = array(
    array(
t('one'),t('two')
    ),
);

 $form['table']=array(
 '#theme'=>'table',
 '#header'=>$header,
 '#rows'=>$row,
 );
 }
 else {

 $form['text'] = array(
'#type' => 'textfield',
'#title' => t('patient_id'
));

 $form['buttons']['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit Button'),
//'#ajax'=> array('callback'=>'anonymous_page'),

);
}
return $form;
}

in the form submit add

$form_state['rebuild']=true;


How can I extend drush aliases with specific variables? I like to know if it is possible to extend drush aliases with more specific path variables. Is there anybody who can tell me how to extend the drush example code, that follows below with array for the file system paths for

temporary files directory
files directory
private files directory

So that I don't have to change them manually after every db sync when the dev server has other path settings then the productive server

This may be a silly question but I just looked at the documentation on github and haven't found any details.

The Drush rsync and drupal-directory (dd) commands already supports the functionality you desire, without the need for you to extend your alias files.  For example, to copy your files directory:

drush rsync @live:%files @dev:%files

To copy a specific folder from your temporary directory:

drush rsync @dev:%temp/foo @live:%temp

To change your working directory to the location where the devel modulr is installed:

cd $(drush dd @dev:%devel)


how to count the results from the exposed filter I have created the content type named candidate_profile, included fields like candidate_name, current_position_description, location , Current_Salary_Range, New_Business_Achievements and Categories_ of_Experience and I have created a view named display_candidate and also I am using better-exposed filter  for current_salary_range field hence how should I proceed to count the results from the exposed filter...?

You can get that in the view itself.

view->Header->"Global: Result summary"


header("Location: /") redirect in template file only works if user is logged in. Why? I was developing a new feature for a client, and deployed it live today.  However, due to circumstances out of my control, they decided to implement an alternative solution and asked me to implement a temporary redirect.

This feature was a standalone full screen flash app that did not fit the site theme at all.  So, I implemented the page as a custom html--pagename.tpl.php file and loaded the page-specific JS and CSS.  It is a custom template for an existing content type.

Now, since the client wants a temporary redirect, I added

header("Location: /");

as the first line of PHP code in the template to redirect any access to that URL to the index page.  However, this only works if the user is logged in.  Anyone
else can view this page and the header code seems to be ignored for some reason.

This URL loads regardless of the Published status set to Published or Unpublished.  In the morning, I will modify the .htaccess to execute a 302 redirect, but would like an explanation for this behavior for future reference.

Output of the tpl files is cached for anonymous users. But only their text output is, that's how Output Control Functions in PHP works. That's why Drupal API functions will not work as intended, either. They may do their job, all right, by serving as cache breakers, but you do not want to break cache on a busy website, as it may be a server killer.

Most stable way of doing temporary redirections is, as far as I found, an .htaccess way. mod_rewrite is already used by Drupal, so it cost you nothing in additional binaries loaded to memory, and it acts before PHP is even started. As described in this answer on SO, you can do this like that:

RewriteRule ^example/my-stuff/$ /example/home/ [L,R=301]

Put it before Drupal redirects, but in the same section.

If you need a PHP logic to decide if redirect is needed, you can do it using hook_menu_alter() instead:

Substitute original callback with yours
Perform any logic needed
Log to watchdog if you want to

Call original callback and return it's result if you are not redirecting, or
Redirect with drupal_goto('<front>')


How to implement a jscript for displaying custom ads I am very much a beginner with scripting, drupal theming, etc and I cannot figure out how to deal with the following "problem":

I have signed up my site with a media network, which will handle all the ad revenue making.
They have given me a custom .js script and shared the following generic instructions:

upload the .js script to the website - That I can do. :)
paste <script type="text/javascript" src="path to script/scriptname.js"></script> into the <head></head> area of all pages on the website. I guess this means editing the page.tpl.php file of the theme I am using to add this piece of code. However, I do not know how to do this, in a way that works well, without breaking the theme and how the website is displayed.
call the script into specific ad areas/blocks using something similar to this: <script>scriptname.display(options = {'width':635,
'ad_width':190,
'max_ads':3,
‘descFontSize':15,
'linkFontSize':12,
'linkFontColor':'999999'});</script> Here, I am not sure if it is enough to simply copy/paste this code, while using the correct name of the script file.

The trouble is, these guys are used to working with WordPress and they won't advise me on how to set things up in Drupal. So... I appreciate any advice you can give.

PS: I am using the latest version of Drupal 7.

Upload your .js file in your theme directory.
In your theme's .info file add
scripts[] = path/file_name.js  as follows.

This will include the .js file in each page of your site. Path of the .js file is relative to the .info file.