Post becomes unpublished upon editing it and no additional date values or image uploads are possible I have a custom content with a large number of multivalue date fields (around 200-300 values). I created a node and added a large number of dates. When subsequently editing the post, the following occurs:

The post is saved as unpublished
Changes to the body field and other text fields such as tags are saved
No additional dates can be saved
Clicking on Preview doesn't show a preview, but saves the post as unpublished
Upon attempting to upload an image file, the Drupal message "[content-type] [post-title] has been updated" (with the specific values in place of the [...] placeholders) appears, but it appears BEFORE clicking Save; upon saving the post, no file is saved
"The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved." appears when clicking Save after the file upload
The node can be made Published from the content administration screen (but not from editing it individually)
The Revision tab is missing even though the content type has revisions enabled by default
The Authored on date is reset to the first time the node become unpublished

I would like to have some instructions as to how to debug this situation.

PS: The site is hosted on Hostgator.com.

I was having a similar problem when editing a node with a field that allowed for unlimited field collection values. Each field collection had 8 input fields, and after adding in over 100 field collection items it stopped adding in more and it would unpublish on Save.

I could publish it from the content administration screen.

I modified max_input_vars in the server php.ini file from max_input_vars=1000 to max_input_vars=2500 and that allowed for the addition of more field collection items and to keep the node published when saved.


Deduct 10% transaction fee when user donates userpoints to another user using rules - Drupal 7 I want to use rules to deduct 10% of the transaction amount from a donor each time he donates userpoints to another user using the userpoints_donate contrib module. Currently there are no rules events or actions from the userpoints_donate contrib module

possible events: user donates points to another user

possible conditions: donation_amount <=> a particular value

possible actions: grant points to donor = (donation_amount * -0.1, i.e grant -10% of donation_amount to donor)

How can i achieve this? Thanks

If you see userpoints_donate.module userpoints_donation_giveform_submit function is reponsible to award points to another user

/**
 * Submit function to give another user points.
 */
function userpoints_donation_giveform_submit($form, &$form_state) {
  global $user;

  $points = $form_state['values']['amount'];
  $to = $form_state['validated_account'];

  $tid = NULL;
  if (isset($form_state['values']['tid'])) {
    $tid = $form_state['values']['tid'];
  }

  $params = array(
    'uid'    => $to->uid,
    'points' => $points,
    'operation'  => 'userpoints_donation_received',
    'entity_type' => 'user',
    'entity_id' => $user->uid,
    'description' => $form_state['values']['reason'],
    'tid'    => $tid,
  );
  userpoints_userpointsapi($params);

  $params = array(
    'uid'    => $user->uid,
    'points' => -$points,
    'operation'  => 'userpoints_donation_given',
    'entity_type' => 'user',
    'entity_id' => $to->uid,
    'description' => $form_state['values']['reason'],
    'tid'    => $tid,
  );
  userpoints_userpointsapi($params);
}

As you see above

userpoints_userpointsapi($params); is called to award $points with transaction operation userpoints_donation_received .

You can use hook_userpoints($op, $params = array()) to act upon certain operations. When other modules award  points to a user, your hook will be called, among others.

  $op: The operation to be acted upon.
      'setting'
        Pass a field set and fields that would be displayed in the userpoints
        settings page. For example, this can be used for your program to ask
        the admin to set a number of points for certain actions your module
        performs. The function should return an array object conforming to
        FormsAPI structure.

  'points before'   Calls your module, and others, before the points are
  processed. You can   prevent points from being awarded by returning
  FALSE.

  'points after'   Calls your module, and others, after points are
  processed. You can take   certain actions if you so wish. Return value
  is ignored.

  The $params variable is the original $params array as sent to
  userpoints_userpointsapi

Using "Points after" $op and  in $params check for operation "userpoints_donation_received"  you make a call to deduct 10 % points using..

userpoints_userpointsapi($params); API function..

<?php
function YOURMODULENAME_userpoints($op, $params) {
  if ($op == "points after") {
    if ($params['operation'] == "userpoints_donation_received") {
      $transaction_params = $params;
      $transaction_params['points'] = -( $transaction_params['points'] / 10);
      $transaction_params['operation'] = "userpoints_donation_transaction_fee";
      $transaction_params['description'] = "Transaction Fee";
      userpoints_userpointsapi($transaction_params);
    }
  }
}


When is node_search() in the node module called? Someone has made changes to core, and specifically the node_search() function in the node module.

I'm not familiar with this function. What does it do, and under what circumstances is it being called?

node_search() is the node module's implementation of hook_search(), which:

  allows a module to perform searches on content it defines (custom node types, users, or comments, for example) when a site search is performed.

That hook is invoked from a number of different places.

At a guess I would say if someone was going to make changes to node_search() it would probably be for the 'search' operation (i.e. altering the results of the standard node search). That particular operation is invoked from search_data().

It might be worth having a look a regular copy of node_search() alongside your hacked copy to see if you can understand what the differences are, and whether you can revert the changes without breaking things (if that's what you need to do).


How to find where are defined tokens for Redirect? After enabling Token and Redirect modules, I've found at /admin/help/token that I can use Redirect tokens. For example:

However, I've got the problem finding the place where and how these tokens are defined (which file and hook or class).

Any ideas?

I've tried to search inside all files in docroot, e.g.

$ grep -r "The URL of the redirect" .
(nothing)
$ grep -r "The URL of the" .
(returns everything apart of redirect, no matching placeholders found)
$ grep -r token modules/contrib/redirect/
modules/contrib/redirect/config/install/views.view.redirect.yml:          tokenize: false
modules/contrib/redirect/modules/redirect_404/config/install/views.view.redirect_404.yml:          tokenize: false
modules/contrib/redirect/modules/redirect_404/redirect_404.routing.yml:    _csrf_token: 'TRUE'
modules/contrib/redirect/src/EventSubscriber/RouteNormalizerRequestSubscriber.php:      // Strip off query parameters added by the route such as a CSRF token.
$ grep -r redirect modules/contrib/token/
modules/contrib/token/src/Controller/TokenCacheController.php:   * Clear caches and redirect back to the frontpage.
modules/contrib/token/src/Controller/TokenCacheController.php:    return $this->redirect('<front>');
$ find modules/contrib/redirect modules/contrib/token -name "*.tokens.inc"
modules/contrib/token/tests/modules/token_module_test/token_module_test.tokens.inc
modules/contrib/token/token.tokens.inc (Note: nothing here for redirect)

So basically I couldn't find the source which module is defining those. This can help me in order to find out, why some of them aren't working as expected.

The main reason I ask this, because I would expect for redirect URL such as /foo/XXX, to return XXX when using [redirect:url:args:last], but these tokens aren't populated at all.

As Clive mentioned, since Redirect is an entity, those tokens are automatically generated by the Token module's token.tokens.inc.

I suggest you read Custom Tokens in Drupal 8 to understand how they are declared & work.


How can I make a template for a product type in Commerce? I want to be able to write my own markup for the fields (see image below) of each product type – how do I do this? My main reason for this is that I want to group them with my own HTML rather than the default provided.

I've tried using <?php print render($content['field_available_colors']); ?> and <?php print render($content['product:field_available_colors']); ?> in the regular node--[content_type].tpl.php and that didn't work.

I've also tried making a template specific for the product type, but nothing happens. I've been looking at the latest post in this thread, but I can't get any of the suggestion to work either...

I'd very much appreciate some help here, what am I missing?

Tried to add the following to template.php, but have no clue what to do with it really. Haven't worked in this way before at all, and this seems pretty steep.

function mythemename_preprocess_node(&$vars) {
  $product_display_types = commerce_product_reference_node_types();
  if (isset($vars['type']) && isset($product_display_types[$vars['node']->type])) {
    $vars['theme_hook_suggestions'][] = 'node__product__type__' . $vars['node']->type;
    $vars['classes_array'][] = 'node-product-type';
    if ($vars['view_mode'] == 'product_list') {
      $vars['theme_hook_suggestions'][] = 'node__product__type__product__list';
      $vars['classes_array'][] = 'node-product-type-product-list';
    }
  }
}

I believe that it is a product reference field, and therefore, the template suggestions are different. That is why creating random node template files is not having any effect. What you want to target is the entity being referenced.

You should check what templates or theme hooks exist in Commerce, and derive the templates from that. You can also add your own suggestions when preprocessing.

Here are some threads that will help:

https://www.drupal.org/node/1245354
https://www.drupal.org/node/1245354#comment-11788691
Is there a product.tpl.php for ALL product types in Drupal Commerce?
https://drupalcommerce.org/discussions/911/customize-way-product-displayed
https://drupalcommerce.org/discussions/337/how-theme-product-display

Note that if you add to template.php or introduce new templates, you will need to clear your caches so it is picked up by Drupal.

A bulletproof way to find out would be to do mytheme_preprocess_entity($variables) in your themes template.php file, and dump out $variables when it is preprocessing a product entity. Within it, you will see possible template suggestions for the product entity itself.

The same applies for fields as well. template_preprocess_field: https://api.drupal.org/api/drupal/modules%21field%21field.module/function/template_preprocess_field/7.x


How to do a RedirectResponse with a destination query parameter? This works:

$redirectURL = '/cart/add/p2';
return new RedirectResponse(base_path().$redirectURL);

The problem is, I want this:

$redirectURL = '/cart/add/p2?destination=somewhere';

The moment I added destination=somewhere, I get this error:

InvalidArgumentException: The internal path component 'http://localhost/XXXX/public_html/XXXX/XXXX' is invalid. Its path component must have a leading slash, e.g. internal:/foo. in Drupal\Core\Url::fromInternalUri() (line 404 of C:\ampps\www\XXXX\public_html\core\lib\Drupal\Core\Url.php).

However, if I do this:

$redirectURL = '/cart/add/p2?SOMETHING_ELSE=somewhere';

Then it works. In other words, it specifically breaks if I add "destination=somewhere".

Why would it be breaking on this and how do I get around it? I.e. How do I redirect to a URL with destination=somewhere in the query string.

FYI: If I can get this to work, I can use "Cart Links" to add stuff to a cart and redirect the user at the same time, making my live a lot easier.

Better use a route, so that the path processing in Drupal can do its job.
If custom.cart_add is the route to /cart/add/{page}, this returns a redirect response with a destination query parameter from a controller:

  return $this->redirect(
    'custom.cart_add',
    ['page' => 'p2'],
    [
      'query' => ['destination' => 'somewhere'],
      'absolute' => TRUE,
    ]
  );


Skip payment method selection in Drupal Commerce I have just installed Drupal Commerce Module with Paybox system and i wondering how can i bypass the "payment method selection". In fact there's only one payment method currently, so i'd like to bypass that step and proceed directly from the first step of the checkout to the last checkout step where there is the Paybox Js redirection.

Anyone already doing something similar?

Regards,
Geolim4

You would have to hide the payment method checkout pane via a form alteration, because the payment method still technically needs to be selected for the redirect page to show properly. However, if you just want to remove the "Review" page since you don't need it as an intermediate step for payment method selection, you could just move the payment method checkout pane to the "Checkout" page and disable the default review checkout pane.


Youtube video size in grid theme I am trying Omega and wondering if there is a way to specify the size of the Youtube video in grid terms, so I could easily show few videos next to each other (in a view for example).

Or if there is a way to make video automatically fit within a cell of a view?

Setting the video's width to 100% via CSS should make it fit whatever width you've given its wrapping cell or div.

Check out the FitVids module / library for an all round solution to making videos behave better on responsive sites.

http://drupal.org/project/fitvids

http://fitvidsjs.com


Do we need PHPMailer? We are building our website in Drupal 7. However, I wonder whether we need to configure and setup the PHPMailer module.

We are designing an ecommerce website that will send an email upon registration, online purchase, forum activity, etc.
We are confused about whether we need to configure PHPMailer in Drupal 7 or we can make use of Google SMTP services. We are totally clueless about this as we have been struggling to setup the PHPMailer.

You don't need PHPMailer. You will need an SMTP server of some description.

If your server is Linux, you will need to install some method of sending email such as postfix. You could either let the server distribute email itself, or configure postfix (or whatever) to relay it to another email server.

If it's Windows, I believe you can configure PHP to use an external SMTP server without needing one on the Drupal server itself.

If you were set on sending messages through Google's SMTP servers, you will probably want to use PHPMailer, as it's set up to make that sort of thing easy. Getting hold of your own SMTP server is not tremendously difficult, however.

Can you tell us more about your hosting environment? Maybe we could be more specific with the answer.


Added field to Basic Page Content Type is not displayed in the page This question may be a bit silly but I have been struggling with it for a long time and still no solution:

I have added the Star Rating Module to display rating stars in my pages. I have enabled the module and configured the "Basic Page" Content type to have the "rating" field. The point is that I edit a page, assign a rating properly but... when I view the generated page the starts don't show up!

I have tried adding another field, this time a text field, but it doesn't appear on the page either.

Any idea why additional fields added to "Basic Page" aren't displayed in the page?

There is nothing special about putting fields on the Basic Page.

However, to be visible, you have to make sure that the field is not <Hidden>.

To check that, go to the Manage Display  panel for the bundle (content type) you've got problems with.


load commerce coupon I want to load coupons that have commerce_discount_reference=4. I find  that can load them by commerce_coupon_load_multiple but I dont know how I add condition commerce_discout_reference=4.
maybe something like

  commerce_coupon_load_multiple(array(), array('commerce_discount_reference'=>4));

what is correct way?

Sounds like the perfect job for an EntityFieldQuery:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_coupon')
  ->fieldCondition('commerce_discount_reference', 'target_id', 4);

$results = $query->execute();
if (!empty($results['commerce_coupon'])) {
  $coupons = commerce_coupon_load_multiple(array_keys($results['commerce_coupon']));
}


$_SESSION vars created outside of Drupal lost when navigating to a Drupal served page I'm building a Facebook iframe app in Drupal.

I'm using an initial simple PHP script (non-Drupal driven) to handle the Facebook open auth side of things - this script is getting the Facebook user's name, id, profile pic etc.
This script stores those values to session vars. Then it redirects the user to a page served by Drupal.

My understanding looking at the D7 session.inc is that pre-existing session vars should be maintained when Drupal session start is called. But if I print_r() the $_SESSION array, it is empty.

So essentially a plain PHP script saying:

session_start();
$_SESSION['name'] = 'bob';

sets the session correctly.
But when then adding a redirect (header()) to a Drupal served page I can no longer get that name variable and the session is empty.

Any suggestions/tips?

Thanks,
Steve

A really good source related to your question from drupal.org's forum:
Struggling with Session Variables (the $_SESSION array) when redirecting to external php scripts

The key for codes outside Drupal's full control to work is to save PHP's current working directory, change it to Drupal's, requiring the needed file to bootstrap Drupal (includes/bootstrap.inc), pass the appropriate $cookie_domain variable ("the domain to be used for session cookies"!), bootstrapping Drupal, and then change the current working directory back to the original. After this, you can write your own codes and use Drupal's functions, mess with its session variables, etc. - of course, depending on the bootstrapping mode of Drupal.

The code to achieve it looks like this (you have to change $your_drupal_directory variable to yours, usually this is in the root, but its path can be different [e.g. if it's in a subdirectory]):

// ...

/**
 * @see http://drupal.org/node/575002
 */

// store current working directory
$currdir=getcwd();
// which is your Drupal directory? (usually it's in the root, but can be different)
$your_drupal_directory = $_SERVER['DOCUMENT_ROOT'];
// change PHP's current directory to Drupal's
chdir($your_drupal_directory);
// including bootstrap file...
require_once("./includes/bootstrap.inc");

// The domain to be used for session cookies. (see: http://api.drupal.org/api/drupal/developer!globals.php/global/cookie_domain/7)
$cookie_domain = $_SERVER['HTTP_HOST'];

// DRUPAL_BOOTSTRAP_SESSION: initialize session handling.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

// the code above should be enough for your task, but if you want Drupal to be "fully loaded, validate and fix input data", you could try the following too (see: http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_bootstrap/7)
// drupal_bootstrap( DRUPAL_BOOTSTRAP_FULL );

// change PHP's current directory BACK to the original
chdir($currdir);

// ...
// YOUR OWN CODE COMES HERE
// ...


taxonomy terms view with custom alphabar (for Spanish) I have a lot of views displaying taxonomy vocabularies with alphabar, the problem is that all the alphabar are by default showing the order for English alphabet, Spanish has ñ and accented letters, at both the alphabar as in the views, words starting with this letters are sent to the back, for instance, alphabar is like this:

......w | x | y | z | ñ | á | é | í | ó | ú

the ñ should be placed after n and those letters with accent shouldn't appear, they should be included within the corresponding unaccented letter

same for order in the view, for instance words are ordered like this (fictional words for the example)

awto
axma
aypa
azor
años
aísi
aóko
etc.

when correct order should be like this:

aísi
años
aóko
awto
axma
aypa
azor

Any idea on how to solve this? Thanks in advance!

I've been reading some documentation about
character settings in mysql, and I have found a solution, I don't know if it's the right way for drupal, and it would not interfere with the taxonomy modules at update time in some way, I hope somebody could comment on this....
Anyway I just changed at the taxonomy_term_data table the collation of the "name" field to utf8_spanish_ci


What's a good access module for a state-level organization? I'm setting up a new website for the Maine Grand Chapter of the Order of the Eastern Star. My goal is to allow each chapter to access their own chapter's node (and nobody else's) and modify the content (annual updates to officers, calendars, etc.) and hopefully also to maintain a group calendar (modules for this yet to be chosen). So, my question at the moment is what the best node access module to use for this purpose is. I'm using D7.20. Flexi access looks interesting, but there are so many to choose from...

You should look at the Organic Groups module. This will allow you to designate individual users as responsible for the each group, and will allow each chapter to post content to their own chapter (kind of a mini web page for each chapter).

You can see an example of this format here.


How do I cache an object loaded through SOAP from a third party that I use in forms? I am loading and object that I use to populate a form. Then on form submit I return some of the fields through SOAP back to the third party. On submit the form building function gets called and loads the object then the submit function gets called and loads the object again. How do I cache the object so that it is only loaded once but available to both or more function to act on it.

Would it not be possible for you to simply pass off the data you need in fields of #type => value? These are passed safely behind the scene through the entire form submission process, acting in a sense as the cache you are striving for.  Consider the following simplistic example :

$form['soap_data_email'] = array('#type' => 'value', '#value' => $soap_data_email);
$form['soap_data_name'] =  array('#type' => 'value', '#value' => $soap_data_name);

After submission, all your soap object's values would be available in the validation and submit callbacks of your form through the usual $form_state['values']['soap_data_email'] and   $form_state['values']['soap_data_name'] array.

If you have many variables this could all be factorised to be more efficient, but this should give you the basic idea.

This is the simplest way I can think of that lets you cache your data all across the form validation and submission process.


How to redirect the user to a product page (node) after payment is made? How to redirect the user to a product page (node) after payment is made?

I'm using the Commerce Express Checkout module. That's why in the Shopping cart can be just one product.

One option is to use hook_menu_alter in a custom module to override your current destination page with a redirect.

<?php

function mymodule_menu_alter(&$items) {

    $items['current/checkout/path'] = array(
        'page callback' => 'drupal_goto',
        'page arguments' => array('new/checkout/path'),
        'access callback' => TRUE,
      );

}

Update:

To use the above code, you'll have to create a module.

1) Create a directory to be used for this module, e.g. /sites/all/modules/MYMODULE

2) Create MYMODULE.info, e.g. /sites/all/modules/MYMODULE/MYMODULE.info. Paste the following into the file.

name = MYMODULE
description = "Module description."
package = Custom
core = 7.x

3) Create MYMODULE.module, e.g. /sites/all/modules/MYMODULE/MYMODULE.module. Paste the following into the file.

<?php

function MYMODULE_menu_alter(&$items) {

    $items['current/checkout/path'] = array(
        'page callback' => 'drupal_goto',
        'page arguments' => array('node/123'),
        'access callback' => TRUE,
      );

}

4) Replace all instances of MYMODULE with your desired module name. Replace current/checkout/path with the current path of the checkout. Replace node/123 with the new checkout path. Lastly, enable your new module.

This will tell Drupal to replace the current checkout page with a redirection to the new one.


Drupal 7 pager from module fuction not displaying in page.tpl I have a function mymodule_submissions in my module which fetches rows from mymodule_table and prints as table theme with pager. Its working fine if I define a menu link in my module to call that function. Pager not printing when I call the same function from a page.tpl.

function mymodule_submissions() {

   $query = db_select('mymodule_table', 'uf');
   $query = $query->condition('uid', $user->uid)
             ->fields('mytable', array('id', 'name', 'createdtime'))
             ->orderBy('createdtime', 'DESC')->limit(3);
   $results = $query->execute();
   $header = array('ID','Name','Created Time');

   $rows = array();

   foreach($results As $result) {
      $rows[] = array( $result -> id, $result -> name, $result -> createdtime,);
   }

   $output .= theme('table', array('header' => $header, 'rows' => $rows,) );

   $output .= theme('pager');
   return $output;
}

From page.tpl, I am calling this function link below

print render(mymodule_submissions());

Anything I'm doing wrong?

You just need to add ->extend('PagerDefault');

$query = db_select('mymodule_table', 'uf')->extend('PagerDefault');

I find the examples module really useful.  They have a pager example.

For what its worth I think using the Drupal db API with theming is a perfectly valid way forward that has a lot of strengths: it's efficient, flexible, powerful and you can put it in version control.  Obviously you should use the best thing for the situation.


How can I get sub-directory names? How can I get the list of the folders inside public:// (or sites/default/files) location?

I have to show all the folder names to users, so that they can choose the subdirectory where they prefer to upload their documents.

I tried with the following code, but it returns the path together the folder name.

$directories = glob($somePath . '/*' , GLOB_ONLYDIR);

The value returned from my code is similar to the following one.

    [0] => sites/default/files//folder_name
    [1] => sites/default/files//new1
    [2] => sites/default/files//newfolder

You can ready the directory using read() function and drupal_realpath('public://') will give you the actual path to the public files folder.

$path = drupal_realpath('public://');
$dirs = array();
// directory handle
$dir = dir($path);

while (false !== ($entry = $dir->read())) {
    if ($entry != '.' && $entry != '..') {
       if (is_dir($path . '/' .$entry)) {
            $dirs[] = $entry;
       }
    }
}

echo '<pre>';print_r($dirs);echo '</pre>';


field collection - taxonomy term can't display I used taxonomy term with field collection and taxonomy term can't display
look this video

https://www.youtube.com/watch?v=cEI1yDcJXT4

By default the taxonomy term page will list all content (NODES) that is referenced by this term. In your case you are referencing the field collection item by this term.

To display the nodes in the term page you need to create a new view as below:

Create a view of type content and add a relation to the field collection type.
In the view filters you need to add filters by content type and another filter to restrict the result by the taxonomy you are using.
Add a contextual filter that will filter the results by the term id - provide a default value from the URL, thus will ensure that you are displaying only nodes referenced by the term id you are viewing.

now you need to use page manager, context, custom code, etc... to place this view in the term page.

How it will work:
When you are viewing a term page it will display the view we previously created. this view will extract the term id from the URL and query nodes related to the term.


How to make user as an exposed filter option in filter criteria of a normal view? In a view, I want list of users of specific role to be exposed filter option, which will list all users of that role.

Example: What I want is in view type like order or customer of ubercart(example), I want user to be filter criteria with exposed filter option of specific role(buyer or seller). If i select one user that particular user order should be listed.

Is that possible?? If so then how?

Thanks in advance.

You may install this module Total Control module. After installing this module goto this link yourdomain.com/admin/structure/views/view/control_users/edit

This view provides the functionality you want.

To see it working you visit the page through this link yourdomain.com/admin/dashboard/users

EDIT I have export the view and pasted it below in-case you just need a reference and don't want to install that module.

$view = new view();
$view->name = 'control_users';
$view->description = 'Total Control over user accounts: Contains a panel pane and a page to control user accounts.';
$view->tag = 'total_control';
$view->base_table = 'users';
$view->human_name = '';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['title'] = 'User Accounts';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'have total control';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Filter';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '35';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'mail' => 'mail',
  'rid' => 'rid',
  'status' => 'status',
  'created' => 'created',
  'login' => 'login',
  'delete_node' => 'delete_node',
  'edit_node' => 'edit_node',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'mail' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'rid' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'status' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'created' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'login' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'delete_node' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'edit_node' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Bulk operations: User */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'users';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['label'] = '';
$handler->display->display_options['fields']['views_bulk_operations']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::user_block_user_action' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'action::views_bulk_operations_user_roles_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::system_send_email_action' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 1,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
/* Field: User: E-mail */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
/* Field: User: Roles */
$handler->display->display_options['fields']['rid']['id'] = 'rid';
$handler->display->display_options['fields']['rid']['table'] = 'users_roles';
$handler->display->display_options['fields']['rid']['field'] = 'rid';
/* Field: User: Created date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'users';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Created';
$handler->display->display_options['fields']['created']['date_format'] = 'custom';
$handler->display->display_options['fields']['created']['custom_date_format'] = 'm/d/Y';
/* Field: User: Last login */
$handler->display->display_options['fields']['login']['id'] = 'login';
$handler->display->display_options['fields']['login']['table'] = 'users';
$handler->display->display_options['fields']['login']['field'] = 'login';
$handler->display->display_options['fields']['login']['date_format'] = 'custom';
$handler->display->display_options['fields']['login']['custom_date_format'] = 'j/d g:ia';
/* Field: User: Edit link */
$handler->display->display_options['fields']['edit_node']['id'] = 'edit_node';
$handler->display->display_options['fields']['edit_node']['table'] = 'users';
$handler->display->display_options['fields']['edit_node']['field'] = 'edit_node';
$handler->display->display_options['fields']['edit_node']['label'] = 'Edit';
$handler->display->display_options['fields']['edit_node']['text'] = 'edit';
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: User: Name */
$handler->display->display_options['filters']['uid']['id'] = 'uid';
$handler->display->display_options['filters']['uid']['table'] = 'users';
$handler->display->display_options['filters']['uid']['field'] = 'uid';
$handler->display->display_options['filters']['uid']['operator'] = 'not in';
$handler->display->display_options['filters']['uid']['value'] = array(
  0 => 0,
);
$handler->display->display_options['filters']['uid']['expose']['label'] = 'User: Name';
$handler->display->display_options['filters']['uid']['expose']['operator'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['identifier'] = 'uid';
/* Filter criterion: User: Roles */
$handler->display->display_options['filters']['rid']['id'] = 'rid';
$handler->display->display_options['filters']['rid']['table'] = 'users_roles';
$handler->display->display_options['filters']['rid']['field'] = 'rid';
$handler->display->display_options['filters']['rid']['exposed'] = TRUE;
$handler->display->display_options['filters']['rid']['expose']['operator_id'] = 'rid_op';
$handler->display->display_options['filters']['rid']['expose']['label'] = 'Roles';
$handler->display->display_options['filters']['rid']['expose']['operator'] = 'rid_op';
$handler->display->display_options['filters']['rid']['expose']['identifier'] = 'rid';
/* Filter criterion: User: Name */
$handler->display->display_options['filters']['uid_1']['id'] = 'uid_1';
$handler->display->display_options['filters']['uid_1']['table'] = 'users';
$handler->display->display_options['filters']['uid_1']['field'] = 'uid';
$handler->display->display_options['filters']['uid_1']['value'] = '';
$handler->display->display_options['filters']['uid_1']['exposed'] = TRUE;
$handler->display->display_options['filters']['uid_1']['expose']['operator_id'] = 'uid_1_op';
$handler->display->display_options['filters']['uid_1']['expose']['label'] = 'Username';
$handler->display->display_options['filters']['uid_1']['expose']['operator'] = 'uid_1_op';
$handler->display->display_options['filters']['uid_1']['expose']['identifier'] = 'name';
/* Filter criterion: User: E-mail */
$handler->display->display_options['filters']['mail']['id'] = 'mail';
$handler->display->display_options['filters']['mail']['table'] = 'users';
$handler->display->display_options['filters']['mail']['field'] = 'mail';
$handler->display->display_options['filters']['mail']['operator'] = 'contains';
$handler->display->display_options['filters']['mail']['exposed'] = TRUE;
$handler->display->display_options['filters']['mail']['expose']['operator_id'] = 'mail_op';
$handler->display->display_options['filters']['mail']['expose']['label'] = 'E-mail';
$handler->display->display_options['filters']['mail']['expose']['operator'] = 'mail_op';
$handler->display->display_options['filters']['mail']['expose']['identifier'] = 'mail';

/* Display: User Admin */
$handler = $view->new_display('page', 'User Admin', 'page_1');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'admin/dashboard/users';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'User Accounts';
$handler->display->display_options['menu']['weight'] = '-14';


Basic code to make a module themable I almost titled the question "Hello world of theming a module", as that quite well describes what I'm looking for. I feel maybe it's to much "slang" though. There's probably a lot of people out there in this situation. I know a lot about programming, but very little about (Drupal) theming.

So, for a trivial "Hello world" module like:

function _modules_page_callback($data) {
  return '' . $data . '';
}

What does the equally trivial version look like, that moves the HTML into the theme-layer?

You first let Drupal's theme system know about your "theme" functions. You just create a function called mymodule_theme and that should return an array with your theme functions defined. See hook_theme for more details.

Example:

function mymodule_theme() {
  return array(
    'funstuff_output' => array(
      'variables' => array('node' => NULL),
    ),
  );
}

Now the 'funstuff_output' function does not exist... so create it!

function theme_funstuff_output($variables) {
  $node = $variables['node'];
  $output = '<h1>' . $node->title . ' is fun stuff</h1>';
  return $output;
}

Now you can call taht theme function anywhere like so: print theme('funstuff_output', array('node' => $node));

In Drupal 6, I think variables is called arguments and there are some other differences. But that's the basics.


How to fix entity property X doesn't support writing, when setting content type field values? I've got a D7 content type with a few fields; nothing particularly special.  I want to be able to programattically change the values of those fields from time to time, and so wrote a function like so:

function set_field_value($field_name, $node, $value) {
    $wrapper = entity_metadata_wrapper('node', $node->nid);
    $wrapper->$field_name = $value;
    $wrapper->save();
}

This worked in a few test cases (like changing the title of a blog node), but when I try it on content type fields, I get an error like:

  EntityMetadataWrapperException: Entity property field_project_video_status_yt doesn't support writing. in EntityStructureWrapper->setProperty() (line 497 of ...)

What I'm doing wrong?

Short Answer: It is not possible to write to that field type using entity metadata wrappers. You may want to raise the issue with the maintainers of the module that provide that field type.

Long Answer: The Entity Metadata Wrapper you are using is provided by the Entity Module. This module extends Drupal's entities in various ways. One of the things it offers is to extend the information about fields, by offering it's own hook, hook_entity_property_info. This hook allows, amongst other things, to define a setter callback. This is the function that is used by the entity meta data wrapper to set the value of a field or property.

The error you are seeing implies that this function is missing for the field type you are trying to access.

The Entity module itself actually provides a default function for fields that do not define their own setter callback. What this means is that :

Either the module that creates the field you're using implements hook_entity_property_info and does not define a setter callback; or
Another module explicitely removes the setter callback from the field type you are using.

Either way, you cannot use entity_metadata_wrapper for that field type until the issue is resolved. You should raise it with the people who maintain the module providing that field type.


When hook_field_info_alter is invoked? I am trying drush cc all, but no luck.

https://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_info_alter/7

I need to programmatically hide a field and thinks that this is place to go.

It's invoked in several places. It happens in _field_info_collate_types(), which is called from

field_info_cache_clear()
field_info_field_types()
field_info_formatter_types()
field_info_storage_types()
field_info_widget_types()

So there's a fairly large surface area for invocation.

hook_field_info() is for providing metadata about fields, though, so using it to programatically hide a field is doomed to failure. You simply don't have that option in the info hook.

Depending on what you mean by "hide" you'll either want to implement a form alter hook (to remove a field from a form), or a preprocess/view hook to hide it from being rendered, or maybe both. Obviously YMMV if you mean something other than those options.


hook_field_formatter_third_party_settings_form doesn't fire I'm attempting to add a checkbox to a field settings form in D9. I have the following code:
function my_module_field_formatter_third_party_settings_form(\Drupal\Core\Field\FormatterInterface $plugin, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, $view_mode, $form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $element = array();
  print '
HERE
';

  if ($plugin
    ->getPluginId() == 'text_textarea_with_summary') {
    $element['my_setting'] = array(
      '#type' => 'checkbox',
      '#title' => t('test'),
      '#default_value' => $plugin
        ->getThirdPartySetting('my_module', 'my_setting'),
    );
  }
  return $element;
}

I then edit an instance of a body field (admin/structure/types/manage/article/fields/node.article.body), and the hook doesn't fire...no debug text nor stopping at the breakpoint on that same line.

There are two problems.
/admin/structure/types/manage/article/fields/node.article.body is the path of a field setting. To trigger the hook you need to visit /admin/structure/types/manage/article/display.
The plugin ID is wrong, too. text_textarea_with_summary is the plugin ID of a widget. What you are looking for is probably the formatter text_summary_or_trimmed.
If this is neither formatter nor widget, but the content type specific field definition, then use a normal form alter hook, because there is no specific hook to add third party settings:
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_form_alter().
 */
function my_module_form_field_config_edit_form_alter(array &$form, FormStateInterface $form_state) {
  /** @var \Drupal\Core\Field\FieldConfigInterface $field */
  $field = $form_state->getFormObject()->getEntity();
  if ($field->getType() == 'text_with_summary') {
    $form['third_party_settings']['my_module']['my_setting'] = [
      '#type' => 'checkbox',
      '#title' => t('test'),
      '#default_value' => $field->getThirdPartySetting('my_module', 'my_setting'),
    ];
  }
}

Edit: The form keys $form['third_party_settings']['my_module']['my_setting'] are important. They are used to submit the third party settings.


How can I integrate a stemmer with Search API? Exactly what the question says - I'm using Search API with Database Search. I also have the Porter Stemmer module, but my understanding is that it only works with the Drupal built-in search.

Any help with this would be greatly appreciated.

It is possible to use the Porter Stemmer module with other modules besides the Drupal standard search. I have done it before (with Views exposed filters).

In your module, you could either invoke the porterstemmer_search_preprocess() function or just copy its contents into your own function. And then pass your search terms to this function. E.g.:

function your_function_for_preprocessing_text($text) {
   // Include porterstemmer (change accordingly).
   module_load_include('module', 'porterstemmer');

  // Convert text to lower case, and replace special apostrophes with regular
  // apostrophes.
  $text = drupal_strtolower(str_replace('’', "'", $text));

  // Split into words
  $words = preg_split('/(' . PORTERSTEMMER_BOUNDARY . '+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

  if (!count( $words )) {
    return $text;
  }

  $has_pecl_stem = _porterstemmer_pecl_loaded();

  // Process each word, skipping delimiters.
  $isword = !preg_match('/' . PORTERSTEMMER_BOUNDARY . '/', $words[0] );
  foreach ($words as $k => $word) {
    if ($isword) {
      if ( $has_pecl_stem ) {
        $words[$k] = stem_english($word);
      }
      else {
        $words[$k] = porterstemmer_stem($word);
      }
    }
    $isword = !$isword;
  }

  // Put it all back together (note that delimiters are in $words).
  return implode('', $words);
}

As I said, I have used the Porter Stemmer to stem all the terms entered in a Views exposed search. However, you'll still need to find the right hook in the Search API module to pre-process the text before the search query is run against the database.


How to customize a single default taxonomy page? In Drupal, we have default taxonomy pages. These pages have the same view. We want to change the layout of one of those pages. Is it possible?

If you are using the standard issue taxonomy module to output your pages, eg:

www.yourhost.com/taxonomy/term/###  (or whatever its eventual alias is)

you can modify taxonomy-term.tpl.php to do almost anything you want.

In D7, it's provided for you and basically looks like this:

<div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes; ?>">

  <?php if (!$page): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

  <?php endif; ?>

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

The key variable to your question is $term and you could do something like this:

<div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes; ?>">

  <?php if (!$page): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

  <?php endif; ?>

    <?php if ($term->tid==THE_TID_YOU_ARE_LOOKING_FOR): ?>
       <?php // do something different here ?>
    <?php else: ?>
      <?php print render($content); ?>
    <?php endif; ?>


How can I force a user to submit webform before viewing certain pages? I have a client who wants a webform to pop up when a user views a search result page. They want to user to submit their contact info in order to view the results, but only once in case they search multiple times.

Your best bet is to use this the splasify module: https://drupal.org/project/splashify

As for popping it up only once, you'll have to set a cookie somehow to track that it has popped up already. It might be suppored in that module already.


Is it possible to apply Authcache caching to elements in page.tpl.php? In applying Authcache settings to an existing site I have encountered a problem where certain items hard-coded into the theme's page.tpl.php need to be personalised for each user. I could do it by moving those components into blocks and/or panels, but they are quite complex and I was wondering if a better approach would be to do it via the Authcache API using the authcache_usercookie.module example as a starting point.

Here is an example of the code I would like to personalise:

<?php if($page['topics_tab']): ?>

        <?php print render($page['topics_tab']); ?>

<?php endif; ?>

Is it possible (easy? difficult?) to modify page.tpl.php to make Authcache cache this snippet for each user, or should I redo the page using blocks/panels?

I recommend to redo the page with blocks (or panels). The Authcache User Cookie example is rather basic and does not demonstrate how to deliver fragments from the custom front controller.

Regrettably there is still not enough documentation on how to roll your own custom fragment renderer. Look at the api.php files and read through the numerous submodules to get the picture.

Last but not least, there are some (closed) support requests in the ticket tracker covering this issue, e.g. #2780485.


Theme specific login redirection? Anyone know of a way within the theme to redirect to a different url after login?

Theme #1:
Eg. User goes to www.examplesite.com logs in and is taken to www.examplesite.com/front

Theme #2:
Eg. User goes to www.examplesite.com logs in and is taken to subdomain.examplesite.com

I know of modules that allow us to do this for the entire site but have not found a way to do it just for a single theme.

Background: its for the mobile site UX.

http://drupal.org/project/login_destination would seem to offer a possibility to use custom PHP snippets as conditions for destinations.

So you need to find out which theme is being used. As I cannot fathom how you are changing your theme in the first place, I cannot help you with that.


Issues importing nodes containing taxonomy terms with &/& using feeds I have a view that outputs XML either on screen (using Views Datasource) or a file (using Views Data Export), and I'm attempting to import the data generated by the view using the feeds module.

The view contains several taxonomies, some of which contain terms with an ampersand (e.g. "Finance & administration).

The datasource view outputs the term without encoding these ampersands "&", while the views data export seems to encode them regardless of the setting in the view to do it or not. (The value stored in the dB is "&", not "&amp".)

With the datasource feed import, it appears all nodes that have & in at least one term associated to the node are skipped. I say this because those nodes never even show up in the debug output (which sounds like a bug to me).

With the views data export XML file import, all the nodes are imported, but the taxonomies that accept multiple values never get set properly.

Using Feeds tamper, I have tried using html entity decode/encode, and attempted to use it before/after explode, but nothing seems to fix either issue. I believe I should focus on the XML file import since at least all nodes are being imported.

Any thoughts on what may be happening during the XML file import, and how to address the issue? All the modules are the latest stable version.

I am using Feeds XPath Parser to import an XML file that contains a couple of fields that I then map to terms in two different vocabularies. It looks like the parser removes ampersands before Feeds Tamper kicks in. This leaves the terms with three spaces where previously there was a space, an ampersand and another space.

My solution - was to create a Find Replace tamper plugin that looks for three spaces in the imported text and replaces the three spaces with a space, an ampersand and another space.

Not pretty, but it works. Of course, this solution won't work if there are other special characters in the feed that would also be removed. In that case, I'd create multiple Find Replace plugins that look for the specific text strings, such as "Canada   Alaska" and replacing them with the corrected string, i.e. "Canada & Alaska". Even less pretty but ...


Render a referenced node via token in field This feels like it should be something people have tried, but I can't find anything after some googling. My use case is simple, I have a node type that only has 2 fields, body and media. The media field is, in fact, an entity reference field pointing to another node type (this is done because there are special cases where the media needs to be rendered HTML). All, I'm trying to do is render the referenced media field, by delta, in the main content area.

I can use the token [node:field-media:0] and print the title with no problem, I can print individual fields without an issue. Is there an existing method to print the rendered entity? I'm good with it using the default view mode.

I know I can code this up, but it seems like such a simple thing I figured there would already be a contrib module out there.

If I understand you correctly, you are trying to render a node inside another node.

In the past, I have used the Display Suite module to perform exactly this task.

With DS you can create custom view modes for content types. For example, for your media content type, you can create a new view mode called 'Embedded' and structure the display to include the fields you want.

Then, in your first content type, you can set the entity reference field to display a rendered entity and select the view mode you just created. The node page will display 'both' nodes as you've structured them.

Note: DS also exposes a Token view mode for you to be able to manage how the token version of a content type gets rendered. The token view mode is useful if you must use tokens (i.e. inject node into the body text), however rendering the entity just in the field formatting should cover a majority of the use cases.

DS is actually quiet deep in functionality - I use it for every build to structure content types, render html in the way I want, etc.

Hope that helps.


Use an entity reference in URL as Views Contextual Filter My site allows users to create a "booking request" node related to a "vehicle" node. I use an Entity Reference to connect the two by prepopulating a "Vehicle" field on the "booking request" node via a string in the URL:

http://example.com/vechiclename=&overlay=node/add/booking%3Ffield_vehicle%3D84

I would like to display a views block on this overlaid page with more info from the related vehicle. As you can see, the NID of the vehicle is in the URL (84), but I don't know how to target it.

I'm familiar with grabbing a path component from the URL, but it's the &field_vehicle=84 that is new to me. Any ideas?

I have never added a views block into the admin overlay (trying to get a parameter from the URL form the views block). But this is how I would approach the problem.

In your view, pick the 'Block' display. Add a contextual filter for the field that is referencing (Vehicle). Expand 'When the filter is not available'. Pick the option PHP Code. User the following code:

return (isset($_GET['field_vehicle'])) ? $_GET['field_vehicle'] : 'all';

I am using 'all' as fallback assuming that you will show everything if a value isn't available. But I guess you can use FALSE if you want it empty.

Save it. Add the block into your overlay/admin theme. Check if it works...

Best regards.


Why does Drupal use strange file extension for PHP code? Is there any hidden reason why Drupal developer decided to use strange file extensions — for example node.install, node.module, simple.profile, case.test? Why not just using stand .php extension?

Thanks

Because it's easier for the core to know about special files that way.

As a developer you're free to name your module or theme whatever you like, so that means that Drupal core needs another way to find and identify certain important files.  Doing this using the file extension is an easy way.


How to use ctools_ajax_command_redirect with $_GET parameters Is it possible to use ctools_ajax_command_redirect with $_GET Parameters ?
I am only able to redirect it to an absolute path as of now ..

I finally figured it

Following is the sample usage with POST param param1 with value as value1

ctools_ajax_command_redirect('url_path_without_base_url',0,array('query'=>array('param1'=>'value1')));


entityform view filtered by current user field (term reference) I have an entityform type that uses a term reference (department).
This term reference was also added to user accounts.

I'd like to make a view that displays the form submission for the same department as the currently logged in user.

I can't seem to make it work because if I go with a user view, I'm not able to retrieve all the entityform fields that I need.
If I go with an entityform view, I'm not able to retrieve the current user's department. I can make a relationship only with the form submitter and that field is never empty so I don't think I can default to the 'current logged in user'

Any ideas?

Since you want to list entities that use the same term reference as the user account, its best to create a view of terms and add relationships to the user and entityform.

Add the entityform fields that you want, using the entityform submission relationship.

Then add the term reference field two times, one with the user relationship and one with the entityform submission relationship. You may hide these fields.

Then add filter 'field comparison', selecting both term reference fields, and choose 'is equal to'.
Also add the filter User (using relationship) is 'currently logged in user'

The result is a view showing entityform submissions that have the same term reference value (department) as the currently logged in user.


Module to allow multiple paths for a single node? Is there a module that would allow me to define multiple paths for a single node? (Not just one node; I need to do this for multiples.) For example, I need to be able to access http://www.example.com/node/153 via both http://www.example.com/tracks/big-picture and http://www.example.com/big-picture.

I need to be able to define at least one of the paths manually, i.e. not using a pattern.

You can already do this using core's Path module in Drupal 6. If memory serves, it should be in admin/build/path/add. Simply create two aliases that both point to node/153.

I should caution, however, that this may raise red flags with search engines. They typically frown on duplicate content, and your SERP rankings will likely suffer as a result.


How to sort images in Views by their position? If you have multiple images uploaded to your node, on the edit mode you can drag those images up and down and position them. How do I set that top image is shown first in Views?

Which sort option is that for the image field?

sort your view with field_image:delta, ascending


How to clear unused files from the database and the filesystem? I would like to have a script that runs on cron, to delete all files that are not currently being used. I noticed that the file_usage table and the hard drive are getting filed with them.

Is there a way to do so?

Drupal should be taking care of this for you. The pattern that modules should be following is:

When you're adding a new file call file_save() (or a function that calls calls it) then call file_usage_add() to let the system know it's being used.
When you're done with a file call file_usage_delete() to release it then call file_delete($file, FALSE). The FALSE indicates that it should be deleted only if nothing else is using it.

So unless you've got a buggy module there probably aren't to many unused files sitting around but if you wanted to check it you could run the following query:

select fm.* from file_managed fm
left join file_usage fu on fm.fid = fu.fid
where fu.fid is null

I ran that on a test site and noticed that the devel_generate module isn't properly registering usage of the user's pictures when it creates them. You might notice similar things.


Implementing direction of a 1:n relation with entity-reference Consider two content types A and B which are in a 1:n relation (say any A entity will be referenced by n entities of type B).
Implementing such a relation with entity-reference fields can be done in 2 ways:

content type A holds the relations:

CT A has its own fields plus one multi-value entity-reference type filed that will store the references to all the B type entities
CT B has only its own fields

content type B holds the relations:

CT A has only its own fields
CT B has its own fields plus one single-value entity-reference type field that will store the reference of each B entity to its own
parent A type entity.

With the first implementation (A type with a multi-value field) I give the user the possibility to sort the related entities, which is not possible with the second implementation.

Is there anything, on the contrary, that is possible to realize with the second implementation but not possible with the first one?

Your claim that "With the first implementation (A type with a multi-value field) I give the user the possibility to sort the related entities, which is not possible with the second implementation." is false.

Some things may be easier one way. Other things may be easier the other way. But ultimately, with Views you should be able to accomplish pretty much anything with both of these approaches. So use the one that's natural for your data.


Displaying field twice in same node I want to have two styles of a specific field. How can I display the field twice so I can style each one differently?

Inside node.tpl.php instead of printing the whole content you can print fields seperately:

<?php print render($content['field_name']); ?>


drupal 8 image dialog position I really hope somebody can help me out with this: I'm designing a Drupal 8 project and I'm using the built-in CKeditor to edit articles. But the image popup renders outside of screen bounds and I can't find how to fix that. There seems to be no way to influence the top parameter of the dialog.

Thanks a lot!

Matt.

Im not able to reproduce it on my drupal 8 projects. It might come from your front-end theme. Try to use an administrative theme for edition, like seven.

{yoursite}/admin/appearance
At the bottom of the page check use administrative theme for editing.

If the issue doesn't occur anymore on theme seven, you should start by checking in your front-end (custom?) theme for styles on thoses classes :

ui-dialog ui-widget ui-widget-content ui-corner-all ui-front editor-image-dialog ui-dialog--narrow ui-dialog-buttons


Permission to Reply to Comments How to allow posting replies to comments to certain user roles only?
The goal is to allow users to post comments but not reply to them and have only certain roles able to post replies.

Initially I thought of hiding reply link for certain roles. But it is not a very bullet proof solution. Anyone knows of better methods?

Edit your comments.tpl.php file and delete the <?php print render($content['links']) ?>

Then all you gotta do is create your own reply, edit, and delete links

reply is /comment/reply/[nid]/[cid]
edit is /comment/[cid]/edit
delete is /comment/[cid]/delete

So use PHP to load the nid and cid and replace the [tokens] with your PHP code.

Then use PHP if statement to check whether login (global) user is of role x, if true, you print the reply link.

For edit and delete links, you check if login (global) user uid is the same as comment author uid.


Styling different fields before/while rendering it using drupal_render I developed a custom module, in which I display tabs of different nodes. I render each nodes using the below piece of code,

$node = node_load($myNodeId);
$view = node_view($node, 'full');
$rendered = drupal_render($view);
print_r($rendered);

Is there a way in which I can access and style the individual elements in the $node, so that my $rendered contains the HTML that has the fields styled as per my wish.

Also a greedy thought, does drupal allow a call back function to be registered while rendering fields? so that my function takes care of rendering my fields of interest.

Yes, assuming I understand correctly that you would like the nodes presented in these tabs to be styled differently to nodes presented normally on the site then I would recommend the first thing you do is set up a separate "view mode" (ie. like "Full content" or "teaser") for this purpose. You can set set up new view mode using hook_entity_info_alter(), Entity view modes or Display Suite. For more information see this tutorial.

Once you have your new view mode in place, you should be able to replace the word "full" in your snippet with the machine name of the view mode. Then you will be able to do some themeing just by changing the formatter settings for your fields in your node type's display settings.

Their are many options for further overriding the themeing of the fields, you could for instance add the following code:

/**
 * Implements hook_preprocess_field().
 */
function MYTHEME_preprocess_field(&$vars) {
  $vars['theme_hook_suggestions'][] = 'field__' . $vars['element']['#field_name'] . '__' . $vars['element']['#bundle'] . '__' . $vars['element']['#view_mode'];
}

...to your theme. This will allow you to create a theme function called something like MYTHEME_field__FIELDNAME__NODETYPE__VIEWMODE() (replace the uppercase words with whatever's relevant in your case).  This will override the funcion theme_field() and you will be able to customise as much as you like.


How to hide node/add and */edit page titles Need to change Drupal 8 node/add page titles - there have been some answers here (most for Drupal 7), but none of them have worked.

So there is always Create  in front of the title in add page - need to drop the part Create - how ?

Need to drop also word Edit  in from the already created node in edit mode - how ?

If someone can point me in right direction and give me _preprocess_node_add_list or some node preprocess sample.

Regards

Virgo

Try with hook_preprocess_page_title

function myModule_preprocess_page_title(&$variables) {
  //- Get the Current route name
  $route_name = \Drupal::routeMatch()->getRouteName();
  switch ($route_name) {
    //- Add node Page
    case 'node.add' :
      $variables['title'] = t('New add page title');
      break;
    //- Edit node Page
    case 'entity.node.edit_form' :
      $variables['title'] = t('test');
      break;
  }
}


Omega theme, global css and the lack of grid at global.css It seems that I misunderstood one major feature of the Omega theme. From what I see, the mobile-first basic css file  - global.css - ignores the grid layout altogether and stacks elements one over another. Am I correct, or am I missing something? Does that mean that all the zones and regions will be rendered in a top-down manner with no width control?

I feel that my question is quite vague; I'd be most grateful links towards some relevant documentation and how-tos regarding the pure global.css design. I feel that most of the docs concentrate on structure of the zones& regions, while there's little sugestions as to how to make global.css work good by itself.
Thanks for your attention

Omega is designed as a mobile-first, breakpoint responsive theme.

global.css is the mobile first sheet, so the grid system doesn't apply.  The grid kicks in with the mytheme-alpha-default.css.

The answer for What's the difference between global.css and default.css files in Omega theme? goes into detail about the stylesheet convention.  In summary:

  How does my site need to look on mobile?  Make global.css
  How do things change when the grid system kicks in?  Make mytheme-alpha-default.css
  How does my site look when I am viewing it in portrait mode on a tablet?  Make mytheme-alpha-narrow.css
  How do things change when I am on a normal desktop?  Make mytheme-alpha-normal.css
  How do things change when I am on a widescreen monitor?  Make mytheme-alpha-wide.css


Allow role to edit node with same taxonomy term I would like to allow a user to edit some node that have the same taxonomy term.

I created a taxonomy for enterprise and I referenced it in a field of user profile. I used this taxonomy in a content type too.

I wonder if it's possible to allow users to edit only nodes with the same taxonomy term, as in this example:

Users :

Alex - enterprise : AAA
Paul - enterprise : PPP

Nodes :

1 - enterprise : AAA
2 - enterprise : AAA
3 - enterprise : PPP

In this example:

Alex can edit node 1 and 2 only, and see all.
Paul can edit node 3 only, see all.

I tested taxonomy access control but I have to create a role for each enterprise to edit node with same term enterprise. But I have more than 100 enterprises.

A few year's back, I had to do this for a D7 site with 100s of content providers that could only post in specific areas.  Did this by have a protected section taxonomy field on the user profile.

Then used hook_node_access to test if the node had a term that matched on of them on the user profile.

That's the basics.

I think I had to do a custom validator for the node create form to check that they were creating nodes with approved terms.

I also think the node create form and edit forms had the term lists cut down to just allowed terms by using a view as the source of the selection list.

Sorry for being general, I haven't worked on that site for years and don't have the code anymore.


how to render create page form & list of contents in page.tpl.php I am theming an admin page & I require to load/render admin forms in page.tpl.php file. The final output should be somehow like the attached screenshot. Scroll below to see screenshot & code written in page.tpl.php.

Admin Page

  <?php print drupal_render(drupal_get_form('node_admin_content')); ?>

  <?php print drupal_render(drupal_get_form('page_node_form')); ?>

I was searching for this solution & I came across this "print drupal_render()". Please suggest best solution for this. I have render same kind of pages in other tpl.php files.

It is recommended to render the forms either in preprocess function or in the custom module. Example of rendering the form in preprocess function:

function MYTHEME_preprocess_page(&$variables) {
  // Assigning node_admin_content form to the variable.
  $node_admin_content = drupal_render(drupal_get_form('node_admin_content'));
  $variables['node_admin_content'] = $node_admin_content;

  // Assigning page_node_form form to the variable.
  $page_node_form = drupal_render(drupal_get_form('page_node_form'));
  $variables['page_node_form'] = $page_node_form;
}

Now to render this form in page.tpl.php:

Admin Page

  <?php print $node_admin_content; ?>

  <?php print $page_node_form; ?>


term_reference field is not created I set up the Services module as REST server, so I can create nodes with custom fields by REST client as in Services 3 - POST node.create with custom fields.

The settings of the Services module are the following.

Server => REST
Path to endpoint => "neoapi"
Session authentication => yes
Response formatters => json
Request parsing => application/json & application/x-www-form-urlencoded
Resource path => http://127.0.0.1/neoapi/node

Content type => mycontent
Term reference field => Autocomplete term widget (tagging)

And post next JSON data via Google Chrome Advanced Rest Client

{
"type":"mycontent",
"title":"The New Article",
"body":{
  "und":[ {
    "value":"This is the body of new article."
    } ] },
"field_neo_terms":{
  "und":[ {
    "tid":"3"
    } ] }
}

At REST client I receive "200. OK" NID and URI of new node. But in site i have new node with title and body, but without terms and error:

Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen()
(line 441 of C:\Program Files\VertrigoServ\www\includes\unicode.inc).
Warning: preg_match_all() expects parameter 2 to be string, array in   drupal_explode_tags()
(line 7254 of C:\Program Files\VertrigoServ\www\includes\common.inc).
Warning: array_unique() expects parameter 1 to be array, null given in drupal_explode_tags()
(line 7255 of C:\Program Files\VertrigoServ\www\includes\common.inc).
Warning: Invalid argument supplied for foreach() in drupal_explode_tags()
(line 7258 of C:\Program Files\VertrigoServ\www\includes\common.inc).

As the documentation you linked says, the structure for the fivestar field is the following.

{
  "field_fivestar":[{
    "rating":"100",
    "target":"0"
  }]
}

Probably you are missing "target"

Also, if you are using auto complete for taxonomy you should use the term id, tid, 3 times:

{
  "field_termins":[{
    "tid":{
      "tid":"[tid:26686]"
    }
   }]
}

Auto complete is the tricky part.


How do i verify users passwords from the hash in the database without drupal core logic I oversee a proprietary CMS with a headless Drupal back-end. We use Drupal to authenticate users, manage permissions and roles, and store HTML for almost 13, 000 pages. As our needs have grown, our custom code base has expanded, and Drupal's role in the project has diminished. Most of the app logic is now handled by a Node.js Express server. The Express app has access to the Drupal database and is already performing some read operations on Drupal tables.

I'd like to start migrating some features off of Drupal and onto the custom app. The one I'm most concerned about is authentication.

Authorization is currently setup as follows. User visits a non-Drupal app landing page. Submits username and password to the Express app, the app uses Drupal's rest login to check for a successful logon. If successful, the app uses standard Express practices to create a session and hand out a cookie.

I'm hoping that the express app can start checking passwords in the database directly, instead of using the Drupal API. I'd prefer that my users not have to reset their passwords and I'd prefer not to disrupt some relationships i have built with the Drupal user tables.  In summary, my questions are these:

How can i check that the hashed password in the DB matches the password submit by the user?
Is the salt value in the settings.php file the one used encrypt passwords in the database or is that salt value somewhere else?

2a. NEW QUESTION: According to the Drupal Docs an unique salt is generated for every user and store in the database, possibly concatenated with the hashed password. Where are these unique salts stored and if they are concatenated with the hashed password, how can I separate them from the salted password?  Are the salts concatenated on the end of the hashed password or the beginning.  Are they always the same length?  What is that length?

What algorithm or module does Drupal use in combination with the salt value to created hashed passwords?
If find the algorithm and salt values is it likely that this system is portable to node.js or are there php or Drupal idiosyncrasies that would prevent a migration.

Thank you in advance for you consideration. I realize it's a little tacky to ask questions about moving off of Drupal, but I'm still a big fan of the platform and the community. It's been very good for our operation.

Tony

A long time ago, I had to move from one system to another and there was a similar concern about migrating hashed passwords. I set up things to check for a password in the new system. If one exists, authenticate against it. If not authenticate against the old system, as it seems you're already doing with Drupal. However, instead of just handing out the cookie, use the opportunity to store whatever was sent in the new system, or physically take the user to a "verify your password" in the new system, and get it saved properly there.


How to add noindex / nofollow robot metatags to Views subpages I have a big view with lots of filters, and Google and friends are killing one of my sites after a cache clear.

How could I add noindex and nofollow metatags in this views' subpages header? I would like to keep the views main page free of these tags.  As I understand the Metatag module is not yet up to the task.

Another idea just came to my mind: Adding nofollow to Views sorting links would achieve nearly the same.

I inquired and no such feature will happen in Views http://drupal.org/node/1758354

Altering robots.txt could be an option. For example this would stop google from accessing your pager.

    # Disallow all URL variables except for page
    Disallow: /*?page=*&*
    Disallow: /*?page=0*

More examples on Views and SEO can be found here.


How should I alter forms shown in a block? I want to alter the login form to display only the @username and @password inputs.

Is it mandatory to write another module to overwrite the user module? Can it be done from  my PHP block by using these 2 variables? If yes, how can I find the name of the variables?
What is the Drupal recommended way for doing this?

There are two ways to display only some fields:

Get the original form, and remove unneeded fields. This can be done 2 ways, in hook_form_alter() or by calling drupal_get_form() and working on outputted array. This way is risky - save handler might be unable to save if some fields it expects are missing.
Create your own form, with your own inputs, validators and save handlers. Copy strings from form you are copying to keep using any translations already available. This is safer, but requires a bit more work.

In theory you can handle form in a block with php filter. I would not recommend it. It's way more manageable to keep code in files. And if you have APC, it's also way faster. Thus, modules are the way to go.


Remove cck field from nodes body I have defined a cck field but I don't want it to be printed out in posts body.

I print body in this way:

<?php print $node->body; ?>

but cck filed still exists. I want to use value of that field for some other purpose.

any ideas?

If you look at the Display Fields in CCK, eg www.yourhost.com/admin/content/node-type/NODETYPE/display, you can exclude fields from the $content variable that is passed to the node template.  I'd look into that and use $content instead of $node->body if it isn't excluded from there as well.


Creating a slideshow with images and text overlays Does anyone know of a module or method to create a node where users can upload an image, add text on top of it through a WYSIWYG, then have the image combined with the text (merge the text and image into one jpg/png)?

We are trying to find a way for users in a school to add slides to our digital signage without using powerpoint, and I was wondering if there was a Drupal module that could do the job or help make it easier.

I don't believe that there's a module that supports the dynamic placing of text on top of an image in a wysiwyg editor. However, you should be able to use the imagecache_actions module to superimpose a text field onto an image field; IOW, you'd need to have separate fields (or a field collection) for the image and text. It also supports custom actions which should allow you to exploit the imageapi and GD as per your requirements.


How to resolve the "undefined variable" notce when I put a flag on a Views page? I want to place a flag link on a page, as suggested on that page: https://www.drupal.org/node/295383

The flag will subscribe the user to the most recent content page, which is done in Views.

I have the Flags: subscribe (by current user) Relationship.

I have installed Views PHP and I want to add to the header of the view a Global:PHP with the code <?php print flag_create_link('subscribe', $node->nid); ?>

Unfortunately I receive an error:

  Notice: Undefined variable: node in __lambda_func() (line 1 of .../sites/all/modules/views_php/plugins/views/views_php_handler_area.inc(39) : runtime-created function).
  Notice: Trying to get property of non-object in __lambda_func() (line 1 of .../sites/all/modules/views_php/plugins/views/views_php_handler_area.inc(39) : runtime-created function).

What could be the reason for that?

Any help appreciated.

The error arises because there is no $node variable defined in the scope.
Try looking inside the $results variable; something like this should work:

<?php print flag_create_link('subscribe', $results[0]->nid); ?>

This will print a subscribe link for the first row of the view.
Also, you have to ensure that the nid is present in your result object. It should be already there, but if not, add the "Content: Nid" field and hide it by checking the "Exclude from display" option.


How to set in my own module dependency on a composer package? I have some of my own modules written on Drupal 7 that use composer packages. These composer packages are downloaded with the module Composer Manager.

How can I set explicitly the dependency on a composer package on my own module?

Should I describe it somehow on my module's .info-file or should I do it via a hook?

It's because if I don't do it, the Composer Manager can remove these packages from the site on the next updating. Unfortunately, I couldn't find any example.

You can add dependencies in your module.

Navigate to your module's root folder. Run composer init. When you get to the question Would you like to define your dependencies (require) interactively, say yes. You can then declare any composer libraries your module depends on.

You can also manually create a composer.json file that looks something like this:

{
    "name": "uniquenamespace/packagename",
    "description": "This module does some stuff",
    "type": "drupal-module",
    "authors": [
        {
            "name": "Some Guy",
            "homepage": "https://www.example.com/some_guy",
            "role": "Maintainer"
        }
    ],
    "require": {
        "somevendor/somepackage": "^1.9"
    },
    "license": "GPL-2.0-or-later"
}

Run composer validate to check that your composer.json file is valid.


After submission of a webform block how to replace that webform block with thank you message in the same page? I have created a webform block and assigned to a page in the right sidebar. After successful submission of that block, I want the thank you message with the values submitted in the webform to displayed where block was there before in the same page.

I have given no-redirect option in the form settings of the webform.

Also in the block settings  of the webform block given view mode as form only.

But how would I replace the webform block with thank you message on successful submission of webform in the same page? Is there any Drupal way to achieve this. Have I missed any settings ??

Any help will be much appreciated.Thanks in advance.

If you have the webform set as a block, you can go to admin > structure > block. Look for your webform block. It should be named something like Webform: 'name of webform node'. Click on the configure link to the right. When the edit form for the block loads, look for the section Confirmation message. Select the option Display the confirmation page in the block on the same page (no redirect). Now when you submit the form from the block, it will redirect back to it and show the confirmation message on reload.

You may need to fill out a message in the webform settings. I have attached an image of the edit block page for you to compare.


Limit the number of nodes created from anonymous users I am in the process of finishing the development of a small appointment scheduling system, just using node creation as an appointment. Anonymous users can thus make appointments via a node creation form.
In order to slightly limit the ease of spamming from a malicious person, I would have liked to know if it was possible to limit the number of nodes created by an anonymous user. I am well aware that it is not very effective security, but the objective is simply to limit the damage.
I found an extremely close answer to my question on Limit amount of content creation per anonymous user.
/**
 * Implements hook_node_access
 */
function MY_MODULE_node_access($node, $op, $account) {

    // Get node type, can be string or node object
    $type = is_string($node) ? $node : $node->type;
    if ($type == 'type_of_interest') {
      // Check flood limit for anon users node creation
      if ($op == 'create' && user_is_anonymous()) {
        // Ensure checked only once per page request, node/add path only
        $access_checked = &drupal_static(__FUNCTION__);
        if(empty($access_checked) && arg(0) == 'node' && arg(1) == 'add') {
          // Record the access check for drupal_static
          $access_checked = TRUE;
          // Check create_node limit of 2 per 12 hours
          // Note, you could make the threshold and window config variables.
          if(!flood_is_allowed('create_node', 2, 43200)){
            drupal_set_message(t('There is a node creation limit of 2 nodes per 12 hours. Please try again later.'), 'error');
            return NODE_ACCESS_DENY;
          }else{
            // Register the node create event to test against for 48 hours
            // Note, you could move this somewhere else to ensure the node is actually saved, e.g hook_node_insert
            flood_register_event('create_node', 172800);
          }
        }
      }
    }

  return NODE_ACCESS_IGNORE;

}

Unfortunately, this is a code block for Drupal 7.
Would the code be similar for Drupal 8?
I am not very used to programming with Drupal 8.

Drupal 8 invokes a specific hook when an entity is created: hook_entity_create_access(). Apart that, Drupal 8 code has been converted to a more OOP code, and it uses methods where before it used functions.
The following code is the one I would use for Drupal 8.
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;

/**
 * Implements hook_ENTITY_TYPE_create_access().
 */
function mymodule_node_create_access(AccountInterface $account, array $context, $entity_bundle) {
  $flood = \Drupal::flood();
  if ($entity_bundle == 'type_of_interest' && $account->isAnonymous()) {
    if (!$flood->isAllowed('create_node', 2, 43200)) {
      return AccessResult::forbidden('There is a node creation limit of 2 nodes per 12 hours.');
    }
    $flood->register('create_node', 43200);
  }
  return AccessResult::neutral();
}


how to make a search form I would like to make a search form for my site so that users can use a series of drop down menus and click to search and it will create a view with listings that fit the criteria of the search.

Its for a property/real-estate website so I want the user to be able to select how many bedrooms, price range, and location. Then, they will get a list or properties that are in the location  selected with the number of bedrooms specified etc.  I  spent a while searching and all I could find is how to customize a single Drupal search field in the header.

You add some filter criteria, and expose them to the users who see the view. The filter criteria can be any of the filter criteria implemented by the Views module, but there is one that you are probably interested to add it for a search view: Search: Search Terms.

You could also add a filter for selecting the user who posted the node, and the date when the node was posted.

At the end, the view page would appear similar to the following one.


Show/Hide fields not working for Condition Fields on node display I have Conditional fields installed, with a checkbox as the dependency which shows two textareas when checked. The issue is when viewing the content type, the checkbox is NOT checked and the text areas still show up. I have checked in Manage Dependencies and the dependants are required and visible when checkbox field is checked.

Is there another place to adjust these settings, if so where would I look?

This is a quirk of the module, per the documentation on the view context:

  The "Value", "Filled" and "Empty" conditions are special: they are the
  only conditions that have ANY effect on form validation and content
  view.

If you want to show/hide fields with the module during content display, you'll need to set the Condition to Value and the according value for your checkbox.


Download all files attached on a site I have researched a little bit and I haven't found a sound solution to downloading all attached files from all content types across an entire site in an single action. I have found a couple modules like Backup & Migrate, or its plugin Backup & Migrate Files that perform similar functions, but nothing to effect that I need. I am trying to archive all attached files for a schools site. The site is drupal7.

If you want the entire files directory of uploaded files, you can do this with Drush:

drush rsync @source.target:%files/ @destination.target:%files

See: https://drushcommands.com/drush-8x/core/core-rsync/

This relies on having %files defined in your path-alias part of your alias definitions for drush.

Alternatively, you could ssh into the server, and tar/gzip the files directory, then scp it down to your machine (or sftp/ftp, I suppose).

Either of these methods will bring the entire files directory with it, which will have all uploaded files, any image derivatives (generated image style files) as well as cached css/js files. If you use the drush command with arguments, you can exclude directories you don't want.


Implement sticky footer for acquia_marina I've searched for a Drupal-friendly sticky footer solution for the Acquia Marina theme for Drupal 7, but I couldn't find anything.

2 examples are given here for Drupal 6: http://drupal.org/node/554048. The first solution is JavaScript-based and the second is CSS-based.

Will the CSS/JS examples given work for Drupal 7? If not, can anyone suggest a simple solution to get the footer to stick to the bottom of the browser window?

My site is running drupal-7.10, fusion-7.x-1.x-dev and acquia_marina-7.x-1.x-dev.

The CSS solution should be implemented the same way in Drupal 7.

Here is the javascript code updated to Drupal 7.

(function ($) {
Drupal.behaviors.acquia_marinaStickyFooter = {
  attach: function (context, settings) {
    var footer_height = $('#footer').height();
    var footer_pos = $('#footer').position();
    var window_height = $(window).height();
    var page_height = $('#page').height();
    var page_pos = $('#page').position();
    var page_total = page_pos.top + page_height;
    var footer_new_pos = window_height - footer_height - page_total;
    var test = footer_height + page_total;
    if (test <= window_height) {
      if (footer_pos.top < window_height) {
        $('#footer').css('position', 'relative');
        $('#footer').css('margin-top', footer_new_pos);
      }
    }
  }
};
})(jQuery);


How to send email to multiple recipients using drupal_mail? I am using drupal_mail to send email,

$to = 'email@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

I want to send email to multiple email addresses at once. Should I be doing this?

$to  = array('one@email.com', 'two@email.com', 'three@email.com',);
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

The to-parameter to drupal_mail is a string, not an array.  But you can have as many receipent as you like in the the e-mails "to" string, provided they're separated by commas.

So to send the same mail to multiple recipients, do the following:

$to  = 'one@email.com,two@email.com,three@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

Se also API documentation for drupal_mail


Help needed with hook_node_submit in custom module to save data I require some help in my custom module, specifically getting the value of a form element added via ajax in hook_node_submit.

First I'll explain the basic module setup needs:

You have created a content type called 'content'.
You have created a sample taxonomy vocabulary and added some sample terms to it.
In the content type you add a term reference field with the name 'field_terms' for the newly created vocabulary and allow unlimited values (checkboxes).

Now you enable the module and create new content of type 'content'.

Once you select 2 taxonomy terms, a select list appears with the 2 or more selected terms in it, allowing the user to select one of the above selected terms once more (to define a main term from the selected terms - if that makes any sense)

So, in terms of the module I have written this:

1) I use the function hook_form_alter() and apply it to only $form_id == 'content_node_form' (content type = 'content').

2) In hook_form_alter() I apply '#ajax' to each checkbox for the field_term checkboxes and create a blank container where the select list will be placed after the callback.

3) I have written the function _custom_callback() which gets the selected checkbox term_ids and term_names from the field_terms to create the select list options. It then outputs the select list if 2 or more options have been selected

4) Implement hook_node_submit() to grab the data from the $form_state and move it into the node object (this is where the first errors occur)

5) Implement hook_node_load() to load the values when editing the page

6) Impmeneted hook_node_insert(), hook_node_update() and hook_node_delete() to do the db stuff.

But when I submit the form I receive the following errors - due to hook_node_submit:

I am unsure how to call my object in the node. My form is called

$form['container']['main_taxonomy_term']

So I presumed this would be correct:

/**
 * Implements hook_node_submit().
 */
function select_main_taxonomy_term_node_submit($node, $form, &$form_state) {

  $value = $form_state['values'];
  // Move the new data into the node object.
  $node->main_taxonomy_term['tid'] = $value['main_taxonomy_term'];
}

I have looked and tried but I just can not find any clues how to get the data from $form_state and into the node object.

Please find attached the module. maybe someone can help me out as this is driving me insane.

Here is the module:

http://www.megaupload.com/?d=181H4B5F

Many thanks in advance.

So now I can answer my own question:

In my module I had $form['container'] defined in the hook_form_alter(), but the actual field $form['container']['main_taxonomy_term'] wasn't defined yet as I was adding it in my callback, so naturally Drupal didn't know about the field when rendering the form.

I restructured the module, moved the $form['container']['main_taxonomy_term'] = array(...) into the hook_form_alter(), created a new function to get the select options, calling upon it in various circumstances, added some extra checks for the edit node form as the options had to be built from the database values upon first display, but after that use $form_state else it wouldn't refresh the list upon editing the checkbox selection...

Oh well, so i finally managed to get it working without error message.

Maybe this is helpful for anyone, or maybe it isn't at all.


Upload Images to specific folders how do I upload images (Media) to specific folders inside the default directory? I will have thousands of pictures and would like to have an organized structure of folders.

Thanks a lot.

You can use File (Field) Paths module. It allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

You can use value of any node field as folder name where files will be uploaded. Or you can create new field for this purpose.