How to set files public directory programmatically? I have standalone script for adding some files to Drupal nodes. It is in main Drupal directory. It is multisite enviromnent. I know how to choose database and I am sure that I am choosing proper database, but my files lands in sites/default/files but I want them in sites/domain/files. I am getting public files path by

drupal_realpath('public://')

It returns sites/default/files.

All other things are correct and file data lands in proper database.

I checked site (admin/config/media/file-system) that database I am using and this path is set to site/domain/files...

Is there any chance to set public path programmatically? So file_copy will use proper path.

EDIT

The reason that I am asking is that my hooks: hook_file_presave doesn't invoke and I am thinking that is because public path problem. (All required module are enabled)

In single site env script works ok.

Probably the only solution is to create module, but it strange it isn't works.
I wanted to stay away from creating modules for long running task because it's take longer and Batch API is slower that good old CLI. All my previous scripts worked with multisites.

You can set that variable like so:

variable_set('file_public_path', 'sites/domain/files');

Hopefully someone else will be able to tell you why this problem is happening, I have no such issue in any of my multisite installations.


Deployment for staging and production I need to make the deployment easy between my staging and production servers.

How can I do this? I need to deploy all the changes, so if I pull from Github and run the script, the changes are applied!

Has anyone written any script or module for this?

I am using Drupal 7.

You should look into drush, drush deploy and especially features.  Not all Drupal configuration options are supported by features, and you will need to do some work to create a deployment process that works for you.  There is no single script that will do everything correctly for you.


How do I programmatically translate a string? I am working on one custom module to alter the fields labels of user login form for visitors. I created a module to alter the labels in the user login form. The French language is enabled on the setup.
I am trying to translate the field labels on the user login form to French. I am using the following approach in a module.
I have included the namespace with use Drupal\Core\StringTranslation.
After that, I have debugged the $form variable inside hook_form_alter().
From this debugged variable, I am trying to translate the filed label 'E-mail' to French.
function hook_form_alter ({here goes all the parameters of alter hooks}){
  $form['name']['#title'] = t('E-mail');
}

I am not able to see the translated Email field label on the user login form.
Am I missing anything? What should I do to translate the strings using hook_form_alter()?

you have find and add your translation string here : admin/config/regional/translate


Extract data from Field Collection using db_select() I'd like to use db_select() to extract values from a field collection attached to the user profile, to help speed up some complex Ajax forms (rather than loading the entire field collection, using standard entity queries, etc, etc).

Assuming I have the following:

Field Collection: field_my_address
Field 1: field_street_number (integer field)
Field 2: field_street_name (text field)
Field 3: field_city (taxonomy term reference field)

How would I go about doing this?

I got it to work like this:

$pid = $profile->pid;

$query = db_query('SELECT nn.field_street_number_value AS number,
                          ss.field_field_street_name_value AS street,
                          cc.field_city_tid AS city,
         FROM field_data_field_my_address AS aa
         LEFT JOIN field_data_field_street_number AS nn ON aa.field_my_address_value = nn.entity_id
         LEFT JOIN field_data_field_street_name AS ss ON aa.field_my_address_value = ss.entity_id
         LEFT JOIN field_data_field_city AS cc ON aa.field_my_address_value = cc.entity_id
         WHERE aa.entity_id = '.$pid);

$records = $query->fetchAll();


hook_init() causes login problems I created a custom module which has the following hook_init() implementation.

function gate_init() {
  $curr_uri = check_plain(request_uri());
  if (strpos($curr_uri, 'admin') === FALSE) {
    if (strcmp($curr_uri, '/gate') != 0) {
      if (!sess_read(GATE_SESSION_NAME)) {
        if (!isset($_COOKIE[GATE_COOKIE_NAME])) {
          drupal_goto('gate');
        }
        else {
          sess_write(GATE_SESSION_NAME, TRUE);
        }
      }
    }
    else {
      if (sess_read(GATE_SESSION_NAME) || isset($_COOKIE[GATE_COOKIE_NAME])) {
        if (!sess_read(GATE_SESSION_NAME)) {
          sess_write(GATE_SESSION_NAME, TRUE);
        }
        drupal_goto('/');
      }
    }
  }
}

It's crazy, but this code causes login problems for authenticated users. I cannot login, I see no errors, I just cannot login if I provide correct username and password.

If I comment out these lines, I can login.

if (!sess_read(GATE_SESSION_NAME)) {
  if (!isset($_COOKIE[GATE_COOKIE_NAME])) {
    drupal_goto('gate');
  }
  else {
    sess_write(GATE_SESSION_NAME, TRUE);
  }
}

I check further and  if (!sess_read(GATE_SESSION_NAME)) is the part causing login problems.   Could anybody give me an advice?

sess_read() should not be used in a module, as that function is passed to session_set_save_handler() from _drupal_bootstrap(), which is the function that is called during Drupal bootstrap.
The purpose of the function is not to read values from the PHP session; if you need to do that, the you can just read the content from $_SESSION[].
To notice that session_start() is called from Drupal during its bootstrap; that means that after a full bootstrap (or any bootstrap that goes past the DRUPAL_BOOTSTRAP_SESSION phase) a session is initialized, and $_SESSION[] can be used.


Views attachments and filters I've created a view from geocoded nodes which shows nodes on a map.
I've also created an attachment view which I've attached to this map view.
This is to have a listing under the map view to make items more accessible.

However, I can't get that to work properly e.g. filter properly.
The following describes filters on the map view:

Content: Geocodes (field_geocodes) - proximity (exposed)
Content: Date(Exposed Popup date) | Setting
Content: EventType (exposed)
Content: Type (= Event)
Content: Published (Yes)

On the attachment view I checked that it inherits contextual filters and filters. However,

I'm no aware that is it inheriting filter values e.g. that I need to
create those filter again in this view?
Or does inherit whole filtering as is?

Anyhow, attachment results won't filter and shows all from first published node or by changing view settings it won't show anything i.e. filters and there's no results.

if Inherit exposed filters and Inherit contextual filters in Attachment settings is set to Yes then it will inherit filters and it's values


Is there a way to have a language neutral link that automatically redirects to the user's active language? We have a multilingual Drupal 7 site, and after turning on the first translation, we realized that one of the third party modules we're using, a slider module (comes with Eventus theme, it's a module the vendor built (or perhaps bought and extended/branded)). The slider module is not multilingual aware and it is routing all users to the same URL (which sends them back to the default language), regardless of the active language.

We're evaluating our options to address this, and one idea (that I am unsure if it is possible) is to make the slider links go to a "language neutral" URL, which will then forward them on to the user's currently active language for any given URL. However, so far I haven't been able to figure out A) if this is possible and B) if it is possible, how to construct the URL. So, is it possible, and if so, how would I set this up? Open to suggestions.

The slider module's content is currently identical for all language versions of the site.

To try and clarify, I'm going to use example the following example URLs:

/about -- this is the default, primary language (english) version of the "about" page
/pt-br/sobre -- this is the translated, Português version of the "about"

The first "slide" in the slider says "Learn more about us!" and links to the /about.

Our goal is to make Drupal aware of the user's current language setting, and if they click on a link that sends them to /about, but their language is currently set to Português, it will automatically redirect them (or at least provide them) with the Português version of the "about" page.

Is this possible, and/or is there a better way to accomplish this?

I'm not familiar with the "slider" module. But from the example URLs you added, it seems to me that at least you should check your configuration at Configuration -> Languages -> detection and selection: the order specified there should be 'URL, Default, User', and not something like 'Default, URL, User'. It could well be that that is all that's needed here ...

Curious to hear what the result of checking this will be ...


apachesolr filters do not work I have installed apachesolr module and built the index for it. now i can search normally but when i filter the result using any enabled filter, the result DOES'T change and i get the same result of searching for the key. for example i searched for business and then filtered the result using taxonomy tid:36 and i got the same result before filtering!!
I have var_dump the $query that has been generated at line 215 in apachesolr_search.module and part of the result is shown below

object(Solr_Base_Query)#17 (13) {
  ["id"]=>
  int(1)
  ["fields":protected]=>
  array(0) {
  }
  ["fields_added":protected]=>
  array(0) {
  }
  ["fields_removed":protected]=>
  array(0) {
  }
  ["filterstring":protected]=>
  string(6) "tid:36"
  ["field_map":protected]=>
  array(0) {
  }
  ["subqueries":protected]=>
  array(0) {
  }
  ["keys":protected]=>
  string(8) "business"
  ["base_path":protected]=>
  string(24) "search/apachesolr_search"
  ["solr":protected]=>
  object(Drupal_Apache_Solr_Service)#16 (20) {....

also the filter doesn't appear in CURRENT SEARCH block. the block still showing

CURRENT SEARCH
Search found 38 items

(-) business

Also I have made a var_dump for params array that has been generated in function apachesolr_search_execute in apachesolr_search.module at line 212 and the result was:

array(13) {
  ["fl"]=>
  string(71) "id,nid,title,comment_count,type,created,changed,score,path,url,uid,name"
  ["rows"]=>
  int(10)
  ["facet"]=>
  string(4) "true"
  ["facet.mincount"]=>
  int(1)
  ["facet.sort"]=>
  string(4) "true"
  ["hl"]=>
  NULL
  ["hl.fragsize"]=>
  NULL
  ["hl.simple.pre"]=>
  NULL
  ["hl.simple.post"]=>
  NULL
  ["hl.snippets"]=>
  NULL
  ["hl.fl"]=>
  NULL
  ["spellcheck.q"]=>
  string(8) "business"
  ["spellcheck"]=>
  string(4) "true"
}

nothing for fq=tid:36
any idea of what i might be missing? or how to fix it?
Thanks for your help

You should consider using Search API module, which can handle Solr and facets, and enables you to use Views to create the search page and has a very good UI for creating search index with facets ect.

I've used it several times and have been pleased with the result.


Computed value on multipage Webform I have multipage webform. I want to compute the value of the component (Hidden -type) which is on the second page based on the data submitted on the first page.

I'm using hook_form_alter and added my client_submit handler:

function mymodule_client_submit(&$form, &$form_state)

I can read there submitted data from the first page and I can do the calculation. But I cannot set the value of the component from the second page. I can see the structure of the form in $form or $form_state parameter. But I do not know how to set the value of the component from the second page as it was not submitted yet.

I can suggest you a simple way to do this. You can pass the calculated value stored in a variable to the next form function.

Like I had two step form & at first step of the form user select some name from given name(checkboxes), I store them in array & pass them to the next form function like --

function MYMODULE_form($names)//Use your module name instead of MYMODULE.
{
  $return_form = drupal_get_form('MYMODULE_get_form', $names);
  return drupal_render($return_form);
}
function MYMODULE_get_form($form, &$form_state, $names)
{
  $form = array();
  $i = 0;
  foreach($names as $name)
  {
    $form['item']['name'.$i] = array(
      '#type' => 'markup',
      '#value' => $name,
    );
    $i++;
  }
}

Try something like this, if it solves your problem. Use simple variable if you don't have multiple values.


How to speed up event confirmation email? I recently setup a Drupal 8 instance to set up a special event website. I am allowing users to build inline contacts to register for an RNG event. Everything seems to be working: The users offer their email and username, and the contact is created; then, they register for the event and the registration is created. Twelve hours later, they get an email message setup using the Courier and Rules integration with RNG.

Is there a way to speed up the confirmation email?  If I send an email from a user contact form on the same website, it sends it immediately. I imagine it is a Courier/Rules issue with how often the email queue is being processed, but I cannot figure out where that is configured.

Courier message dispatch is all done in cron. Therefore, in order to speed up the delivery of messages, you should run cron as often as possible.

Personally I run it every 30 seconds, but every 1-5 minutes should be fine in most cases.

Disclaimer: I am the maintainer of both the RNG and the Courier modules.


EntityFieldQuery fieldCondition I have the following code:

$query = new EntityFieldQuery();

$result = $query
    ->entityCondition('entity_type', 'field_collection_item', '=')
    ->propertyCondition('field_name', 'field_version', '=')
    ->fieldCondition('field_version', 'entity_id', '105', '=')
    ->execute()
;

The first two conditions are fine, but the fieldCondition() is causing the following SQL exception:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_version0.field_version_entity_id' in 'where clause'...

The problem seems to be that 'field_version' is prepended to the column 'entity_id'.  I have looked inside _field_sql_storage_query_field_conditions() and there appears to be no way to stop it from prepending this. This is the table I am trying to perform the fieldCondition on:

+-------------+---------------+---------+-----------+-------------+----------+-------+---------------------+
| entity_type | bundle        | deleted | entity_id | revision_id | language | delta | field_version_value |
+-------------+---------------+---------+-----------+-------------+----------+-------+---------------------+
| node        | shopping_cart |       0 |       105 |         123 | und      | 0     |                   5 |
| node        | shopping_cart |       0 |       108 |         126 | und      | 0     |                   8 |
+-------------+---------------+---------+-----------+-------------+----------+-------+---------------------+

How may I perform this query correctly?

entity_id is the entity ID of the entity the field is attached to; in this case, the ID of your field collection item. To add a condition on that, you need to use a propertyCondition() on the "field_collection_item" primary key.


What happens if you leave out an `access callback` specification? In a custom module, if you have a menu hook item that has a custom access argument, but don't specify an access callback, what is drupal's default behavior? Does it use user_access? In other words, is an access callback necessary to specify?

Yes it uses user_access() by default, but only when you specify 'access arguments'. See http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/7.


How to change color and sidebar menu without using themes We have a number of different themes on our website as we have different departments with different color styles. However, the only thing that changes are the colors of the sidebar and which menu is displayed on the sidebar; the layout of these pages remain the same almost exclusively. It seems as though having 16 different themes, which we do, is unnecessary if these are the only things changing (sidebar color and menu).

Are there any good modules which could achieve this functionality (changing color and menu depending on department) without having all these different themes? Or are themes the only/best way to go to achieve this functionality? Also is having this many themes the average or is that a lot?

There are 16 different departments so 16 different colors are needed. Create one theme for all of them. In your .css file create 16 classes and in each one set a custom background color. Like this

.dp—i{ background-color:#abcdef !important}

Now using preprocess functions, and based on the department add the css class to the page component. If it is a block use preprocess_block, if it is region use preprocess_region. By checking the department and adding approprite css class to the class array it will work


When should I use Apache Solr instead of Drupal core search? I'm in the process of migrating a medium-sized on-line magazine to Drupal.

I do not know much of Drupal's internal search engine capabilities, but I'm aware of the Apache Solr Search Integration module, which integrates the java-based search engine from Apache. Unfortunately, Solr is something new to me too.

So my questions are:

When should I use Apache Solr instead of the Drupal core search? In what type of websites core functionality is not enough? Should I care about the performance gains of using Solr if my visitors only do hundreds of searches per day?
Will learning how to use and integrate Apache Solr cost me lots of weeks/months?

Learning and integrating solr could take no more than a couple days. There is ton of documentation on the API and a wealth of resources on Drupal.org.

Your use case sounds like a great candidate. Here are three good reasons I would use it on a particular site.

You have a significant amount of searches being made from the site and limited server resources, Solr will increase efficiency.
You need specific search control beyond core, core search really is just search content inside of nodes, It will ignore block, pane, etc. content. (There are other options that dont require non-php based environments).
Search is a major part of your site. It is common that users are finding content through google and other major search engines so search is not as important as it once was. However, some sites encourage or even require the user to search the content of the site. For anything like this, I would suggest solr, in addition to the other listed items, SOLR offers more control and search power (facets and related content) and less limitations.


Can a student gradebook be created without a custom module? I'm confused about when I need to build a module.  I'm using Drupal 8.  If I create a content type of a student, class, grades and so on, can that be done without a custom module?  Can it be done solely with content type and views?

I think no. You need content type and views as you write. I think that you also need to use taxonomy (for year and class) so you can assign students to years and class. For calculation you need to write some module, maybe you can do also that in view.

Try the Computed field module.

  Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!


Exposed filters and taxonomy. How to make a redirect to a term page when exposed form submit? Let's say there are 2 vocabularies:

Sizes (S, M, L, XL)
Colors (Red, Green, Yellow)

pathauto sizes: /size/s, /size/m, ... pathauto colors: /color/red, /color/green, ...

There is a catalog - taxonomy/term/% view with the following filters:

Size
Color

If we use a filter, then the url will be like this - ?field_size_tid=2&field_color_tid=3 It's normal, when several fields are selected in the filter

But when one field is selected in the filter, the url will be like -
?field_color_tid=2 But in fact the ?field_color_tid=2 = /color/green

How to make an redirect to /color/green instead of ?field_color_tid=2 in this case after exposed form submit?

Here is the code that should work for your use case. Create a custom module and replace YOUR_CUSTOM_MODULE part:

function YOUR_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    // Exclude cases when query contains 'field_color_tid'.
    if (strpos($_SERVER['QUERY_STRING'],'field_color_tid') === FALSE) {
      // Act only if query string contains 'field_size_tid'
      if (strpos($_SERVER['QUERY_STRING'],'field_size_tid') !== FALSE) {
        $selected_tid = $form_state['view']->exposed_input['field_size_tid'];
        // Check if such taxonomy term exists.
        $term = taxonomy_term_load($selected_tid);
        if (!empty($term)) {
          // Redirect to taxonomy page.
          $path_alias = drupal_get_path_alias('taxonomy/term/'.$selected_tid);
          drupal_goto($path_alias);
        }
      }
    }
  }
}


JavaScript loading order I've installed eu-cookie-compliance module in few projects and everywhere it worked as expected but in one project I have problems with loading JavaScript in correct order.
Even if I implement hook_js_alter and set higher weights, eu-compliance JavaScript is loaded before misc/drupal.js and misc/jquery.js. Is there any better way to reorder this JavaScript?

You could always change the group it's in:

function MYMODULE_js_alter(&$js) {
  $js['path/to/eu-cookie-compliance.js']['group'] = JS_DEFAULT;
}

Drupal's misc JS, jQuery etc, should all be in JS_SYSTEM, which has a lower weighting than JS_DEFAULT. There's also JS_THEME which has a height weighting than JS_DEFAULT.

The drupal_add_js() docs discuss the whole JS weighting thing in much greater detail.


How can I setup Git/Drush dl/make caching of Drupal projects? I'd like to setup the ability to have Drupal projects cached locally when I do a Git clone or Drush dl/make, so that if I happen to be offline or just to save bandwidth, when I Git clone/Drush dl/make a project that has previously been downloaded it will pull from the cache instead of from D.o., possibly after pinging D.o to see if there is a newer version (if online).

I'm sure I saw something about this once before, but haven't been able to track down the specifics.

There is a blog post about locally cached git repositories here: http://randyfay.com/node/93


How to use the Rules module to unset all flags (set x days ago) without using Rules Scheduler This is a follow-up to my question "How to use the Rules module to unset all flags (set x days ago) when cron runs?".

Case: users set flags on content using Flag module (flags are per user, not global).

Requirement: after a period of time (= x days) the system should automatically unset these flags using Rules module.

Limitation: the Rules Scheduler module cannot be used (for a solution using Rules Scheduler module please see the question linked to above).

Create a page and use whatever content type you want for it, eg. "Article". And assign a path to that page also, e.g. on \admin\dummypage. It doesn't matter what the content of that page is.

Then create a rule (using Rules) and enable the Path Rules module also. With this combination you can trigger a rule when the page \admin\dummypage is visited.

The rule can do (= perform a Rules Action) what you want to do. Built a view and with the help of VBO you can apply the changes you want. See therefore the video mention in the next answer.

Then you have to make sure that the page is visited. You can do this by either of following ways:

Put a reminder in your calender that includes the URL of your special page, and click on the page.
Use a websites like http://www.montastic.com/ (they will retrieve this page regularly).
Schedule a cron job. In this cron job you do a wget statement to retrieve the page and send it to null.


The link generated by a View's header (Global: Text area) is only visible for the admin role and I need it to show for other roles I have the following code in the View's header (Global: Text area).

<?php
  global $user;
  if (user_access('create page content', $user)) {
    $output = l(t('Publica un artículo nuevo'), 'node/add/articulo');
    print $output;
  }
?>

If I log in as admin I can add an "articulo" by clicking on the link that the PHP generates in the header of the view. However if I log in as a different role I can still add an "articulo" by using the navigation menu but for some reason the link generated by the code above disappears i.e. the link is only visible for the admin role and I want it to be visible for other roles as well. I have tried changing the permissions for the different roles but it has not worked. If the other roles can create content from the navigation menu why does this link disappear for them. Do I need to change something within the view or ...?

Thanks in advance.

As per your code , you need to make sure two things...

Logged in User should have create page content access in permissions since your code checks for that permission
Logged in User should also have access to create articulo content "node/add/articulo" since l function checks for user access of the  path he is trying to access.

Make sure logged in user role have both permissions in your permissions list. Clear cache and rebuild permissions before verifying.

In your case , Make sure the different role you are mentioning has "create page content" permission.


Hide Certain Values from an Apache Solr Facet I have some Apache Solr facet blocks i'd like to filter certain values from. For example if a facet contains the values:

Filter by letter:
 - a (6)
 - b (4)
 - c (2)

I want to hide the facet "c" so visitors won't be able to use it as a filter. Is it possible? i'm ok with editing/creating modules and also it would be okay a solution that uses CSS to hide the row from view (which was my first thought but then i realized there isn't a unique identifier for facet values)

I kept looking for a solution on the internet after posting this question and i have discovered this module:  https://www.drupal.org/project/facetapi_bonus which does exactly what i need


How to show nodes with a flexible grid? For a website I need to show nodes with a flexible grid. There will be several rows (no specific number) and each row can contain:

1 full width image
2 50% width images
1 50% width image (left/right) and 1 50% width text block
1 full width text block

The administrator should be able to change the order of these blocks easily. I'm planning to do this with the Field Collection module, I think with this I can get this to work. But i was wondering, is there a better way to do this?

Here are two examples of what the node could look like, but ofcourse there are hundreds of different options.

You could try Paragraphs which is an alternative to Field Collection.


Memcache do cache_pages? I have disabled Cache pages for anonymous users from Drupal admin admin/config/development/performance.

I have set my site to point on 2 domains such as www.ex1.com and www.ex2.com. One domain is for german language and one is for English. All is working fine on my localhost where there is no memcache. But on my live server front page is getting cached.

In settings.php I have settings like below:

$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_default_class'] = 'MemCacheDrupal';

// The 'cache_form' bin must be assigned to non-volatile storage.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

// Don't bootstrap the database when serving pages from the cache.
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

$conf['memcache_servers'] = array('memcached:11211' => 'default');
$conf['memcache_bins'] = array( 'cache' => 'default',
        // Any bin that goes to 'none' will fall through to database caching.
        'cache_form' => 'none', );

Do this can help like adding below line ?

$conf['memcache_bins'] = array('cache' => 'default',
                                 'cache_page' => 'pages',
                                 'cache_block' => 'blocks');

setting pages cache to point cache_page.

Please suggest. That will be great if someone can explain that how we stop cache_pages when we are using memcache.

UPDATE: Its happening with only view Titles ie: titles get cache if I visit one domain first and then second. It shows title language from first domain into second domain.

Thanks!

This is what you need.

// Turn off page cache
drupal_page_is_cacheable(FALSE);
// Set memcache prefix to be different for each hostname.
$conf['memcache_key_prefix'] = $_SERVER['HTTP_HOST'];


Change the default language of a node Given that I have a node in English as default language and Danish as a translation, is it possible to set the Danish translation as default language for the node?

Of course.

I would do it this way:

1) Install of module devel.
Drupal7

2) go to drupal/devel/php
Of course.

Drupal8

in the textarea add:

  //please, change the nid of your node

use Drupal\node\Entity\Node;

$nid = 1;
$node = Node::load($nid);
$node->get('langcode')->value = 'da';
$node->save();

In Drupal7

$nid=1;
$node=node_load($nid);
$node->language='da';
node_save($node);


Contextual links for nodes displayed via views When you create a node or a block you get a contextual link icon in top right of the item when hovering and etc. It is easy to edit content like that and etc.

When you create a view page and display multiple nodes via it, there are no contextual links hovering on those items and the only way to edit those is via Content.

I.e. I have a Panels page. It has a node at the top area of the page and it has that hovering icon for contextual links and it is easy to edit that node while viewing this panels page.

And then at the bottom area there's is a view which shows some grid-listed nodes too and none of those nodes has access to contextual links.

So is this possible somehow to add contextual links to nodes shown via Views?

Solved it myself.

Steps:

Enable Global: Contextual Links and Content: Edit Link fields
Exclude Content: Edit Link from display
In Global: Contextual Links settings, select the Content: Edit Link

However this works correctly and fine only while in preview mode, when watching the actual page in action the links nor the cog icon does not appear. As I understand this is some kind of a bug.

To fix that, you need to add additional CSS to your theme, which is (in my case):

.views-field-contextual-links {
  position: relative;
}

And now everything works fine, every element has it's own drop down cog/link.


How do I redirect a node to a path followed by a wildcard? I have a basic page node that contains two views in block form. The views both contain contextual filters captured from the URL. How to I publish my node to allow the user to visit /report/2002, or /report/2004, or /report/2010. The blocks are configured to display on /report/*. How do I do the same for a node?

Do I need to make my own controller with custom routing?

A view with a page display instead of the block display would generate the route automatically.


hook_field_attach_presave not saving - user profile field EDIT: As per a suggestion below, I tried using hook_field_presave, but couldn't access any parameters of the field. I then tried hook_field_attach_presave, but my alterations aren't being saved. My current module code is :

function module_field_attach_presave($entity_type, $entity) {
  $field = $entity->field_user_location;
  $locality = $field['und'][0]['locality'];
  $locality = ucwords(strtolower($locality));
  dpm($locality);
  }

The transformation is present when Locality prints out via dpm, but the transformation is not saved to the field itself. Any idea why?

ORIGINAL: I'm using an AddressField field in my user profiles, but I'd like to make sure that the cities that users enter are correctly capitalized. How can I do this?

I'm assuming it's some implementation of str_replace, but I don't know what to do with it.

You'll need to implement hook_field_presave(). You can find out from the parameters passed in if it's being invoked for an address field saved to a user account and do the necessary transformation on the 'locality' of the address field value in the $items array.


Create a renderable array for checkbox I want to inject a checkbox within a preprocess function and I think it should be a renderable array.

What is the structure of a renderable array for a checkbox?

Update:

I use profile2 module and have created profile checkbox fields. While viewing profile currently the field are show as just text. I want to show it as disabled checkbox with state. So it is not within a form.

Assuming that your render array is part of a form (outside of which a checkbox doesn't make a whole lot of sense), you would do it like this:

$form['checkbox'] = array(
  '#type' => 'checkbox',
  '#title' => 'Title',
  '#default_value' => 1, // Checked by default
);

Have a look at the checkbox type documentation for all of the available properties.

EDIT

Just to add that render($form['checkbox']); also works perfectly outside of the form context using the above code; the correct checkbox element is rendered, but without the "name" and "id" attributes.


How to get different image styles in the same view? I'am a newbie, and I want to make a simple view with an image field (in article nodes), that looks like this layout :

And for this, I don't want to use CSS rules to resize the view rows images, for two reasons :

I am using bootstrap grid, and I don't want to deal with relative heights, since images in articles have various sizes, so I prefer that this view do the image resizing for me.
I want to learn this view trick without relaying on CSS tricks.

I tried different tricks, like:

importing the image filed twice, making each one in different image style, rewriting them (displaying them conditionaly) based on "view result counter", but putting a condion like {% if counter == 1 %} or like {% if counter == '1' %} don't work (i think it still an open issue).
I tried also making some theme preprocess or theme hook altering to force a different image style for the first iteration.

I'm so frustrated because of such an easy task that looks so hard to me.

Any help?

The Twig Tweak can help you.

Firstly, you should write a specific condition for check if the image is first.

{% if loop.index == 1 %}

Inside condition you need to fetch an uri to the image and apply the Image Style Filter.


uppercase form textfield I want to have a form textfield automatically uppercase the text entered as it is typed in.  I was hoping that there was as set-able property that would allow for this but I’m unable to find one.

  $form['elementName'] = array(
            '#type' => 'textfield',
            '#title' => $this->t('Address'),...
  )

The searches I have done so far point to the use of  ‘Plugins.’  However if there is a simple(er) solution I prefer that.  Any ideas appreciated;

However if there is a simple(er) solution I prefer that.

Sorry, maybe I going too deep, but the most simpler solution that you can use just for display is a CSS solution.

Based in your example:

input[name='elementName'] {
  text-transform: uppercase;
}

That's it, any char will be uppercase in your textfield. If need store in uppercase, just change case before save.


How can I give option tags of a select tag ids or classes in Drupal 7? I was able to add classes to option tags in a select statement in Drupal 6 using a very convoluted method. I was hoping that there would be a better way in Drupal 7. Does anyone know how to add classes to option tags in select tags?

You cannot give class or an id to options directly through form api. you can however, theme select element to add classes to select options.

   // theme_select
function THEME_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));
  return '<select' . drupal_attributes($element['#attributes']) . '>' . THEME_form_select_options($element) . '</select>';
}

/**
 *
 * @param type $element
 * @param type $choices
 * @return string
 */
function THEME_form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    $choices = $element['#options'];
  }
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    if (is_array($choice)) {
      $options .= '<optgroup label="' . $key . '">';
      $options .= THEME_form_select_options($element, $choice);
      $options .= '</optgroup>';
    }
    elseif (is_object($choice)) {
      $options .= THEME_form_select_options($element, $choice->option);
    }
    else {
      $key = (string) $key;
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
      $options .= '<option class="' . drupal_clean_css_identifier($key) . '"  value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
    }
  }
  return $options;
}

Similar question is answered here


Using Simple jQuery click() events in Drupal 7 I've been able to get jQuery to load and work for some basic things such as:

(function ($) {
  console.log('jquery called');

  $(document).click(function() {
    var h1 = $('h1').text();
    console.log(h1);
  });
}(jQuery));

However, when I try to do the following, nothing happens.

(function ($) {
  $("h1").click(function() {
    alert('clicked!');
  });
}(jQuery));

I'm wondering if this has something to do with when the .js file gets called. I suspect that the document element already exists, so having a click event on it is no problem. However, I think that the h1 elements don't exist by the time the click event is loaded. I've tried the .bind() and .on() functions as well, with no luck.

Any ideas?

I call my .js file from my theme's info file, not sure if that matters.

(function ($) {
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.ss2 = {
  attach: function(context, settings) {

  $("h1").click(function() {
    alert('clicked!');
  });
}}

})(jQuery);

be careful with braces at the end, and rename ss2 as you want, it's just for example...


Text formats all look the same? I am using the CKeditor and IMCE modules.

When in edit mode, I can see the following text formats in the dropdown menu under the body text area:

Filtered HTML
Full HTML
Plain text
PHP code

I am logged in as an admin, selecting different text formats from the dropdown menu does not change anything on the page. For example, selecting Plain text, doesn't remove the icons at the top of the text area. What am I doing wrong/missing?

Selecting the PHP code option however does change the appearence of the text area in a sense that the icons disappear.

This is expected behavior.

The "Text Format" Select List affects the way drupal parses and displays the data after it has been saved and is being displayed to the end user; not the way it is saved nor the way it is displayed on the Node Edit form.

By default:

Given Input:

Title

  <?php echo 'bar'; ?>

"PHP Code" filter output

Title

  bar

"Full HTML" filter output

Title

"Filtered HTML" filter output

Title


Filter a view based on an attribute of a user? I'm building a Drupal 7 site with a content type for events, and a view that displays a calendar of upcoming events. Events can be at one of two locations, and each user is also associated with one of the two locations. I'd like to set the calendar up so that the user only sees events for their location.

I tried doing this by creating a custom field on user profiles for location. However, I can't figure out how to use that field to filter the events on the calendar. It doesn't show up as an available value for contextual filters. Is there a way to do this?

Another option would be to make user location into a role, and then use role permissions to show the user one of two location-specific calendars. But this doesn't seem like what roles were really intended for.

Could I get some advice on an efficient way to do this? Events and user accounts are created by an administrator, and users don't need to be able to edit their location.

Finally found an answer, described in detail here. Confusingly, it starts with creating a view for displaying users. Use a contextual filter to limit it to the currently logged-in user. You can then create a relationship to bring in information about the custom user field, and a second relationship to find nodes that share the value from that field. I tried this and it worked for me!

A more straightforward method is described a few comments earlier, but I haven't tried that one.


Is it possible to have custom, default fields added to all new product types In Commerce 2? I have multiple custom fields that will need to be on all new product types (Commerce 2). The fields are already created on the 'default' product type. But new product types do not inherit the custom fields.

Is there a way to have custom fields automatically added to all new product types?

Nothing that just works.

You could define them as a base field through code by defining them in hook_entity_base_field_info(), so for example how scheduler module does that. Then they will be non-configurable fields that are always there. If they're not multiple, they will even be added to the product base tables.

Those kind of fields are a bit tricky to uninstall.

The other option is implementing a hook_commerce_product_type_insert() and then copy the configurable fields you want from the default type and add them to that new bundle as well.


Delete Drupal login capability In our environment, we make changes to a drupal site that are then replicated to an outside webserver. We do not want people to be able to log into the drupal site from the outside. I want to remove whatever file /user and /admin resolves to but I can't find any information on this. In wordpress, you delete the wp-admin folder. Is there anything like this with Drupal? Turning off the "Allow login" setting will not work for us.

Note- We cannot make any changes that are saved in the database. Changing Drupal settings will not work. There's got to be a login file on the server we can delete.

Just have an htaccess entry that redirects /user and /admin to the front page.


Date selection with price - without commerce I need a option to let users set up dates and price when creating node with unlimited number of entries.

For example:

"from: 15/01/2015 to 20/02/2015 - Price = 50 USD"

from: 21/02/2015 to 15/03/2015 - Price = 70 USD

from: 16/03/2015 to 15/05/2015 - Price = 90 USD

It would be nice if could look user friendly too since users will make atleast 7-8 entries.

Something like "from: __________ to __________ : price __________"

Instead of underline it should be date popup and for price i would use integer.

You can accomplish this with the Field Collection module and Date module.

Navigate to manage fields under your node type
Create a new field with field type of Field collection
Set the number of values to unlimited under the field you created in step 2
Navigate to /admin/structure/field-collections and select Manage Fields under the field collection you just created in step 2.
Select Manage Fields
Add From Date Field
Add To Date Field
Add Price Field


Custom node template based on field condition Is it possible at all to create a node template file based on a specific field value?

For example I already have a node template file called "node--video.tpl.php" for nodes of content type video. I would now like to add a checkbox field in that content type.

If the box is unchecked then it will use the above template.

If the box is checked then it will use a different template.

UPDATE: I added the following to my template file as Mohammed suggested, but I am not getting the changes.

function motg_preprocess_node(&$vars) {

$node = $vars['node'];
  if($node->field_solo[0]['value'] == 1)
  {
       $vars['theme_hook_suggestion'] = 'node__solo';
  } else
  {
       $vars['theme_hook_suggestion'] = 'node__video';
  }
}

My field "field_solo" is correctly outputting a value of 0 or 1 also.

You can actually do that in the preprocess node function something like this:

function THEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  if($node->field_solo[0]['value'] == 1)
  {
       $vars['theme_hook_suggestions'][] = 'node__theme1';
  } else
  {
       $vars['theme_hook_suggestions'][] = 'node__theme2';
  }

}

Here if the condition is true then the node template would be node--theme1.tpl.php

and if the condition is false then the tpl would be node--theme2.tpl.php.


How to check progress of sql-sync that hangs up? I run:

drush sql-sync @mysite.es.remote @mysite.es.local

then I hit Yes to continue then command completely hangs up for ever. Meanwhile I checked phpMyAdmin and it seems that it's synced my local database with remote but it's still missing some tables.

Is there any way how to check progress of sql-sync?

Run with --verbose or --debug to see more and lots of output, respectively, or run with --simulate to see only the commands that Drush would run.

Another helpful thing to do with sql-sync is to run drush @mysite.es.remote sql-conf and drush @mysite.es.local sql-conf - this will print out the database records sql-sync will use for the two sites.  In your case, since you are getting to the y/n prompt, this part is probably working.


Can Display Suite be used for "Show: Fields" as well as "Show: Content" to be able to rewrite field output? I need to be able to adjust field output in view results but also want to make use of Display Suite for layout.

However, it would appear that Display Suite is only available for "Show: Content" and not "Show: Fields" View Display Format and therefore the facility to rewrite output is not available.

Definition and comparison of "Show: Content" vs "Show: Fields"

In Views, what is the difference between "Show Fields" and "Show Content" under Format?

The answer is: no. But there is an alternative solution.

No - (At the time of writing), Display Suite does not appear to have functionality  for laying out fields in a view result row for “Show: Fields” format.

For laying out views row results, using display suite is only available for Views outputting the full node (i.e. Show: Content) as a row. The layout is done in the manage display section of the content type, defining a view mode for use in outputting the node in the view.

The solution therefore for laying out fields ( “Show: Fields” format ) and so making available the standard view functionality to modify each field's output behaviour for the view row result would be:

use the views_fieldsets module to group fields in parent div containers as required
use css to layout these parent divs and their children as required. for example, see: How to place Text and an Image next to each other in HTML?
access each field's settings as usual in the Views Edit Display, to customise the field's output e.g. rewrite it.


Making menu items active on desired page I am creating a custom module for menus through which we can allow individual menu link to be active on desired path/paths. The module interface provides similar functionality as block module's visibility configuration.

I am using hook_translated_menu_link() to implement the visibility functionality. As I have referred menu item visibility module for this, but not getting the desired output. Do i need to implement any other hook for this or I am missing out something. As I have implemented hook_form_id_form_alter() for the interface and mymodule_submit() for form submit functionality and right now trying out hook_translated_menu_link() for visibility functionality.  I also have a database entry for my module.

Is there a way you could make the Context module a dependency for your module and hook into the Context module to do this?  Context already allows you to do this exact function.  You specify conditions and reactions when those conditions are met, per context.  In your case you would specify particular paths as conditions, and then your reaction would be to simply activate a particular menu item.  I would seriously consider checking it out rather than reinventing the wheel.


How do I turn a select list into a radio button? I have a list text field that I want to display as a series of radio buttons instead of a select (dropdown) list.  In Drupal 7, I could change this on Manage fields.  How can I do that in Drupal 8?

step 1 : choose the field type is  "list(text)".

step 2 : change the "Allowed number of values" as limited in Field settings

step 3 : change the "field widget" as Check boxes/radio buttons in Manage form display


Expand sub-menus on hover in a menu block I need to show menus expanded in the sidebar. I used the menu blocks to show the submenus. But now the problems is when I hover on the parent menu initially it is not showing the submenus which was appearing before.
And also submenus is expanded only when click the parent menu which then lists all the submenus with expanded.

Please tell me how to show the submenus on hover in menu blocks when the submenus are not expanded

You can use this module Nice Menus. Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)

  Three styles/types of menus are currently possible: horizontal, menus drop down; vertical, menus fly to the left; vertical, menus fly to the right. There is a handbook page that provides a list of sites that use Nice menus.


Change display format of date in token I am using the token for the quiz close date ([node:quiz:quiz-close] in a certificate for the quiz module and would like to change the format. I looked at Date & Time in the configuration settings and have already defined a custom one that is just the date (called just_the_date).

How can I embed a token for a field that records a more detailed date, but just have it show in my custom format or change the display format for this field?

Turns out I just needed to take the token, [node:quiz:quiz-close] and append it with the custom date format machine name :just_the_date] to get [node:quiz:quiz-close:just_the_date]. Also, it's in the list of tokens, once you expand the date item further.


Show if there are 'new' comments on a view of terms? I have comments on nodes that are categorised by terms. I need to show a view of the terms and if there are any new comments in any of the nodes that term is tagged with.

So if I have the following:

Term1
-NodeA (has new comments)
-NodeB (has new comments)
Term2
-NodeC (no new comments)
-NodeD (no new comments)
Term3
-NodeE (no new comments)
-NodeF (has new comments)
Term4

I need my view to look like this:

Term1 – new comments!
Term2
Term3 – new comments!
Term4

First I tried making a view of comments to include the new comments field and using relationships to show the terms. However if a term has no nodes or comments (Term4 in my example) I need the term to still be displayed.

So I then tried making a view of the terms. I added the relationships 'Taxonomy term: Content with term' and the field 'Content: New comments' which uses this relationship. This does show the number of new comments as expected. It gives me duplicated results (which I may be able to fix with grouping fields) but unexpectedly it also hides the terms that have no comments or nodes.

Am I going about this the right way and if so how can I stop the 'empty' terms being hidden?

UPDATE Ive updated D core and a few modules that had new versions (but not views). The view works fine with the relationship of 'Configure Relationship: Taxonomy term: Content with term' when the field is 'Content: Title (Title)'. However when I add the field 'Content: New comments' then terms that have no comments are hidden.

UPDATE Ive tried the following in a views field:

if(intval($data->node_new_comments) > 0) {
  if(!array_key_exists($data->tid, $static)) {
    print "new comments !";
    $static[$data->tid] = 1;
  }
} else {
  print "here you do whatever you want when there's no new comment";
}

UPDATE - by 'new comments' I mean comments that the logged in user hasnt read. This is a standard field in views. I need this rather than an arbitrary date cut off. Sorry for any confusion.

This works for me. I have a term view that shows the term name field and my code adds the new comment flag after the term name.

The code goes in a custom module.

You need to change to VIEW_NAME to your view name and the TAXONOMY_FIELD_NAME to the name of your field (like field_tags for example).

/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  global $user;
  if ($view->name == 'VIEW_NAME' && $user->uid) {
    // Get all the tids of the views results.
    $tids = array();
    foreach ($view->result as $result) {
      $tids[] = $result->tid;
    }

    // Get all the tids that have recent comments.
    // Only return terms that relate to nodes that have not been viewed by
    // the current user since the last comment.
    $query = db_query("SELECT t.TAXONOMY_FIELD_NAME_tid
                         FROM {node_comment_statistics} c
              LEFT OUTER JOIN {history} h ON c.nid = h.nid AND h.uid = :uid
                   INNER JOIN {field_data_TAXONOMY_FIELD_NAME} t ON t.entity_id = c.nid
                        WHERE c.comment_count > 0
                          AND t.TAXONOMY_FIELD_NAME_tid IN (:tids)
                          AND (h.timestamp IS NULL OR h.timestamp < c.last_comment_timestamp)",
               array(':uid' => $user->uid, ':tids' => $tids));
    $commented_terms = $query->fetchCol();

    // Loop through the results and add the new comments flag where necessary.
    foreach ($view->result as &$result) {
      if (in_array($result->tid, $commented_terms)) {
        $result->taxonomy_term_data_name .= ' new comments!';
      }
    }
  }
}


How to loop through a dynamic taxonomy vocabulary and if term is chosen, do an action? My problem is as follows:

I have a taxonomy vocabulary with terms, which are changing from time to time.
I have two node types --> type 1 and type 2
Type 1  has a taxonomy term reference field
Type 2 has an entity reference field which can be prepopulated with the module "entity reference prepopulate"

If I create a new node of node type type 1 then a rule should check which terms are selected and create a new node of type 2 for each selected term automatically.

The entity reference field of the new type 2 node should be prepopulated with a reference back to the original type 1 node.

Because the terms of the vocabulary are changing, the check up by the rule should be IMHO dynamic.

Dummy-Code:

If a new node of node type 1 is saved,then check which taxonomy terms are selected.

for each selected term:

create a new node of type 2
and prepopulate the entity reference field of node type 2 with the value of node type 1.

I tried it with the Conditional Rules module, but there seems no for..each control loop available.

How can I solve my problem?

If a new node of node type 1 is saved,

= Rules Event: After saving content, of type "type 1".

  then check which taxonomy terms are selected.

= Rules Action: Create a Rules loop, which iterates over each of the selected taxonomy terms, assume you use a name for each list item like "selected_term".

  for each selected term:

= Rules Action (which is part of the loop), in which you perform a "Rules Component", and which uses as parameter the "selected_term".

  create a new node of type 2

= 1st Rules Action performed as part of the Rules Component, which is to "Create an entity" (a node of "type 2").

  and prepopulate the entity reference field of node type 2 with the value of node type 1.

= 2nd Rules Action performed as part of the Rules Component, which is to "set a data value", for the entity reference field, as part of the entity (node) that got created in the previous Rules Action, and followed by a Rules Action to "save the entity".

Refer to the List and loops video for more details about processing lists and loops via Rules.

Note: no need for the Conditional Rules module ...


Wrap teasers in a div (simple taxonomy page, no views) I would like to know if there is a way to wrap the nodes teaser in a  without using jQuery.

Basically, this is how the DOM is :

        term description, others custom fields…

teaser content

teaser content

teaser content

What I want :

      term description, others custom fields…

teaser content

teaser content

teaser content

I'm using Display Suite for a better customization, I checked all the tpl files, but I found nothing…

Thx :)

Using template.php and hook_preprocess_page()

function THEMENAME_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $variables['page']['content']['system_main']['nodes']['#prefix'] = '
';
    $variables['page']['content']['system_main']['nodes']['#suffix'] = '
';
  }
}

So what this does is checks if the URLs match the condition /taxonomy/term/%term-id then if it's satisfied then it adds a prefix and a suffix that are to be rendered by <?php print render($page['content']); ?>.


Page Arguments Not Getting Passed My code was working perfectly, but at some point my hook_menu page arguments stopped getting passed.

I am using versioning and can revert back to the previous code, but the page arguments are still broken.

Is there some change that could be causing page arguments to not get passed?

Thanks a million!

Disclaimer:  Sorry, I am not a Drupal developer, so the code is an attempt at injecting plain php into a site.

Inventory.module

    function inventory_menu() {
  $items = array();

  $items['admin/commerce/inventory'] = array(
    'title' => 'Inventory',
    'description' => 'View inventory reports for your store.',
    'access arguments' => array('access commerce reports'), // Inherited by children.
    'page callback' => 'inventory_reports_dashboard',
    'page arguments' => array( '10', 'DESC', 'false', 'admin@sltwtr.com', 'false'),     // page_arguments = threshold amount,  sort direction, hide zero inventory, email report to, save_to_email bool, download_csv
    'file' => 'inventory.dashboard.inc',
    'weight' => 0,
  );

  $items['admin/commerce/inventory-download-csv'] = array(
    'page callback' => 'inventory_download_csv',
    'access arguments' => array('access commerce reports'),
    'file' => 'inventory.dashboard.inc',
    //'type' => MENU_CALLBACK,
  );

  return $items;
}

Inventory.dashboard.inc

/**
 * Renders the inventory reports.
 */
function inventory_reports_dashboard( $threshold='10', $sort_direction='DESC', $hide_zero_inventory='false', $email='admin@sltwtr.com', $save_to_email = 'false') {
  drupal_add_js(drupal_get_path('module', 'commerce_reports') . '/theme/js/dashboard.js', 'file');
  drupal_add_css(drupal_get_path('module', 'commerce_reports') . '/theme/css/commerce_reports_dashboard.css');

  // on first load we want to grab all of the default values
  // after first load, we want updated values to pass through
  //$threshold = 18;
  $render = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . "/sites/all/modules/inventory/inventory.php?threshold=$threshold&sort_direction=$sort_direction&hide_zero_inventory=$hide_zero_inventory&email=$email&save_to_email=$save_to_email");

  return $render;
}

function inventory_download_csv(){
  $file = './inventory.csv';
  $filename = 'inventory.csv';
  //drupal_set_header('Content-Type: text/csv');
  //drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
  drupal_add_http_header('Content-Type: text/csv');
  drupal_add_http_header('Content-Disposition: attachment; filename=' . $filename);
  if($file) {
    //file_transfer($file, array('Content-disposition', 'attachment; filename='.$filename));
    $csv_contents = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . "/sites/all/modules/inventory/inventory.csv");
  }
  else {
    return drupal_access_denied();
  }
  $fp = fopen('php://output', 'w');
  //$csv_text = array2csv($db_result);
  fputs($fp, $csv_contents);
  fclose($fp);
  exit();

}

Inventory.php

<?php

define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);

require_once DRUPAL_ROOT . '/sites/all/modules/myfunctionlib/myfunctionlib.module';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

//require_once DRUPAL_ROOT . '/includes/common.inc';
//require_once DRUPAL_ROOT . '/includes/module.inc';
//require_once DRUPAL_ROOT . '/includes/unicode.inc';
//require_once DRUPAL_ROOT . '/includes/file.inc';

//drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
clean_dump($_GET);

When I change the url:

mysite.gotpantheon.com/admin/commerce/inventory/12/DESC/false/admin@sltwtr.com

The get parameters no longer reflect changes

array(6) {
  ["threshold"]=>
  string(2) "10"
  ["sort_direction"]=>
  string(4) "DESC"
  ["hide_zero_inventory"]=>
  string(5) "false"
  ["email"]=>
  string(16) "admin@sltwtr.com"
  ["save_to_email"]=>
  string(5) "false"
  ["q"]=>
  string(0) ""
}

I would change your code to (as @J.Reynolds specified):

  $items['admin/commerce/inventory/%/%/%/%'] = array(
    'title' => 'Inventory',
    'description' => 'View inventory reports for your store.',
    'access arguments' => array('access commerce reports'), // Inherited by children.
    'page callback' => 'inventory_reports_dashboard',
    'page arguments' => array(3,4,5,6),     // page_arguments = threshold amount,  sort direction, hide zero inventory, email report to, save_to_email bool, download_csv
    'file' => 'inventory.dashboard.inc',
    'weight' => 0,
  );


Customize order of a list in Drupal 6 I have a list of links that are all displayed as one list.
They are currently sorted by 'Title' asc.

I would like to customize the order of this list.

How can I do that in Drupal 6.

Example:

A1
B1
C1

But I want instead to have (not sorted or organized in any specific order):

A1
C1
B1

This is my backend interface in Drupal 6:

Thank you for your help!
Izumi.

In your own custom module implement hook_views_pre_render and alter the view's result in the following manner:

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'my_view') {
    // for example reverse the result
    $view->result = array_reverse($view->result);
  }
}

Use devel module and namely the dpm function to test your code before and after. It is very handy.
Hope this helps.


How do I get name and label of fields in user profiles? I want to get the list of fields added to user profiles(listed here admin/config/people/accounts/fields). I need machine name and label of each field. How do I get them?

You can use the field_info_instances() function to get that data:

$fields = field_info_instances('user', 'user');

foreach ($fields as $field) {
  $machine_name = $field['field_name'];
  $label = $field['label'];
}


Adding Background image in Views template file How to add background in Drupal 8 views-view-fields.html.twig' files.

I try like this but it's don't work. Using views I just output image paht.

 <div class="cover-img" style="background:url('{{ field_image }}');">
    </div>

Thank you

Adding CSS background image hardcoded in the Twig (or TPL in D7 sites) isn't a best practice. You should do this via your theme's css file like style.css, or via a module (some theme's give you the opportunity to add it directly on your site).

I would suggest to restore any such changes in the Twig and redoing it in the css file.


How do I change store based on location? I need to have different prices for same products based on country. I was advised to use Price list module and to have different store per each country and I did that.
I.e. I have Swiss store and Serbian store.
For Swiss store for supported billing countries I selected only Switzerland and for Serbian store only Serbia.
Swiss is default one and prices in product variations are defined in CHF. Now I'm trying to override prices for Serbian store (in RSD).
So, I created Serbian price list and added alternative prices for products. Problem is that those alternative prices are used only if I include also Swiss store for that Serbian price list (so price list is active also for Swiss store). If I select only Serbian store, as it suppose to be, then price list is not used (I see default prices in CHF).
I read here: https://drupalcommerce.org/blog/42419/commerce-2x-stories-stores
.. that stores are actually representing billing locations. But that confuses me because product and their prices are displayed before customer enters billing address?!?
What I'm missing here? Why Serbian store is not automatically active if I'm testing from Serbia? Do I need some GEO IP module or something? Even when I'm testing as a logged user (location entered before) I still use default Swiss store instead of local Serbian store.

Configuring the stores is one thing, determining which one is used for any given page request is another. One store is configured to be your default, and absent any other code, that store will always be used for the current page request, influencing visible products, pricing, carts, etc. If you want to make the current store something other than the default, you have to write a store resolver.
An example module you can reference is the Commerce Store Domain module, which resolves the current store based on the current domain. You can do something similar using the GeoIP module. I'm not aware of any existing contrib that integrates that as of yet.


Drupal7, draggable menu reordering missing, weight dropdowns instead My client cannot see the draggable arrows next to menu items in the list view, while I can. I checked the cookies and it appears he is missing a cookie that I have in my browser:

  Drupal.tableDrag.showWeight

I'm not sure if this is relevant, but it looks quite promising.

We are both using Google Chrome 13.

Has anyone experienced this problem before, is there a way to force Drupal to regenerate the cookie?

Has your client accidentally clicked on "Show/hide row weights" in the top right corner of the menu list?


Retrieve field value using PHP + Search API + Views? I haven't had this problem in the past but I'm trying to retrieve a field value in a Views PHP Field for a view I made for Search API. I'm using the code below but I tried with 'nid' as well.

$stream = $data->_field_data['vid']['entity']->field_stream['und'][0]['value'];

You can see the var output here. I'm trying to get field_stream but am having no luck...

http://www.ovwrc.com/waste-search?search_api_views_fulltext=poop%20poop

Run $data though dmp to inspect the array and see what values are available.

Search Krumo may be useful as I expect that array will be huge!


How to make correct View for tasks for each user? I have taxonomy vocabulary with departments. Different users have task's nodes.

I need View like this:

Department1   Task5_ForUser10
Department2
Department3
Department4   Task7_ForUser10
Department5

I've created View with taxonomy terms, Relationship with task's node and with Contextual filter "User ID from logged in user", but I see now only short variant:

Department1   Task5_ForUser10
Department4   Task7_ForUser10

How can I get View with full department list and tasks for each user?

You can solve above problem using Views Field View module..

Project page says

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

Create a new view which accepts term id as argument and lists nodes related to that term
Add Contextual Filter Author ID - Provide default value
In your view add term id and select Exclude option
In your view add above view as a field and read term id using token in settings.

See the result below


Preventing a duplicate node from being created I'm building a site with a content type that includes a URI. Is there a module that would prevent a node of that content type being created if the URI it includes is already referenced in an existing node? i.e., so that the site can't have two nodes with the same URI field?

There is the Unique Field module that does this.


Drupal install in sub folder I am trying to install a drupal site that I built a while back. I put it in a sub folder for viewing purposes and am having trouble logging in. I got the site installed, the DB connected but when I go to myurl.com/sitename/user I get a 404 error. The site is in  maintenance mode so I can't get into the backend system. I know the site is partially working as when I go to myurl.com/sitename I get the maintenance page with all broken links. I did some searching and made sure my .htacces file was updated with this code:

RewriteBase /sitename
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

But still not working...
What else should I be doing here?
THanks

Make sure to configure your base url in your settings.php file and revert your .htaccess to the default from drupal.


How to understand Views SQL statement? I try to figure out the meaning of View's sql statement.

This following is Views auto-generate sql statement:

SELECT taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM
{taxonomy_term_data} taxonomy_term_data
LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_hierarchy ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
INNER JOIN {taxonomy_term_data} taxonomy_term_data_taxonomy_term_hierarchy ON taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE (( (taxonomy_vocabulary.machine_name IN  ('book_category')) ))

What's the meaning of {...}?, It seems a table name, I try to copy above sql to mysql, But mysql alert me:

SQL Syntax error.

So I try to remove {...}, Like this :

SELECT taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM
 taxonomy_term_data
LEFT JOIN  taxonomy_term_hierarchy ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
INNER JOIN taxonomy_term_data ON taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN  taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid

But Mysql alert me:

Not unique table/alias: 'taxonomy_term_data'

What's the problem of Views's SQL?

Only remove the curly brackets, not what's inside the them. The brackets contain the actual table name, and directly after is the table alias which is used later.

This should work (only brackets removed):

SELECT taxonomy_term_data.name AS taxonomy_term_data_name,
       taxonomy_term_data.vid AS taxonomy_term_data_vid,
       taxonomy_term_data.tid AS tid,
       taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM   taxonomy_term_data taxonomy_term_data
       LEFT JOIN taxonomy_term_hierarchy taxonomy_term_hierarchy
              ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
       INNER JOIN taxonomy_term_data taxonomy_term_data_taxonomy_term_hierarchy
               ON taxonomy_term_hierarchy.parent =
                  taxonomy_term_data_taxonomy_term_hierarchy.tid
       LEFT JOIN taxonomy_vocabulary taxonomy_vocabulary
              ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE  ((( taxonomy_vocabulary.machine_name IN ( 'book_category' ) )))

Note that if your tables has a prefix, i.e. drupal_ then you need to add that to the table name, because that's the reason the brackets are used, in case of table prefix.

Cheers,


Put a node submit form in a block In Drupal 7, I have defined a block called mycontenttype_block. I would like the output of the block to be the node submit form for an existing content type, like this:

function mymodule_block_view($delta = '')
{
    switch ($delta)
    {
        case 'mycontenttype_block':
            $block['subject'] = t('Mycontenttype submission form');
            $block['content'] .= $something;
            return $block;
            break;
    }
}

Where $something is the form output. I tried setting $something to drupal_get_form('mycontenttype_form) but I can't get any output...

Here in drupalsixlandia, I wanted to have this on a different page and did something along the lines of this to get it to work:

global $user;

module_load_include('inc','node','node.pages');
$type = 'TYPEOFNODE';
$node = array('uid' => $user->uid, 'name' => $user->name, 'type' => $type, 'language' => '');

return drupal_get_form($type .'_node_form', $node);

so perhaps D7 needs a similar $node argument as well.

ADDITION:  a quick look suggests D7 wants $node to be an object, not an array and does it by just doing:

$node = (object) array('uid' => $user->uid, ...

You might be able to grab its code directly and use it.  Looking back, I don't know why I just didn't grab this from node.pages.inc directly myself:

/**
 * Returns a node submission form.
 */
function node_add($type) {
  global $user;

  $types = node_type_get_types();
  $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => $type, 'language' => LANGUAGE_NONE);
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

  return $output;
}

Ah...here's why.  I didn't like the title, and I doubt you want that if you are stuffing this in a block :)


Programmatically get a list of all fields? How to retrieve a list of fields, similar to what is available at admin/reports/fields, but so that I can have them in an array that I can stuff in a select dropdown.

You should use field_info_fields(), which returns an array containing information about all the defined fields. Its output is similar to the following one.


'"media_edit_action" plugin does not exist' error when performing update I get the following error after a database update. It looks like it completes the update by displaying Completed 8 of 8 but it doesn't run the updates. Any help is appreciated.

  Failed: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "media_edit_action" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of /srv/bindings/ae21023ced6d43099409c0fbbeded25e/code/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

This is what the updates need to run.

System module

  Change plugin IDs of actions.
  Clear caches due to schema changes in core.entity.schema.yml.

Views module

  Update dependencies for moved bulk field plugin.
  Add additional settings to the entity link field and convert node_path usage to entity_link.
  Add placeholder settings to string or numeric filters.
  Fix cache max age for table displays.
  Include views data table provider in views dependencies.

I believe that action at some point became deprecated and was removed from the media_entity module.  However, the configuration lingered and is blocking Drupal update from completing successfully.

What worked for me was to go the the Admin > Configuration > Development > Configuration Synchronization > Updates Report (menu tab).

If you view the Full Report, then you can see that the config for the media_edit_action is still present.

Use the pulldown menu on the right to delete that config.

When you run update again, then it should complete successfully.

Hope this helps!


Programmatically adding and removing users to a user reference field? I would love to see some code samples for this task. I have found this example already http://www.midwesternmac.com/blogs/jeff-geerling/programmatically-adding-or, but it is unclear why that example uses node language for array key, and based on the comment the user removal could be better as well.

It should be pretty simple:

Load the node you are trying to modify using node_load().
Look for the user referencing field.
Modify the user referencing field.
Save the node using node_save().

I wrote those steps before looking at the example you linked, but after looking at it, it pretty much follows those steps. To answer your question regarding the language: The reason for that is that you are not supposed to hardcode the language key directly. If I am not mistaken, in Drupal 7 this key is something like 'und', but when you use a language on a node this key changes dynamically to something like 'es' or 'en'. If you hardcode the language key, then your code will be translation incompatible. Even if you don't use translation, it is still consider a good Drupal programming practice not to hardcode that language key ;)

If you follow the code that it is given in your link you will be fine.


Primary links background not visible by non-admins I have styled my primary links with a background and it all works out just fine. Except for when I log out, the background disappears.
So it looks like the anonymous user doesn't have permissions to see the background (which I would fine strange...)

Is this a known issue and if so, what can I do about this?

Did you use the correct classes? E.g. when you use the .logged-in class in your CSS, the style will not be used when not logged in.


Is there a downside of having too many features? I have worked on or seen different D7 projects in the past, with different strategies for features:

One feature per view, content type, etc, with a consistent naming pattern. The result is many features with small or medium size. This has been my personal preference in the past.

Examples:

mysite_ft_vw_articles, for an "articles" view.
mysite_ft_ct_event, for an "event" content type.
mysite_ft_tx_categories, for a "categories" taxonomy vocabulary.

Multiple elements grouped into the same feature, e.g. if they are related to a specific section of the site, a specific topic etc.

I am now in a new project where we have to pick the strategy we want to follow, and some team members prefer to have bigger features with more elements in them.

To me the only problem I can imagine with having too many features would be performance. Some operations in Drupal may get slower if more modules are enabled.

The main problem with less but bigger features would be git merge conflicts, and side effects of "drush fu" on unrelated functionality.

Question

Am I missing something?

How big could the performance or memory impact be for e.g. 300 enabled feature modules?

What other downsides would it have?

Is there a recommended way / best practice?

Related

When using features to manage deployment, should I break my functionality into many little features or one big feature?

This question is asking whether to have multiple features or one big feature. But the accepted answer still suggests to group a lot of things into one (e.g. all content types, all views, etc).

I am asking whether to have multiple features, or even more features.

Note: the sites where I did this so far had fewer content types and views, so if there was a performance impact it would have been smaller. Also I have not compared few or many features on the same project to see which is faster. This is a new employer, new team, new project, I want to do things the way I used to on other projects, but want to evaluate the pros and cons and have a good argument, before I force this on a team that used to work differently in the past.

I'll jump in with an answer, though I agree with others that there is probably no single correct way.

My experience with features is that large features become very difficult to manage. Even one-feature-to-rule-all isn't a great answer, though it obviously reduces the conflicts possible, though that helps, because of the management of all those individual elements becomes hard.

In the past I have attempted to keep one "feature-module" for each aspect-feature of the site - so for example one feature describing a content type, and the views using it, and the rules, etc. Sometimes this is essentially one page, sometimes more. I have also tried larger groupings - bad idea - but not so far smaller ones (one for the actual CT, another for the view, etc.

The aspect of 'too many modules' is real, though I have dealt with perfectly functional sites with >200 (non-features) modules active. A mitigation you could use is for the live system to run with the features modules disabled, because their effect should be in the database and so the code is not needed. I haven't tried this, though.

From this experience I think that the choice should be to keep the scope of each feature small and very, very well defined. Most of the time I have got into trouble it has resulted from some aspect of a feature that is on the border between several elements -- it should probably have been its own thing not lumped into other things.

So: smaller features with very well defined scope for each.


How to hide certain items in a term reference field? I have the taxonomy 'Types' with terms A, B and C. I've added a term reference field 'Type' to the users with the 'Types' vocabulary. Now, when people register, they can choose between A, B and C in the 'Type' field, but I'd like them only to be able to choose between A and B.

How can I hide the third option?

You can use the Entity reference module to achieve this goal.

Install Entity Reference module.
Create a view of terms, with a display type of Entity Referance, and your filters/conditions
Create a field of Entity Reference type.
In field settings: Choose its target type is Taxonomy Term.
In entity selection mode choose 'Views Filter by an entity referance view'. Choose the view you created above in 'View used to select entities'.
Now save it.


How do I add a list of members I have added users and want to display a list of members as a block in a space on Open Atrium. I have looked in menus and Open Atrium when trying to add content but cannot find anything that will allow me to do this?

Theres a widget called "OG members" that could help you.

When in a space, you have this button to personalize the display. Click it then you can add widget (the '+' button). In the new window, you can find widgets that you can add and configure as you need.
Theres one called 'OG Members' in the category called (I think) 'Panel panes'.
I think this widget is meant to display members of the space you visiting


Configuring views to display book pages as teasers, in the correct order I am trying to display book pages as teasers, on the book cover node.

I created a Views block and display it under the parent node.

Book relationship is added, and a contextual filter as well.
Correct book pages are displayed in the block, but the problem is in the ORDER (weight).

None of the following criteria options work:

(Book parent) Book: Weight (asc)
(Book parent) Book: Hierarchy (asc)
The two above combined

Book pages are always displayed in the same order, which is not the same as order of pages in that book.

What am I missing? Any ideas?

Thanks!

In the sort criteria use:

Book: Weight (asc)

If you take the weight of the parent then all childs will return the same value.

To avoid confusion a Views example to import is added at the bottom. It presumes that:

the top parent node is NOT of the type 'book'
all  child pages are of the type 'book', also sub-childs.

Do not forget to:

'create a new book' in Book outline for the top page (even if it is not of the type 'book')
enable the block 'View: Child page teasers', probably in the 'content' area.

You can try at admin/structure/views/import the example below on your site or with https://simplytest.me/project/views (after deploy enable the Views UI and Book module):

$view = new view();
$view->name = 'child_page_teasers';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Child page teasers';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Child page teasers';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Relationship: Book: Parent */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'book_parent';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Book: Weight */
$handler->display->display_options['sorts']['weight']['id'] = 'weight';
$handler->display->display_options['sorts']['weight']['table'] = 'book_menu_links';
$handler->display->display_options['sorts']['weight']['field'] = 'weight';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['nid']['specify_validation'] = TRUE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'book' => 'book',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');


Attach a view to a specific node I'm looking for a module that makes it possible to attach an existing view to a specific node. I've looked at eva, but it seems only to allow connecting a view to all entities of a specific content-type. I wrote my own module, that can do this, and it works, but I would like to use a module that is well tested and maintained. Does anyone have any suggestions?

* EDIT *

I have installed the views reference module and this seems to be what I want, but when I do print_r($content) in my node--type.tpl.php file, the only thing related to this field is the following:

[field_attached_view] => Array (
                        [und] => Array (
                            [0] => Array (
                               [view_id] => products_view:first_display
                               [arguments] => sample/all/jeans
                             )
                         )
                     )

I have managed to load and display the view by something like this:

  $view_id = $node->field_attached_view[$node->language][0]['view_id'];
  $parts = explode(':',$view_id);

  $args = explode('/',$node->field_attached_view[$node->language][0]['arguments']);
  $view = views_get_view($parts[0]);
  $view->set_display($parts[1]);
  $view->set_arguments($args);
  $view->execute();
  echo $view->render();

But, there must be a cleaner way of doing this?

Thanks in advance.

You can use the View reference module.

  Defines a field type View reference which creates a relationship to a Views display and allows the view to be displayed as the content of the field.


Make uploaded image thumbnail bigger I have file upload field in node edit form. After succesfull upload process (ahah by clicking Upload form button) I am getting thumbnail instead of file upload field. It's standard Drupal behaviour. I would like to know how to change size of image thumbnail generating by Drupal after ajax upload.

Could somebody give me any advice?

Here's want you need to do to modified the image field thumbnail thats display after you upload an image.

You will need to overwrite the imagefield_widget_preview theme function. You can drop this theme overwrite in the template.php file of your theme.

function THEMENANE_imagefield_widget_preview($item = NULL) {
  //By default this returns  theme('imagefield_admin_thumbnail', $item);
  //But If you're going to change it I would recommend replacing it with image-cache.
  //Also you should keep the imagefield-preview div.
  return '
' . theme('imagecache', 'your_custom_preset', $item['filepath'], $item['alt'], $item['title']) . '
';
}

This will replace the thumbnail images uploaded using image field.

Hope this helps.

Also remember, to use the name of the theme thats being used when editing. In-case you're using different themes.


How to display text next to image drupal view? I have created a view displaying unordered list of fields - image, Title, descriprion.

How do I get the title and description to display next to image, eg

 IMAGE | Title
         Description

The simplest solution to your problem is, on right side in views there is a format option set it to Unformatted list, in settings do not select Add views row classes and Add striping (odd/even), first/last row classes.

Below that is Show:Fields | Settings , click settings and select Provide default field wrapper elements and then select the fields mentioned below it to be displayed inline, which in your case is image Title and description.

Also the Table Format is good option but it creates a lot of problem in CSS customization.


Views... no format options in Fields->User? In any Field using the USER type there are no format options.  I'm making a user_picture view and want to use the image cache option.  But, at the bottom of any Field (pertaining to USER) where Format* usually shows up, it's not there.  Any ideas why?  Thank you.

Also, Format* works for nodes/content types.  So, it's installed and working functionally.

The short answer is that the user image is not a field unlike images attached to nodes. Views is using the field formatter that applies to fields and the way they are themed to allow you to select how you want to theme the field. This functionality doesn't work for properties like the user image.

The same goes for the say the node type. You can't select how to display the node type.

The easiest thing to do, is properly get the raw url and with theming turn it into the image with the image cache preset you want to use.


How to create a Privatemsg thread with multiple recipients in a Rules component? I'd like to send private messages to a selected group of users. For this purpose I use a view with VBO and a Rules component action (utilizing the "Send message" action provided by Privatemsg) - as  described in this question.

However, I still have a minor issue with it: Since I send the messages looping through the list of users, privatemsg module sends individual messages and doesn't create a thread with multiple users. Is it possible to use the whole array of users in a single "Send message" action?

Probably one solution might be to use cutoms PHP code in rules component and create thred with privatemsg_new_thread function. But it's not a very drupalish way, I guess.

I found a solution using a rule component with custom php code. It needs some changes in privatmsg module, see in this discussion: https://www.drupal.org/node/2725325


Modify arrays in form alter I'am having an issue which i cannot understand it , for example i have the following lines:

$form['field']['und'][0]['#type'] = 'select';
$form['field']['und'][1]['#type'] = 'select';
$form['field']['und'][2]['#type'] = 'select';
$form['field']['und'][3]['#type'] = 'select';

it works as expected , but if i try to change this hard coded method to :

foreach ($form['field']['und'] as $field)
            $field['#type'] = 'select';

it is not working anymore as expected...After a call like

 print render($form['field']);

for the first paragraph the result is good , as expected. But for the second paragraph it is not working anymore, the result is like nothing has been modified in the array. In the dsm($form) result either way the value of '#type' key is modified... I cannot understand the behavior. Please help!

Like PHP documentation says:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

http://php.net/manual/en/control-structures.foreach.php


HTML tags in Taxonomy Term Name I'd like to emphasize a character in the Taxonomy Term Name field. Text format is Filtered HTML, but the name (=title) is being displayed like this:

AK ORDERED SETS, N-UPLES, ORDERED ALGEBRAIC STRUCTURES

Any ideas?

Thank you very much!

Check the setup text format: Filtered HTML, here

admin/config/content/formats/[your_format]

The settings will filter the desired output.
Or just choose Full HTML (if configured properly) ;)


Proper way to create image field in a content entity My site allows users to upload images and add title and description to it. So I make a new class which extends ContentEntityBase. In its baseFieldDefinitions() method, I put an image field beside title and description fields:

$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setRequired(TRUE);

I expect to see a file/image upload control in the add/edit form, but I don't see it. I see only the title and description textboxes.

I tried to find "create('image')" in all Drupal source code but didn't see any examples. So I don't know if creating an image field like this is the proper way or not?

See ...

$entity->getFieldDefinition('image')

'file_extensions' => string(16) "png gif jpg jpeg"
'file_directory' => string(31) "[date:custom:Y]-[date:custom:m]"

And edit

$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setDescription(t('Image field'))
  ->setSettings([
    'file_directory' => 'IMAGE_FOLDER',
    'alt_field_required' => FALSE,
    'file_extensions' => 'png jpg jpeg',
  ])
 ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'default',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'label' => 'hidden',
    'type' => 'image_image',
    'weight' => 0,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);