Apply image styles to image field I have a code where view is rendered programatically and it contains an image field. However usually images are coming from nodes where different image style is applied so location of image is in different folder. If I preview the view manually style is applied and images appear in the proper styles folder but if this is executed by code it doesnt happen. Anyone with ideas how easily to trigger application of image styles from the code without walking each returned image field, checking is image style applied and so on.

I went with only solution which came to my mind - foreach the view results, check the image fields and then apply image style and create derivatives. Because when view render image fields programatically it doesn't actually set the files in proper styles folder, it is done on browser request but this doesnt suit our use case.


Partial URL transliteration? Is it possible to partially transliterate URL alias, so to leave for example the case of the node title unchanged, such as in:

/this/is/my/transliterated/path/THIS-IS-UNCHANGED-Node-Title-888

with the purpose behind it being to preserve product symbols, where similarity between lower and uppercase is unwanted.

And I mean fully automated behavior, such as with a template function or a module.

Certainly, you can call path_set_alias()  (or path_save() in Drupal 7) and set up whatever you want.  You could call these from within nodeapi() (or node_op..... in Drupal 7) and set up your path however you want.  But, I also think that drupal isn't case sensitive, so, 'foo/bar/BAZ' is the same as 'foO/bAr/BaZ' as far as it's concerned here, so, gotta be careful.

ADDITION:

If you want pathauto to do this, quick hack would be to edit pathauto.inc and do this:

  if (true) {
    $foo=drupal_strolower(dirname($output));
    $bar=basename($output);
    $output=$foo . '/' . $bar;
  } else {
    // Optionally convert to lower case.
    if (variable_get('pathauto_case', 1)) {
      $output = drupal_strtolower($output);
    }
  }

where it does just this:

// Optionally convert to lower case.
if (variable_get('pathauto_case', 1)) {
  $output = drupal_strtolower($output);
}

but it's up to you to more refine if(true) otherwise it will do this for every alias.


for D8, How to skip (don't update) some fields from existing entity during import if this field already has a value How to skip (don't update) some fields from existing entity during import if this field already has a value?
That for Drupal 8 with modules (migrate, migrate_plus and migrate_tools)

example of an yml I would like:

process:
  uid:
    -
      plugin: migration_lookup
      migration: users
      no_stub: true
      source: uid
  field_telephone: phone
  field_user_country: pays
  field_adresse/given_name: prenom
  field_adresse/family_name:
    -
      plugin: skip_on_notempty  \--> do not exist
      method: process
      source: \--> actuel value of 'field_adresse/family_name', How to get that ?
    -
      plugin: get
      source: nom

To import only a single field, or possibly multiple, use "overwrite_properties".

  overwrite_properties: If the migration has specified a list of properties to be overwritten, clone the row with an empty set of destination values, and re-add only the specified properties.

destination:
  plugin: 'entity:node'
  overwrite_properties:
    - field_name

Source:  Drupal\migrate\Plugin\migrate\destination


Why is jQuery dependency not working? I'm extending core Classy theme so I have included my JavaScript code in theme.libraries.yml file like this:

js:
  js/blogger-list.js: {}
dependencies:
  - core/jquery

but still browser console shows error: jQuery is not defined

blogger-list.js is really simple:

(function ($) {
  $(".views-col a").hover(function() {
    $(this).css('background','red');
  });
})(jQuery);

I'm using Drupal 8

What do I need to do?

First of all: DON'T EDIT ANY CORE FILE! EVER!!! Simply create a sub-theme or a very simple module to add your custom stuff.

I doubt a little bit that it really is this exact file that raises that error. But if so (your theme.libraries.yml looks incomplete somehow), please try to follow the docs as close as possible and use Drupal.behaviors to add JS functionality. See JavaScript API overview.

MYMODULE/MYTHEME.libraries.yml

foobar:
  js:
    js/blogger-list.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

js/blogger-list.js

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $('.YOUR-VIEW-ID-OR-WHATEVER', context).once('myCustomBehavior').each(function () {

        $(".views-col a").hover(function () {
          $(this).css('background', 'red');
        });

      });
    }
  };
})(jQuery, Drupal);

And last but not least don't forget to attach your library to a render array or your theme's info file. See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.


How can I make sidebar_first narrower? I try to make the sidebar_first narrower in a Bootstrap 3 theme in Drupal 8. There is no numbered class like col-sm-4 here that I could change and thus ask the devs. What is the right approach to take?

            {% if page.sidebar_first %}

                {{ page.sidebar_first }}

            {% endif %}

col-sm-4 will be applied via a function in the theme. if you search through the theme for where the variable is set you can change it there. Possibly in the .theme file.


Adding meta data to user I would like to store meta data about users.

At first this I tried by adding fields to the user, but this is not exactly what I want, because the user himself should not be able to manipulate or view the data.

The data I want to store is based on actions a users takes in the application. Its is similar to a status which I want to write and read programmatically. E.g. has the users phone number been validated by the system?

What is the best way to store such data?

Fields are definitely the best method for storing this data.

You can combine fields with the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

With that module you'll be able to specify exactly which fields the user should be able to view/edit.


240sec Registering New Account with Services I am working with a fresh copy of Services 7.x-3.4 / user resource enabled.

A POST to api/user/register is made with Content-Type header application/json and body:

{
   "name": "ffftest",
   "pass": "123",
   "mail": "afsdf@awdfasd.com"
}

The Drupal user is created immediately, but the HTTP request takes about 240sec to respond. When that finally happens, the response is good: status 200 with the uid/uri.

How do I find out what's going on with the HTTP response and get Services to respond immediately?

(Possibly related to the new CSRF token https://drupal.org/node/2013781#comment-7508325)

This was a server configuration issue as described here: http://www.promediapublishing.com/blog/2012/07/fixing-a-slow-registration-form-post-on-drupal-7


Memcache integration is not loaded I'm trying to setup memcache on my drupal 7 site. I have a memcache server setup and working and I've used setsebool -P httpd_can_network_memcache 1 to allow apache to communicate with it. I've also confirmed that port 11211 tcp is open in ip tables.

I've installed the memecache drupal extension, the PECL extension in PHP and when I run phpinfo(); I see that memcache is loaded.

In settings.php on my drupal web server I have the following:

/**************************************************
 * MEMCACHE
 **************************************************/
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['memcache_servers'] = array(
        'memcacheserver.ourdomain.local:11211' => 'cluster'
);

$conf['memcache_bins'] = array(
        'bin1' => 'cluster'
);

$conf['memcache_key_prefix'] = 'sdrupal';

However when I go to the status reports page I see the following:

Memcache integration    Memcache integration is not currently loaded.
Check README.txt and ensure that memcache.inc is configured correctly in settings.php

I've read through the readme.txt file repeatedly and of course you can see I have memcache.inc specified above.

I thought perhaps I had a conflict with the varnish module, or the apc module as those also set cache_backends - but its an array so I think thats ok. I also commented them out and I'm still seeing the error above.

I also confirmed that sites/all/modules/memcache/memcache.inc exists.

Why isn't drupal loading/finding memcache.inc?

Thanks
Brad

You've got to add these lines to your settings.php file to run memcache proper:

$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

If you're on top of a multisite installation also don't forget to add this one:

$conf['memcache_key_prefix'] = 'unique_key';

More information about configuration and setting memcache for drupal you can find here.


How do I limit the number of images displayed in a teaser? I have a site with an image field that allows for unlimited images. I want the first image in the field to be shown in the teaser (for both listing and views). Is there a configuration option that will let me do this?

I'd rather not put in a self-written module (as it means I have to maintain it myself).

Try using this module http://drupal.org/project/field_multiple_limit

It allows you to go into the display settings for your content type and configure the teaser settings to display only a certain amount of values. You can even make it skip vales, for example if you want it to display values 2 to 5.


Deleting a Drupal 8 Content Type Field also Deletes all the Views linked to it... Undo? So I deleted a Drupal 8 content type field and it also deleted the views that is associated with it. Is there an undo button?

Yes, that's what currently happens. Drupal informs you on the delete confirmation page what all will be deleted.

You can try one thing that to restore your backed up database.

Also, there is an issue that tries to improve it so that the view updates itself instead.


How do I add a role to new users? I'm using the Drupal 8 version of the Rules module. How do I add a role to new users with a rule?

I created a rule.

Name: New user role
Events: After saving new user
Action: Add user role
Data selector: user.roles

I don't know what to set for value. Is my rule correct?

I want to add the particulier role to users.

I also have tested rules module in drupal8 but data selectors did not worked, as also mentioned here https://groups.drupal.org/node/516054

Then i tried https://www.drupal.org/project/registration_role which worked for me. You may also try this module if you want to assign a role to a user on registration.

Thanks


RSS icon in QuickTabs I'm using Drupal 7.14 with QuickTabs 7.x-3.4. I have a couple of views with feeds attached to them. I've also set the "Attach To:" field for these feeds. The ones that aren't inside a QuickTab are working fine, but the ones inside QuickTabs won't display their RSS icon. How can I get the views inside QuickTabs to also display their RSS icon?

One way to resolve this is by creating required feeds page with views.

Then add this generated feed pages link manually through Global Text area field of appropriate view in footer using HTML anchor tag. Separate links will be displayed inside each view footer of QuickTabs as per setup.


Giving a Group it's own calendar I've learned how to create groups via Organic Groups, and I learned how to use the Calendar to create a site wide calendar.

I guess what I need help with now is how to integrate the two. I can't seem to figure it out. Any tips?

Use a relationship with the group Id and set the default value of your contextual filter to group Id from content


How to redirect a user to his own content after log in? I want to redirect a user after log in to his own content.For example lets say a user created a node/3.After log in I want to redirect the user to node/3.How can I do that with rules or with something else?

To list the contents of a ( the current) user you can set-up a view and add a filter ar URL argument. To redirect the user to this view after login you can use rules.


Views Filter Content Type Drop down option sorting I have a view to with the Filter of Content Type in drop down and based on selection it is displaying the nodes.

Now I need to alphabetically order the Content Type options into Filter Drop down.

Currently the content type listed into drop down as

Press Release
News
Event

and I need to display it as

Event
News
Press Release

There is no such way I found into views configuration. Do any one have idea how to do so ?

One solution here is to use the Grouped filters option the Filter type to expose setting. In each grouped filter you can use the Is one of... operator and select the type. Grouped filters have weights that you can drag around to any arbitrary ordering.

As an example, here's a reverse ordering of content types:


Make view exposed filter shows results related to previous filter in view About my form:
In my project, i'm having a form where project name field is select(drop down) and i have to enter a field(example "sub-project"). Then i will submit the form with project name from select(drop down) and i will type my sub-project name.

View Form:
Here, while showing the form results as table i want two exposed filters. they are
1. Project name(As select box in filter field)(**No problem in this part)
2.Sub-project name(As select box in filter field)(**Problem)

Question:
Now, if i select project name in filter(Example: Project Auro) then automatically i want the sub-project field(2nd exposed filter) to show the sub-projects as drop-down which are only related to Project Auro, that i submitted in form.

Please assist me, and Thanks in advance if you guide me in this problem.

As always there are many ways to solve a problem in Drupal.

The easiest way here is probably the Views Dependent Filters module.

This way the "sub-project" form field will only appear after a user chooses the "project" filter.


Facebook integration I am currently developing a real estate website, and the client wants to push a notification to his Facebook page when he edits or adds a real estate.

How can I achieve this, with a module or hard-coded?

Post It Everywhere just one click and your content will be posted to:

Facebook
Twitter
LinkedIn
FriendFeed

The most common way to make your site popular is by posting your content to different social networks. Here is a new and simple way for publishing content to different social networks.

  Features:

  The link "Post it Everywhere!" will be displayed with every node type(the admins select). This link will be used to post on all the
  networks
  Authenticate Once, Use Forever: The users don’t have to authenticate every time when they login to the site or want to post
  content. Each user will authenticate himself only once and these saved
  settings will be used to post in the future.
  The users will not be moved to other sites to post the content (as it happens in various modules that users are redirected to that
  social network on which they want to post).
  The user names and passwords of users are not saved for this purpose so no risk for security and spoofing.
  Facebook Connect API is used to send posts to Facebook and OAuth is used to connect to LinkedIn, Twitter and FriendFeed. OAuth API can
  be downloaded from this link.
  End users can update their settings at anytime.


Determine Next Item in DrupalQueue for Drupal 7 I am trying to figure out how Drupal pulls what will be the next item to be processed in the queue for Drupal 7.  I have looked at SystemQueue::claimItem and I am missing something.  I have a queue that jams from time to time and I do not know how to figure out what record it is jamming on.

Thanks,
Steve

SystemQueue::claimItem has the code you're looking for. https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/function/SystemQueue%3A%3AclaimItem/7.x

You can run the same query that will be used to get the next item in the queue. Just replace $this->name in the code below with the queue name.

    $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE expire = 0 AND name = :name ORDER BY created, item_id ASC', 0, 1, array(
      ':name' => $this->name,
    ))
      ->fetchObject();

$item should have everything you're looking for.


How to start views at %nid position (from path)? I have a portfolio showing somes nodes (views3 + views slideshow using cycle). Everything works fine, I've a default path /portfolio to access to it.

However, I'm trying to set a path for each slide. I would like to use /portfolio/%nid and using %nid in views to default the first viewed slide to this node id.

Anyone know how it is possible ? I've tried with UI but I don't think it is enough.

In jQuery Cycle there is an option called startingSlide. By default this is set to 0, like this: startingSlide: 0

If I remember correctly there is a tab/textarea for advanced settings where you can add options to jQuery Cycle from within the Views UI. I think you can add "startingSlide: 5" for example there.

You will need to find out which is the starting slide (convert the %nid to which row in the view it is) and add it as a HTML element. When that is in place we can fetch it with jQuery and add it as a jQuery Cycle option. I'm not sure which is the best way but I think you could do something like:

    function MYMODULE_views_pre_render(&$view) {
      if($view->name == "MYVIEW") {
        $view->attachment_after = $startingslide;
      }
    }

You will have to add more code to find out $startingslide there of course. Look inside $view->result and find out which of the rows that is the argument, that will be your $startingslide. Use dpm() on the view to search through the object.

Hope this will help you. Let me know what you ended up doing :)


Drupal Commerce - creating a product catalog I've downloaded Drupal Commerce and created my 3 products. Everything else I've kept as the default. Then I wanted to created a catalog so users could buy items. Note: I've also installed and input API credentials for Drupal Paypal already. So then I went to create a view of type 'product display' as seen here:

https://drupalcommerce.org/user-guide/setting-product-catalog

But when I create a new view 'product display' is not one of the 'type' options.

So my question is, how do I get something to show as a product display item? somehow it seems I have to map the products I created to 'content types'...but shouldn't the module already do that?

I looked back through the documentation on that site, and undoubtedly I missed something, but I'm not seeing how this is done.

Note #2: I tried to install commerce kickstart, but I'm using WAMP and couldn't get it to work, so I have to trudge through on my own.

You need to have the Product Reference module enabled and create your Product Display content type manually and add a product reference field to it. Then you can use this content type in Views.

Source: Creating Product Display Content Type


add link programmatically to views field Drupal 7 I am generating views result using ldap query and eliminating some result by checking it against Drupal node title using hook_views_pre_render() and looping through views result.

I want to add link to this ldap views using Drupal node id.

Tried adding in the same pre_render function using drupal l() function. But it displays full html i.e

    title

instead of html.

Can anyone help resolving this issue?

Thanks...

Instead of coding why you don't use views fields.

Add the title and node id fields to the view.
Exclude them from display.
Add a global: custom text field.
Use tokens to print the HTML you want.

It should look like this:

[title]


Mass translate taxonomy terms I have around 400 taxonomy terms; very complicated hierarchical stuff.

I wonder if anyone knows about a plugin (taxonomy manager style) that can help me do it without having to dive into taxonomy and translated one by one.

Thanks !

Translation Table:

  This module presents your taxonomy terms or menu items in a table, and
  each language has a corresponding column. Just fill out the
  translations and click Save.


Browser specific javascript inclusion It seems like the browser conditionals:

  drupal_add_js(drupal_get_path('module', 'cufon') . '/js/cufon-drupal.js',
 array('group' => JS_THEME, 'browsers' => array('IE' => 'gte IE 9', '!IE' => TRUE),
'weight' => 999, 'preprocess' => FALSE));

included in template.php (or a module) are not working due to the fact browsers option is supported for drupal_add_css() but not for drupal_add_js().

Can one state a not-hackish/patchy solution to exclude this file cufon-drupal.js on older browsers?

A solution like

<!--[if gte IE 9]>
<script src='<?php drupal_add_js(drupal_get_path('module', 'cufon') . '/js/cufon-drupal.js'); ?>'>
</script><![endif]-->

in html.tpl.php
is not working.

Seems like there is a non-drupal solution:

if(jQuery.browser.version.substring(0, 2) != "8.") { alert("not ie8"); }

It is not very handy as I have to paste inside the brackets the content of cufon-drupal.js content.


warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'search_form' I am getting a warning when I use a new theme, I've got error that search form not found.

warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'search_form' not found or invalid function name in /......./...../includes/form.inc on line 377.
Line 377
$form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);

I have tried changing some items on line 377.

You need to either

Enable the core search module or
remove the search form block from being rendered in your theme (perhaps in template.php or page.tpl.php)


How am I supposed to upgrade a site to latest core version? I tried to update a Drupal 7 site to the latest version. The old Drush update doesn't work and it throws an error about a unknown engine type output format.

I tried to delete the web folder, extract Drupal 8 files, change the database connection settings to use the old database, and call update.php. It doesn't work, and it throws errors about MySQL encoding.

I tried to install Drush 9 to upgrade core, but it keeps complaining about the composer.json file.

I tried to install Drush 8, but it shows more errors.

How am I supposed to update an old Drupal installation to latest core version?

From Drupal documentation :

  Strictly speaking, 'updating' refers to taking your site from one 'minor' version to another, as for example, from Drupal 7 version d7.1, to d7.2; or from Drupal 8 version d8.0.0 to d8.1.3, etc.

Which means upgrade can be done only to minor version.

If you want to change the whole version for example moving from Drupal 7 to Drupal 8 you need to migrate your site, and this normally involved a data migration and restructuring, Also changing and reviewing your custom modules code.

See Upgrading from Drupal 6 or 7 to Drupal 8


How do I empty the cart? I want to programmatically empty the cart after these events.

Add to cart
Update quantity (in cart page)

In fact users must have only one product in their cart.

Are you sure you want to empty the cart? Or do you just want to limit the quantity of any product to one?

I recently had a similar situation. I added a hook_form_alter to hide the quantity so it can't be readily changed. There's not a specific FORM_ID you can use for an add to cart form because they get a hash added to them, so it looks like this:

function my_module_form_alter(array &$form, FormStateInterface $form_state, string $form_id){
  if (strpos($form_id, 'commerce_order_item_add_to_cart_form_') === 0) {
    ... plus any other logic specific to your use case

    _my_module_specific_add_to_cart_form_alter($form, $form_state, $form_id);
  }
}

function _my_module_specific_add_to_cart_form_alter(array &$form, FormStateInterface $form_state, string $form_id){
  // Doesn't make sense to buy more than one, so hide it.
  $form['quantity']['#type'] = 'hidden';

  ... plus any additional changes, e.g., I have this:
  // There's only one variation, so hide it. (
  $form['purchased_entity']['#type'] = 'hidden';
}


How to store a list of bundles in a select field (programmatically)? I need to be able to present a list of available bundles (in this case, Commerce Line Item types) as a select field on an entity, so I can use the value in a custom module. Suggestions?

I've tried creating a select list (using commerce_line_item_type_get_name) and then populating the field's "allowed values" programmatically, but the problem is that when bundles are added/removed, I can't change the allowed values if data is already stored. I don't actually need this kind of data management, as it doesn't matter if stored values reference a bundle that no longer exists. Perhaps I don't need a select list, but a textfield with a dropdown menu input widget or something? I would appreciate any advice on how to proceed.

Thanks! :)

I've found that there is an "allowed values function" setting for list fields. Perfect! :)

http://www.phase2technology.com/blog/setting-the-allowed-values-function-property-on-text-fields/


Google Analytics module is not tracking site search I have a site that is using the Google Analytics (GA) module. It's happily tracking data to GA. However, I can't seem to get Site Search working.

The site uses Apache Solr. A search results page for the query "test" is:
/sitesearch/test

I've enabled "Track internal search" in the Google Analytics module config page
I've enabled "Site search Tracking" in GA
I've set the query parameter to "sitesearch" in GA
I've unchecked "Strip query parameters out of URL" in GA
I've confirmed that if I manually hit this URL, it pings a track in GA:
/sitesearch/test?sitesearch=test
(Any URL on the site with ?sitesearch=test works.)

I'm out of ideas. What could be causing this to fail?

The problem is that Google Analytics only supports site search tracking if the path is "search/something", not "sitesearch" as we use on my client's site.

Line 138ish from googleanalytics.module:

if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = search_get_keys()) {
  $url_custom = '(window.googleanalytics_search_results) ? ' . drupal_to_js(url('search/'. arg(1), array('query' => 'search='. drupal_urlencode($keys)))) . ' : ' . drupal_to_js(url('search/'. arg(1), array('query' => 'search=no-results:'. drupal_urlencode($keys) .'&cat=no-results')));
}


Downloading core via command-line I usually download the latest Drupal 7 using drush dl drupal --select, but but Drupal 8 doesn't get listed.

What are some nice and quick ways of download the latest version of Drupal 8, even though it is still in alpha stage?

drush dl drupal-8

Since there are no stable releases of Drupal 8, you must use the --all option to see the tagged alpha releases:

drush dl drupal-8 --select --all

This also works.

drush dl drupal --default-major=8 --select --all

Both of these are now working in the current version of Drush, without the --all flag:

drush dl drupal-8 --select
drush dl --default-major=8 --select

Note that the Drush pm-* commands only work with one major version of Drupal at a time, and that version currently defaults to Drupal 7. Therefore, drush dl drupal only shows the various Drupal 7 releases available, and does not include any versions of Drupal 8. This much has not changed.

drush dl drupal-8 now works fine with the Drupal 8.0.0-rc1 release.


Add an html snippet some within body of the theme using preprocess I want to add a small html within the body tag of the site. I believe I can use template preprocess for this. I don't want to touch the template files. I am doing this from a module.

You should add hook_node_view() into your module. See the given example on how to add HTML markup.

function mymodule_node_view($node, $view_mode, $langcode) {
  $node->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}


Is there a secure mongodb wrapper? I was looking into MongoDB module, but found it very verbose and overly complicated to perform simple DB operations and this module seems to be tightly integrated with Drupal entities.

Is there any other Drupal-PDO wrapper for Mongodb that is easy, secure (NO SQL injection free) for simple DB operations in Drupal?

Thanks for your time.

As far as I can see, there isn't any PDO wrapper for MongoDB, and there isn't any code that allows to use MongoDB as database for Drupal, simply for the fact Drupal expects to use an SQL database engine, while MongoDB is not an SQL database. You cannot generally convert a static query into code that uses MongoDB.

The Mongodb module allows you to use MongoDB in those cases where Drupal is not expecting to get data from a database, although the default implementation uses database table. That is what happens for the cache, entity fields, and Drupal queue, for which a module can define a new PHP class to implement a different mechanism to store data.

Notice that the Mongodb module is not tightly integrated with Drupal entities, as it doesn't use any Drupal entity to work. It eventually allows you to store field data in Mongodb, but that is an additional module you can eventually use. If you are not interested to store field data in MongoDB, the main module (mongodb.module) still works, and can be used from the other sub-modules.


appened custom text to content in template_preprocess_taxonomy_term drupal 8 I want to append some custom text to taxonomy term pages using template_preprocess_taxonomy_term hook, But when I add my custom array key to it, the text don't show up on the term pages.
PS I have cleared drupal cache many time.

Here is my code

function cars_theme_preprocess_taxonomy_term(&$variables) {
      if($variables['view_mode'] == 'full'){
         $variables['content']['cars_view'] = "this is test";
     }
}

Ok, so here is how I did it.

function cars_theme_preprocess_taxonomy_term(&$variables) {
      if($variables['view_mode'] == 'full'){
         $variables['cars_view'] = "this is test";
     }
}

And then in my twig file I output the cars_view as {{ cars_view }}


How to supress the second sidebar in Zen theme? I have nodes that include blocks in the second sidebar. When all the blocks are removed, every node's content takes up the width of the page (and extends into the sidebar region) which is what I want. When I add any block, even if it isn't displaying on that specific node, the sidebar is no longer suppressed.

I also have to re-save every block I add in the second sidebar region, because if not, it displays the title 2x and it displays on every node, regardless of what it is configured for. So for example, if my block of "related links" displays only on node x, it will show also on node y UNLESS I re-save the block configuration.

I have not found anything in my searches here and on Google (most want to add to a sidebar not remove it), and I just don't know where to even start looking for what could be wrong. Any help would be appreciated.

Go to structure => blocks, and move those blocks in another region, voila second sidebar suppressed. You may want to change the regions altogether but that gets into theme templates and such...


Obtaining the node type being added with php Other than pulling the information from the url itself, is there a way to retrieve/obtain the node type that has been selected in the add content area. ie: www.mydomain.com/node/add/article... using PHP? I have been able to do this when updating/editing a node using menu_get_object() in a template file but not when adding a node.

If you are changing the form used to create a node, then you could use the following code.

function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    // The node is being created.
    // Use $node->type to get the content type of the node.
  }
}

The reason is that node_add(), the page callback for the node creation form, contains the following code.

  $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);

This means that the form used when creating a node is the node edit form.

As alternative, if you need to change the node creating form when the content type is, for example, article, you can use the following code.

function mymodule_form_article_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    // The node is being created.
  }
}

As in this case the form is altered only when article is the content type of the node, you don't actually need to check the content type.

If you need that information in other cases, then you can only get it from the URL.


Using an address field widget on a custom form and storing data I have a Subscription custom entity and I would like to use the default entity form for administration tasks and a custom multistep form for the subscription process.

I added an address field to my Subscription entity and I would like to use the widget in one of the custom form steps.

I was expecting I could use something like '#type' => 'widget_id' plus some widget configuration, but it does not seem to be so simple as this answer points out.

  a widget and a form element are two different things that are used in different cases; consider a widget a more specialized type of form element.

What would be the right approach then? In the field_attach_form change record a comment suggests

$display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
$display->buildForm($entity, $form, $form_state);

How do I get just my address field? Form display modes?

And then, how do I deal with validating and storing the data properly?

You can limit the $form array's elements by setting their #access property to FALSE.

The validation and storing should be handled by the form for the corresponding entity by itself.


How to access table tokens in views through handler I've added a custom field of type global using views_handler_field. This custom field type is basically a button that needs to call a javascript function. This javascript function takes an adjacent field's value as a parameter. When I edit the view on my webpage, under rewrite rules->replacement values, I can see the token for the value I need in my handler's functionality. In the code example, it's [fieldID]

However, I don't see any way to access this value in my views_handler_field include file.

function render($values) {

    $actions = array();
    $variable = variable_get('fieldID'); // HERE is what I'd like to do to get the adjacent [fieldID] icon

    $alt = t('Download File');
    $actions[] = array(
      'name' => t('Download'),
      'html' => 'javascript:initiateDownload('.$variable.')',
      'id' => t('download-button-' . $variable),
      'icon' => theme('image', array('path' => drupal_get_path('module', 'download_process') . '/images/edit.png', 'alt' => $alt))
    );

    $output = '';

    $counter = 0;
    foreach ($actions as $action) {
      $output .= l($action['icon'], $action['html'], array('attributes' => array('id' => $action['id'] . $counter), 'html' => TRUE, 'external' => TRUE));
      $counter++;
    }
    return $output;
  }
  function query() {

  }

I've tried working with get_render_tokens, but I don't think that that's what I'm looking for. Any help here would be appreciated! For reference, I'm using Drupal 7.

The answer ended up being very simple. All I needed to do was cast $values to an array, then access the id. Like this:

$array = json_decode(json_encode($values), true);
$value = $array['fieldid'];


how to show file counter using file_download This is a beginner question, in file_download module. I have installed it and then I followed Install Instructions. But I couldn't figure out how to show the counter or statistics_popular_block, I tried to create a new view but didn't get any thing. I am new to views.

When I look to the source code I can see things such like:

src
  FileDownloadSettingsForm.php
  Plugin
     Block
         FileDownloadPopularBlock.php
     views
         field
             FileDownloadCounterTimestamp.php
             FileDownloadNumeric.php

any help?

The module's project page gives these instructions:

Download to modules directory
Enable module
Apply formatter to any file or image field
Apply settings for title, currently either filename or nothing

Did you apply the formatter?  To apply the formatter, you need to go to "Manage field display" for your content type, choose the image/file field, and then change the formatter.


"Site off-line due to technical problems" (no extra info in message). What causes this? What causes the following message on a Drupal 6 site with no other information?

Site off-line
The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.
If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider's database server is running. For more help, see the handbook, or contact your hosting provider.

I think it means that the database did not respond in time but can someone confirm that?
I can force almost the same message by stopping the db but then it has some extra info under it about not able to connect to the db. That makes me wonder what it means when there is no extra info at all.
It is definitely related to slowness. It happens sometimes when the site is very busy and therefore slow. There is no obvious reason recorded in either the Drupal or Apache logs
Thanks

I'd wager you're using Drupal 6. And yes, it means a fatal error in connecting to the database.


Adding a validation handler to the registration form I have altered the registration form to change the thank you message and add the validation of some fields.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['actions']['submit']['#validate'][]  = 'checkout_nationality_form_validate';
    $form['#submit'][] = 'thank_on_submit';
  }

All code is working fine; my problem is the registration doesn't take the default Drupal validation. Why does this happen?

You need to change this line

 $form['actions']['submit']['#validate'][]  = 'checkout_nationality_form_validate';

to

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


Exception handling for incorrect content type for request in custom REST API plugin I have created a custom REST API plugin for an endpoint. I have set the accepted format to json using the configuration options. This works. However, if we set the content-type to something other than application/json I am getting a 500 error.
I am seeking to know how this exception can be handled more gracefully. However, what is preventing this is the fact that I am not able to get the Request object in the plugin code.
I tried extending the default EventSubscriber services but they do not seem to be of help. I am seeing that this seems to be an open issue in Drupal.org
https://www.drupal.org/project/drupal/issues/2954286
I am thinking of altering the route and set the default format to json as in manually added custom routes but open to better ways.
Any help would be appreciated.

For the record, here is how I managed to solve the issue. This is a workaround but it allows for graceful degradation.

I created an event subscriber that extends
HttpExceptionSubscriberBase
There is an onException method that retrieves the event that generated the exception
From the event, we can get the request type and handle the exception.
By overriding the method we can handle this exception

class MyClassService extends HttpExceptionSubscriberBase {
public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();

    // Make the exception available for example when rendering a block.
    $request = $event->getRequest();
    $request->attributes->set('exception', $exception);

    $handled_formats = $this->getHandledFormats();
    $format = $request->query->get(MainContentViewSubscriber::WRAPPER_FORMAT, $request->getRequestFormat());
    if ($exception instanceof HttpExceptionInterface && (empty($handled_formats) || in_array($format, $handled_formats))) {
      $method = 'on' . $exception->getStatusCode();
      // Keep just the leading number of the status code to produce either a
      // on400 or a 500 method callback.
      $method_fallback = 'on' . substr($exception->getStatusCode(), 0, 1) . 'xx';
      // We want to allow the method to be called and still not set a response
      // if it has additional filtering logic to determine when it will apply.
      // It is therefore the method's responsibility to set the response on the
      // event if appropriate.
      if (method_exists($this, $method)) {
        $this->$method($event);
      }
      elseif (method_exists($this, $method_fallback)) {
        $this->$method_fallback($event);
      }
    }
    // We are now assuming that this a special RuntimeException
    // where the Content-type header is not set to json or missing.
    if ('json' != $request->getContentType()) {
      if (method_exists($this, 'on415')) {
        $this->on415($event);
      }
    }
  }

public function on415(GetResponseForExceptionEvent $event) {
    $method_exception = [];
    $method_exception['message'] = 'Missing or unsupported Content-Type request header.';
    $response = new JsonResponse($method_exception, 415);
    $event->setResponse($response);
}


Use entity_uri or drupal_path_alias()? What are the difference? And when should you use which one?

entity_uri() is rather new to me (Drupal 7) and I see it little used. But it appears to be a lot cleaner and better performing then drupal_get_path_alias().

FYI: I want to get some background information to deal with an issue on Tagadelic.

These functions actually have not much in common. There is no question of using one or the other. You will in fact use both of them, although you will most likely not call drupal_get_path_alias() directly.

entity_uri() returns an array that contains the path and options to link to an entity. So for example for a node, you call it like this: entity_uri('node', $node) and it will return node/$node->nid. That's kinda trivial. It gets more interesting with other entity types, like private messages (where the path is messages/view/$message->thread_id#privatemsg-mid-$message->mid).

You use the returned array like this: url($uri['path'], $uri['options']) (or similarly with l()). Then, that function will call drupal_get_path_alias() internally to check if there is an alias for that internal path and will use that.

The idea is that you can generate the internal path for any entity, without any kind of special handling. A real life example is the Userpoints project. Userpoints transactions support to reference an entity by specifying type and id (Yes, Userpoints used the entity_type terminology since Drupal 5...). Previously, there was a large bunch of code with support for nodes, comments and users and a custom hook to be able to support more things. When I ported the module to Drupal 7, I was able to replace all that with a simple call to entity_uri() and it now supports all entities out of the box: userpoints_create_description().


Programmatically alter a field collection field item not yet saved in the database Updating field collection field item gives error when one item is added.

I have the following code which works well when just changing values of a field already saved in the database but if I add a new field collection item to the node it throws an error (I guess because the value hasn't been saved yet in the database)

  EntityMetadataWrapperException: Unknown data property field_date :

function pdf_app_node_presave($node) {

 $node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_chapitres->value() as $library) {
$library_wrapper = entity_metadata_wrapper('field_collection_item', $library);
 $library_wrapper->field_pdf_title->set('newtitle');
                $library_wrapper->save();
  }
 unset($library);
 }

I might try removing $library_wrapper->save(). Calling $entity_wrapper->save() within hook_node_presave() is problematic for the exact reason you're stating -- the field collection item doesn't exist yet so it doesn't have the data needed to allow it to be created/saved. Calling $entity_wrapper->save() inside of hook_node_presave() can also sometimes cause issues on its own. By setting the value but not saving it, it should act as though you entered the value in the field on the edit form and should be saved when the parent node is saved.

Alternatively, you might try hook_node_update() or hook_node_insert() instead of hook_node_presave(). These fire later in the saving process, at which point your field collection item may already exist, in which case you won't have any problem saving it


Custom Image Background in Block I tried Dynamic background module but it seems it's not what I am looking for. Is there such a module that will allow me to change the background for a certain pages or group of pages that works the same like block?

Like in Block, I can select which pages this block will be shown.

Example:

    Show background on specific pages
         All pages except those listed
         Only the listed pages

I believe there's a module that can do this, I would be very glad if somebody can point me to the URL of the module.

Thanks in advance.

You can do it via a class that you selectively add to the pages, then using CSS add a background. Two modules stand out:

Node Class

  Node Class is a simple module that allows users to add custom CSS
  classes to any node through the node/add interface.

Context

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

See also:

Is it possible to add css class to the page's body tag with rules when certain conditions are met?

and

Context Block Classes


How to add country phone number prefix in webform? I have a webform, with a field for phone number.

I would like to have another select dropdown field before phone number, with country name and country phone number prefix.

Eg:
Singapore (65)
United Kingdom (44)
Venezuela (58)

Webform allows you to load options in bulk. Just google for this list and load it into a spreadsheet. Use a bit of find/replace to get it into the format needed by a webform select element, which is:

65|Singapore (65)
44|United Kingdom (44)
58|Venezuela (58)

Then create a webform select field and paste it in.

To get the fields to line up side-by-side (with country code right before phone number and not on a separate line) use the webform_layout module.


Alter webform select option values I'm using a custom module to change subject and recipient email. Actually my fields are a single text field for the subject, and a select field for recipients.

I would like to add a more options actually. My webform is on a public page opened to all. I add a new page with a link to the contact form and I want that link to provide some options.

So my link is like this: /node/5?option=1

This bring me to the aforementioned page and set the subject field according to my custom module like this:

function ca_formdispatch_form_alter(&$form, &$form_state, $form_id)
{
    $nid = arg(1);
    drupal_set_message(t(" webform_client_form: .", $form_id));

    //determination de l'ID du formulaire afin de l'alt�rer
    if ($form_id == 'webform_client_form_5' && $nid == 5)
    {
        $origine = $_GET['origine'];

        drupal_set_message(t("contenu d'origine : @origine.", array("@origine" => $origine)));

        //liste des email destintaire possible en fonction de l'origine du destinataire

        switch ($origine)
        {
            case '1':
                $email_dest='xxx@example.com';
                $sujet_mail="Message pour 1";
                break;
            case '2':
                $email_dest='xxx@example.com';
                $sujet_mail="Message pour 2";
                break;
        }

        //affectation de la valeur de $email_dest comme email destinataire du message,
        $form['submitted']['destinataire']['#default_value']=$email_dest;
        drupal_set_message(t("contenu de email : @email.", array("@email" => $email_dest)));

        //affectation de la valeur de $sujet_mail comme sujet du message
        $form['submitted']['sujet']['#default_value']=$sujet_mail;
        drupal_set_message(t("contenu de sujet mail : @sujet_mail.", array("@sujet_mail" => $sujet_mail)));
    }
}

It works for the subject field but not for the recipient field. My recipient select field can take 4 options. I can set the select on an existing key but not add a new key not provided by the select by default.

I would to lock the key set by the module or hide the select field to don't allow is change by the user that did click on the link before.Is it possible? I know I can use hook_webform_select_options or hook_webform_select_options_alter but I don't know how with to make this code ... if someone could help me.

EDIT:
i test this to get the "key" and pass it to the webform field but  i think it doesn't work.

switch ($origine) {
  case 'charge-relation-entreprise'://valeur de $origine
  $clef="Chargé des Relations Entreprises";
  $email='web@pro.com';
  break;....

$form['submitted']['choisissez_votre_destinataire']['#options'][$clef] = $clef;
$form['submitted']['choisissez_votre_destinataire']['#value']=$clef;
$form['submitted']['choisissez_votre_destinataire']['#key']=$clef;

but if this display the right text in the select,it doesn't send mail...

EDIT2 : i get the right key label displayed if i set a default value key in the webform select list setting like here https://computing.artsci.wustl.edu/help/drupal-webforms-advanced

But my select doesn't work anymore if i go to the webform page directly,whithout instructions in the url.Like with the edit1

For select fields to accept a default value, this value must be part of the #options list.

So you have to add the option before you can set the default value (important is the array key):

$form['submitted']['destinataire']['#options'][$email_dest] = $email_dest;
$form['submitted']['destinataire']['#default_value'] = $email_dest;

Then to hide the form element you can do:

$form['submitted']['destinataire']['#access'] = FALSE;

Or to keep it visible but disabled:

$form['submitted']['destinataire']['#attributes']['disabled'] = 'disabled';

But in any case, the submitted value for select elements must be part of the options list, otherwise it won't be accepted as a valid submission value. This is one of the many ways that Drupal tries to prevent malicious form manipulation.

For the difference between #value and #default_value: if #value is set, then it doesn't matter if a user chooses a different value for the form element. The finally submitted value that arrives in the submit handler will be the value set with #value. It's hardwired so to speak. #default_value on the other hand is more like a suggestion, it is changeable by the user and whatever is chosen will also arrive at the submit handler.


How does the Drupal LDAP module manage passwords? I'm currently configuring the LDAP module for my Drupal site (7.37) and I wanted to know if it's my AD password that is stored in my database (table users).

If it's not my AD password, is it just a random string? What it is and how does it works?

Thank you.

PS: I haven't configured anything to store the password.

This is all explained in the documentation and help text provided in the admin screens of the module.

Drupal supports multiple login sources. When a user logs in an entry for the type of login used for the person is stored in user_auth as an example.

By default LDAP does not store for example the AD password of the user within Drupal. It stores a dummy password and passes login info to LDAP from the login form upon a login attempt.

If you configure LDAP to sync drupal account information to and from Drupal then Drupal may store the password your LDAP accounts -- but this depends on how you've configured your LDAP service, and how you want the drupal ldap module to interact with it.


How to get a list/array of all content entities? I need a list of all content entities, to query them all and check if they have a specific field.

Couldn't find this in the API doku.

This is what you need:

use Drupal\Core\Entity\ContentEntityType;

$content_entity_types = [];
$entity_type_definations = \Drupal::entityTypeManager()->getDefinitions();
/* @var $definition EntityTypeInterface */
foreach ($entity_type_definations as $definition) {
  if ($definition instanceof ContentEntityType) {
    $content_entity_types[] = $definition;
  }
}

But a better approach would be to get the field first and then the bundles which has this field. For example, we are looking for the "field_image" in "node" typed entities:

   use Drupal\field\FieldStorageConfig;

   $field_image = FieldStorageConfig::load('node.field_image')
   $bundles = $field_image->getBundles();


Drush minimal bootstrap only for variables for vget How do you make drush bootstrap  minimal. How do you specify the bootstrap method like DRUPAL_BOOTSTRAP_VARIABLES, DRUPAL_BOOTSTRAP_CONFIGURATION  in the drush command?
Background:
I just want to have the drupal variable value in a shell script variable. I can use vget, but i donot want to make the full bootstrap.

The general answer to your question is that you cannot change the bootstrap level of a Drush command as a user; Drush has already specified the minimum bootstrap level in each command's command record.  Running a command at a lower bootstrap than it needs will cause it to fail.

However, in the case of variable-get, it looks like you are correct.  vget is set to use a full bootstrap, but it would probably work just fine with DRUSH_BOOTSTRAP_DRUPAL_DATABASE.  This could be classified as a Drush (performance) bug.

If you would like to help out here, you could submit an issue to the Drush issue queue.  Add DRUSH_BOOTSTRAP_DRUPAL_DATABASE to the variable commands, test it and post a patch, and the maintainers would be happy to commit it.

Here's what the record for variable-get would look like:

  $items['variable-get'] = array(
    'description' => 'Get a list of some or all site variables and values.',
    'arguments' => array(
      'name' => 'A string to filter the variables by. Variables whose name contains the string will be listed.',
    ),
    'examples' => array(
      'drush vget' => 'List all variables and values.',
      'drush vget user' => 'List all variables containing the string "user".',
      'drush vget site_mail --exact' => 'Show the variable with the exact key "site_mail".',
    ),
    'options' => array(
      'format' => array(
        'description' => 'Format to output the object. Use "print_r" for print_r (default), "export" for var_export, and "json" for JSON.',
        'example-value' => 'export',
      ),
      'pipe' => 'A synonym for --format=export. Useful for pasting into code.',
      'exact' => 'Only get the one variable that exactly matches the specified name.',
    ),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_DATABASE,
    'aliases' => array('vget'),
  );


Hide default value by view mode I have an image field inside the content type 'Article'. I have two view mode: "teaser" and "full". I have a view page ('Homepage') showing all 'Article' nodes using "teaser" view mode.

In the 'Homepage' view, I'd like to display a default image if the image field is not setted.
In the "full" view mode I'd like to hide image field if is not set.

It's possible to do that?

Here is what I would do.

Do not set a default image for your image field.

In views, instead of using a content: teaser use content: fields. Then in No Results Behaviour of your image field you put <img src="/link/to/image.png">

Then you create a "full" version using content: fields, which you don't do a No Results Behaviour.


Programmatically adding line items to Ubercart order Can someone please suggest how do we add line items to an Ubercart order in Drupal 8? When I look at the references in Ubercart module, I get this:

// Load line items... has to be last after everything has been loaded.
$order->line_items = $order->getLineItems();

I am already setting product details to the order. However when I set line items by above line of code, system doesn't allow me to proceed ahead and doesn't even show any error.

Thanks in advance for any help or suggestions.

The issue was I was assigning the value in order total manually from the product details, instead of using ubercart's $order->getTotal() , which defines line item initially. Hence, this worked for me to get the order generated after setting product and other payment details in order:

$order->total               = $order->getTotal();
$order->line_items          = $order->getLineItems();
$order->save();


How do I style a node page for a specific content type? I have a content-type "foo". As you know, you can look at such a node by using it's nid and going to /node/nid. I'd like to create 100% custom markup and CSS for this page.

I want code and files and only code and files. So, what I'd expect is a MVC architecture, meaning, that there's a template file to which all the node related data is passed and I can easily change the markup. But since Drupal isn't MVC at all, it somehow gets very complex and I absolutely don't get the architecture here. I'm not sure  can use one template only; if so what's the naming pattern?

Can someone tell me the cleanest and easiest way to create the HTML for the node page?

The easiest way is to create a new template file called node--[node-id].tpl.php, for example node--10.tpl.php

Then you just need to copy/paste your code from the node.tpl.php you have on your actual theme and change it like you want. For the CSS, the cleanest way I think is to add a custom class in your template high enough to be able in your CSS to target it.

You can have a look at this answer that explains the difference between node--[node-id].tpl.php and page--node--[node-id].tpl.php


How do I prevent Drupal from sending an email to the admin every time a new user is created I've inherited maintenance of a drupal 7 site from another group.  Currently, every time a new user account is created the admin is sent an e-mail about it.  The admin wants this disabled.

I've been unable to find what's sending the e-mail.  There's no workflow rule for it, and the Trigger module is disabled.  Admin Notify doesn't have any setting turned on for new users, and visitors do not require admin approval in order to create their accounts.

Some of the research I've done suggests that this is drupal core functionality with no settings attached to it.  If that's the case, how would I go about stopping it?  Any ideas on where else the setting might be for the e-mail?

Do the email sent to the admin have the link to activate the user's account?

If so, go to: example.com/admin/config/people/accounts

Check the REGISTRATION AND CANCELLATION paragraph (should be the 2°): if Visitors, but administrator approval is required is checked, every time a user create an account an email is sent to the admin to let him approve/refuse the user new account.


Comparing entity against previous entity in views Say my view lists people and their salaries using data from their profile..

Abby, 10000, O
Amelie, 10000, O
Alan, 15000, O
Ben, 15000, O
Bertie, 20000, O
Boris, 20000, O
Carl, 20000, O
Carol, 25000, O
Derek, 25000, O

How can I change the third column to an X when the salary changes?

Abby, 10000, X
Amelie, 10000, O
Alan, 15000, X
Ben, 15000, O
Bertie, 20000, X
Boris, 20000, O
Carl, 20000, O
Carol, 25000, X
Derek, 25000, O

I'm guessing I do it in hook_views_pre_render($view), but there are so many variables/objects in the $view, I don't know where to start.

I don't think it matters, but I'm using views_data_export to output this into a CSV.

Probably late by now, but have you tried using revisions? You can pull in individual fields that has any revision.


How do I create a landing page that can go to page--front? I have two pages, the intro page (page--intro.tpl.php) and the front page (page--front.tpl.php). When you type worldovercomers.church, the front page loads.

How can I set it so when the user visits the website the intro page loads instead (worldovercomers.church/intro)?

I also want to include a link that when clicked goes to the main site (page--front). How can this be achieved?

Please note that I'm a Drupal novice.

You should try the Panels module.

It has a "pages" feature that allows you to create pages from pre-existing layout templates that are included, or you can create and import your own layouts from .tpl files. Then you can dynamically add content to them (it stores the settings in the database, but you can use the Features module to store them in code).


acquia/solr/D7: indexing additional files outside of a node I'm trying to set up a way to index uploaded PDFs in such a way that a user can search for a term (foo) and get a list of all the nodes with fields that contain foo somewhere; and once they've clicked through to a page, they should be able to search for bar within the attached PDF and see a list of snippets along with a link to jump to that page in the PDF. In my research, I decided the best way to do this would be to write a module that splits the PDFs into individual pages with filenames that include the page number, index those new documents (along with the parent document), and build my "snippet" results from those new documents. So, for example, when I upload sample.pdf, I get the following folder structure:

content
 |
 +-- sample.pdf
 |
 +-- sample.pdf_src
 |  |
 |  +-- sample.pdf_1.pdf
 |  +-- sample.pdf_2.pdf
 |  \-- sample.pdf_3.pdf
...

That works fine, but where I'm getting stuck is indexing those extra files. For background, I'm using Acquia's Solr module (apachesolr_search) with the extra attachments module (apachesolr_attachments). Is it even possible to manually index those additional files I broke out? If not, are there any other ways I can get those files into the index? Maybe attach them to the original node where the user uploaded the original PDF? I just don't want to get into a situation where I have 800 attachments to a single node because the one PDF the user uploaded contained 800 pages.

If it were possible to get page numbers out of the original upload when searching for content, that would be the most ideal situation; however, my research indicates it's not possible. I'd be happy to be proven wrong, though.

Decided just to work within the Drupal framework rather than trying to hard-code something special. After I split the PDF, for each page I used file_save_data() to register the file in the file_managed table, then added the resulting file to the node in a separate file field:

$thisSplitURI = "{$splitURI}/{$finalFilename}_{$i}.pdf";
$thisSplitPath = drupal_realpath($thisSplitURI);
$file = file_save_data($contents, $thisSplitURI); // $contents is the value where the raw PDF contents are stored
$file->display = 1;
$node->field_split_pdf_pages[LANGUAGE_NONE][] = (array) $file;

Probably not ideal, especially when there's an 800-page document in there, but it gets the job done.


node_delete doesn't work! I am calling node_delete($nid) from inside a function callback that is called when the DELETE button is pressed, but the node is not deleted.  There is no error - it just doesn't work!  What can be going wrong?

In bhl_form_alter() I put:

$form['actions']['delete']['#submit']['0'] = 'delete_mem';

Then delete_mem($node) calls node_delete($node->nid).

I have also tried to figure out a way to use the default callback hook_node_delete(), but if I put a redirect there with drupal_goto(), the redirect happens, but the node again does not get deleted. drupal_form_redirect() doesn't work in this function because $form_state is not passed.

The first mistake in the code is how the additional submission handler is added. You should add it with the following code:

$form['actions']['delete']['#submit'][] = 'delete_mem';

If you want to be sure that submission handler is executed first, you should use the following code:

array_unshift($form['actions']['delete']['#submit'], 'delete_mem');

The second error is the argument declared for the form submission handler that, as shown in this documentation page, should be:

function delete_mem($form, &$form_state) {}

As consequence of this, if you defined your function as function delete_mem($node) and you call node_delete($node->nid) from that function, node_delete() doesn't work because what you are calling $node is really a form array, which doesn't contain the nid property; what you are passing to node_delete() is NULL, and the function doesn't delete any node. Eventually, NULL could be converted to 0, but there aren't nodes using 0 as node ID, and the function will not find any node to delete.
If you are using a Drupal development snapshot, you would get a warning about accessing a property of something that is not an object.

Supposing that you are altering the node edit form, the submission handler you are writing has access to the node object through $form_state['node']; the node ID can then retrieved with $form_state['node']->nid.

You can check the code executed from the default submission handler added from the Node module to the "Delete" button, which is the following one.

function node_form_delete_submit($form, &$form_state) {
  $destination = array();
  if (isset($_GET['destination'])) {
    $destination = drupal_get_destination();
    unset($_GET['destination']);
  }
  $node = $form['#node'];
  $form_state['redirect'] = array('node/' . $node->nid . '/delete', array('query' => $destination));
}

It uses $form['#node'] to get the node object, and $node->nid to get its node ID. Consider the note added in node_form() about $form['#node'].

  // @todo D8: Remove. Modules should access the node using $form_state['node'].
  $form['#node'] = $node;

This means that using $form['#node'] would not working anymore on Drupal 8 (or any future version), while $form_state['node'] would still work for Drupal 8 and any future Drupal version.

In this case, your submission handler doesn't need to call node_delete() as the function is already called from the submission handler added from the Node module to the "Delete" button. If you really need to delete information about a node that is being delete from a database table that your module uses, then you should implement hook_node_delete().

  I have also tried to figure out a way to use the default callback hook_node_delete()

hook_node_delete() is a hook that needs to be implemented. If your module is bhl.module, the function that needs to be written has the following signature:

function bhl_node_delete($node)

That hook is implemented when you need to delete data saved from your module in its own database table, where you save some custom data and the node ID. It is not required to delete a node, which a task already done from node_delete_multiple(), which contains the following code.

try {
  foreach ($nodes as $nid => $node) {
    // Call the node-specific callback (if any):
    node_invoke($node, 'delete');
    module_invoke_all('node_delete', $node);
    module_invoke_all('entity_delete', $node, 'node');
    field_attach_delete('node', $node);

    // Remove this node from the search index if needed.
    // This code is implemented in node module rather than in search module,
    // because node module is implementing search module's API, not the other
    // way around.
    if (module_exists('search')) {
      search_reindex($nid, 'node');
    }
  }

  // Delete after calling hooks so that they can query node tables as needed.
  db_delete('node')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('node_revision')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('history')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('node_access')
   ->condition('nid', $nids, 'IN')
   ->execute();
}

Inside the implementation of hook_node_delete(), you don't call node_delete(), or you cause an infinite loop. In fact, node_delete() calls node_delete_multiple(), which then invokes any implementation of hook_node_delete(), including yours that would call node_delete(), that would call node_delete_multiple(), which again would invoke any hook_node_delete() implementation, including yours.

As general suggestion, the functions defined from a module should always be prefixed from the short module name. In your case, if the hook function is bhl_form_alter(), the submission handler should be bhl_delete_mem().


Getting Views Rows Data in Custom Module I dont know if im over thinking this but im not making much progress with my function. I am trying to get the values from views rows in my modules for example if I was to use $row->field_name inside of a view.tpl file then it would show the output of that row, except I am trying to do it in a module. Ultimately I am trying to render the image style of the 1st image that loads from the view. This is what I have so far.

function custom_module_views_pre_render(&$vars){
    if($vars->name == 'front_page'){
        $vars->result[0]->field_field_image[0]['rendered']['#image_style'] = 'front-page-scroll';
    }
}

Update 1: I've attached a image of what I am trying to do seeing how when I use preview(); execute(); or render(); it makes the function stop working, actually it makes the whole site stop working. If I cant get to the field view result count which counts the the number a current node is then I can say if($views->view_result_counter == 1) then render just that node. The function would look something like this.

function custom_module_views_pre_render(&$vars){
    $views = views_get_current_view('front_page', 'page');
    if($views->name == 'front_page'){
         if($views->views_result_counter == 1){
            $vars->result[0]->field_field_image[0]['rendered']['#image_style'] = 'front-page-scroll';
         }
    }
}

Here is a image of what I am trying to do, Now I currently have the 1st image rendering as I want it to but it keeps rendering the image of each page instead of it rendering one time only.

Now as for my view is there any reason why execute or render wouldnt work? this is what my view looks like.

any suggestions?

as this site is not about php programming I will not go very deep into this. but what you are probably looking for is http://api.drupal.org/api/views/views.module/function/views_get_view_result/7

to render the view use $view->render();

further reference: http://drupal.org/node/342132


succesfully changed order regions in info file, but rendered html stays untouched Layout-wise I want 3 columns in this order: sidebar first - content - sidebar right. Since the region order in d7 is content - sidebar first - sidebar second I wanted to change that order in html.

If I remember well, all that's needed to change the order of the regions, is to do that in the .info file.

So I simply just put the content region between sidebar first and sidebar second so the info file has the following in it:

regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[sidebar_first] = Left sidebar
regions[content] = Content
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

When I go to structure -> blocks The result that I'm seeings is what I was aiming for; the content region is being replaced. Yet, when I go and check the HTML,The order remains content - sidebar first - sidebar second.

Goes without saying I cleared caches often.

the orders of your regions are probably defined in the page.tpl.php of your current theme. so you will have to change the order there, changing the order of your .info entries should (if any) only change the output from configuration pages.


Using panels and\or contexts to build simple blog w/ static menu My goal is to build a simple blog that has a vertical list containing a library of blog titles and then the "meat" of a selected bog entry on the left.  I want the library list to be static such that it is always there whenever the user selects different blog articles.

This seems to me to be somewhat simple but for the life of me, it's got me stumped.

Any help is appreciated - Thanks.

It is simple to do:

set up your panel as normal - include the 'block' of information you want visible in the section you want it
click on the settings icon and select Visibility: Add new rule:

This allows you to set the conditions under which that particular block of information will be visible. You can have it appear only on nodes of a particular type for example.


How can I create a table in which columns and rows get added dynamically? I want to create table with Tasks as columns and Users as rows.

Here is a sample of how such a table should look like:

------------------------------------
|       | Task 1 | Task 2 | Task 3 |
------------------------------------
| User1 | 30%    | 0      |        |
| User2 | Done   | 100%   |        |
| User3 |        | 100%   | 10%    |
------------------------------------

I want to do it in the following way.
When I create a new node with Node Type "Task" that has
title "Task XX..." and some description, then the new
column with "Task XX" label appears.

Users (User1,User2...) are just a group of drupal users.
So probably I need a new Node Type like "User tasks track".

And when a new "Task XX" appears, probably Node Type
"User tasks track" should be extended with a new field "Task XX".

I've checked a lot of modules (EditableViews, ViewsMatrix, QuickEdit,
Datatables, AjaxTable, Footable, FiledCollections, SlickGrids),
but I still can't see the whole solution.
If these modules can provide the described behaviour.
I can write custom module which plays with database, but I really don't
want to invent the wheel, if there is the solution somewhere out there.

Please help me with you opinion, any references, architectural tricks/advice.
Anything that can at least show me the directions to the solution.

I forgot that famous tagline from a recent president, but in French I would sound something like "Mais oui, c'est possible" ...

The question here seems like a variation of something I recently ran into, related to processing log messages. One of the challenges with recent log messages (watchdog), is that there might be quite a few PHP notices, warnings, and errors that are filling up your logs. So a good practice is to identify / address these problems in your site (which will reduce the required resources for your site also and will result in a faster site).

However digesting these messages is quite a challenge. That's why I've come up with my own "custom" report, as illustrated in this screenprint:

Within the "Report Execution Parameters" (collapsed in the screenprint above), I specify the search criteria of the log messages to be retrieved (like severity, User name, etc). And the red numbers are hyperlinks to get a drill down report of the specific messages for which I want more details (= to display the actual watchdog entries).

Some more details about the above table:

Think of the columns (with headers starting with "Msg Type:...") as your "Task XX". While each row (= different message) is like your "User1", "User2", "User3".
If there wouldn't have been any errors with (say) "Msg Type: Ajax" or  "Msg Type: page not found", then the corresponding column wouldn't have been created.
Some columns (like "Msg Type: Error" or "Msg type: PHP") contain a value for multiple rows.

Refer to my answer to "How to gets analyts and generate visual reports from sessions?" for more details about creating reports (tabular displays) as in the above screenprint.

Just in case anybody wonders "How did you do that?" (without checking out my answer in the above link): There's a module for it ... it's called Forena ... And the clue in this specific case is to use Forena to create a "Crosstab table".

Bottomline: no need to re-invent the wheel ...

Disclosure: I'm a co-maintainer of the Forena module.


Properly bootstrap drupal for standalone PHP file? This is what I have right now:

<?php
    define('DRUPAL_ROOT', '/var/www/clients/client1/web15/web');
    include_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
//  drupal_flush_all_caches();

    $users = views_get_view_result('userlist', 'uid_list');
    $i = 0;
    foreach ($users as $user) {
        $filename = 'sites/default/files/generated_pdfs/individual_pdf_report_' . $user->uid . '.pdf';
        generate_employee_pdf($user->uid, $filename);
        error_log('Generated ' . $filepath);
        $i++;
    }
    // create object
    $zip = new ZipArchive();
    // open archive
    if ($zip->open("sites/default/files/generated_zips/individual-reports.zip", ZIPARCHIVE::CREATE) !== TRUE) {
        die ("Could not open archive");
    }
    // initialize an iterator
    // pass it the directory to be processed
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("sites/default/files/generated_pdfs/"));
    // iterate over the directory
    // add each file found to the archive
    foreach ($iterator as $key=>$value) {
        $zip->addFile(realpath($key), $value->getFilename()) or die ("ERROR: Could not add file: $key");
    }
    // close and save archive
    $zip->close();
?>

I'm getting a bunch of errors from the above when run standalone. Works fine in my module. Some of the errors are:

Warning: Invalid argument supplied for foreach() in drupal_depth_first_search() (line 56 of /var/www/clients/client1/web15/web/includes/graph.inc).
Warning: Invalid argument supplied for foreach() in _module_build_dependencies() (line 229 of /var/www/clients/client1/web15/web/includes/module.inc).
Warning: include_once(sites/all/modules/views_bulk_operations/actions/archive.action.inc): failed to open stream: No such file or directory in views_bulk_operations_load_action_includes() (line 56 of /var/www/clients/client1/web15/web/sites/all/modules/views_bulk_operations/views_bulk_operations.module).

By far the easiest way to manage the bootstrap is to use drush php-script, alias scr.

file.php:

<?php
echo l('Link', 'path');

Cli:

drush @alias scr file.php

Output:

Link

This way you need to deal with nothing with regard to the bootstrap, drush will solve it entirely for you, and gives you the ability to use it easily across sites thanks to aliases. (Might even work on remote sites, though I haven't tried that)


Gmap does not work on iPhone I am using the Gmap module to display a map on the page; however, it works on the PC, but not on the iPhone.
I checked the iPhone debug console, and got the following error:

  Drupal.gmap [undefined] is not an object

Could anyone please suggest me the way to solve this problem?

So your solution hacks the module code. Do the community a favour and submit your change to the issue cue for the module so that everyone can share in your success or even better roll a patch for the authour to apply to the module code.


See my custom entity as a normal page in drupal 8 I created a custom entity with the drupal 8 console. Everything works well. However, when I am logged in as an administrator, my entity appears in an admin page instead of a normal page like for nodes.

In this case, the title and the edit links (tabs) are displayed in the gray bar of the administration.

How to make my entity appear as a node without the gray bar of aministration?

Thanks for your help.

Then you have probably defined an admin path to view the entity:

/src/Entity/MyEntity.php

 *   links = {
 *     "canonical" = "/admin/structure/my_entity/{my_entity}",

Change this to a non admin path:

 *   links = {
 *     "canonical" = "/my_entity/{my_entity}",


How to quickly create Drupal 7 Installation profiles / Distributions Dose anyone know how to make quickly and easy installation proflies for drupal 7?
Something like this 5 easy step tutorial but for drupal 7.

This really helped me.

How to Write a Drupal 7 Installation Profile http://drupal.org/node/1022020


View of taxonomy terms - add preprocess class I have a view showing taxonomy terms with an images field. I'd like to add a class .has-images if the images field is not empty.

I've done this before with nodes using preprocess, have tried something similar and have looked around for an answer though I can't seem to get it to work. Also where would the code go? would it go in a view.preprocess.inc file?

This is an example of node.preprocess.inc

function THEMENAME_preprocess_node(&$vars) {
 if(!empty($vars['field_images'])) {
    $vars['classes_array'][] = 'has-images';
 }
}

Any help would be much appreciated.

You should try hook_views_pre_render(&$view);
http://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7

Also you can write a template file to write extra css class with condtion. For this go to advance section and go for theming section and choose a template name.


drupal_add_js and url encoding In my module, I add javascript with a url parameter:

drupal_add_js(libraries_get_path('mylibrary') . '/MyLibrary.js?config=MY_CONFIG_PARAM');

When I view the HTML page source, the line loading the script looks like this:

<script src="http://example.com/sites/all/libraries/mylibrary/MyLibrary.js%3Fconfig%3DMY_CONFIG_PARAM&amp;nbbffw"></script>

The '?' and '=' are encoded. Trying to load this script results in an error, because browser can't find it (but if I manually decode it in the browser bar, it's found).

How to add javascript with a parameter, so that it won't get encoded?

Try this code

drupal_add_js(
  url(
    libraries_get_path('mylibrary') . '/MyLibrary.js',
    array(
      'query' => array(
        'config' => MY_CONFIG_PARAM
      )
    )
  )
);


Change the node edit link for a specific content type I want to be able to change the node edit link from node/[nid]/edit to my_custom_module/[nid] for just one content type. Which hook sould I implement?

I need this change to be applied to all the node edit links present on the frontend and backend of the site.

I tried implementing hook_menu_link_alter but this hook does not provide me any node-related data so I can not apply the link changes just to one content type.

You can use hook_node_prepare, Please check the below code which can help you to sort out your problem.

function hook_node_prepare($node) {
if($node->type == "somecontent type"){
    drupal_goto("/somepath..");
}

}


Javascript file attached via Drupal behaviours does not work occasionally I'm facing a weird issue where a JS file attached via the Javascript API does not work properly. I couldn't really pin down why it isn't working by the JS file consists of a few event listeners which get attached to DOM elements and it looks like this:
(function ($, Drupal) {
  Drupal.behaviors.basics = {
    attach: function (context, settings) {
      if (context !== document) {
        return;
      }

     initPublicationsAccordion($)
     initBackground($)
     initNavbarFix($)
     initMobileNav($)
     initAuthorsDropdown($)
     setTimeout(() => initCarousel($), 500) // this fixes it
    }
  };
})(jQuery, Drupal);

and the corresponding *.libraries.yml file:
global:
  css:
    theme:
      css/main.css: {}
  dependencies:
    - core/drupal
    - core/jquery
    - drulma/bulma
    - drulma/mainjs

...
mainjs:
  js:
    js/main.js: {}
  dependencies:
    - core/drupal

There are no errors in the console, but I noticed I can make it work by wrapping the functions in a setTimeout. I would appreciate if anyone has an idea?

You are firing your event on document context, which happens only once (basically same as old school $(document).ready()). But a major point Drupal behaviors is that they are fired every time when somehing is added to the DOM, even when added with Ajax. (core's  BigPipe might add blocks with Ajax, this module is enabled by default)
So instead of the one-shot
  Drupal.behaviors.basics = {
    attach: function (context, settings) {
      if (context !== document) {
        return;
      }
      ...do stuff

target the specific DOM nodes, e.g. if your carousel has a container

...

attach the behavior to its class:
  Drupal.behaviors.my_fancy_carousel  {
    attach: function (context, settings) {
      $('.my_fancy_carousel', context).once('init_my_fancy_carousel').each( function() {
        ...do stuff...

Also notice the .once('my_unique_identifier') part which makes sure your functions don't trigger repeatly on the same DOM node


How to grant userpoints to users who perform a login 5 days consecutively? I need to know if a user has performed a login, for example, 5 days consecutively. The reason for this is I want to award User points to them.

For example:

User A performs a login on Monday, Tuesday, Wednesday, Thursday and Friday. (granted 10 points)
User B performs a login on Monday, Tuesday, Thursday, Friday and Saturday. (no points)

I'm trying to do this with Rules but failed miserably. Any ideas?

Note: I'm trying to use Rules condition to compare my_last_login values against today's date with an offset of -1 days but it always return False.

Statistics module in the core would work in this case.


How to get my custom 404/403 pages to work with Bootstrap? I use this in my template.php for custom error pages:

  //custom 404 not found page
  $header = drupal_get_http_header("status");
  if($header == "404 Not Found") {
    $vars['theme_hook_suggestions'][] = 'page__404';
    drupal_add_css('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', array('type' => 'external'));
  }

  //custom 403 access denied page
  $header = drupal_get_http_header("status");
  if($header == "403 Forbidden") {
    $vars['theme_hook_suggestions'][] = 'page__403';
    drupal_add_css('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', array('type' => 'external'));
  }

And I have custom page--403.tpl.php and page--404.tpl.php (these don't exist as nodes)

And they work if it's non-Bootstrap theme, e.g. it works on Zen theme, but it doesn't work on Bootstrap theme. When you go to some random URL it just gives the default page not found error and doesn't load my custom pages.

And I don't get it why.

Also with Bootstrap theme you have to put your custom pages inside templates/system and put your custom functions inside page.vars.php.

You're using $vars instead of $variables (per conversation in IRC).


Make views slideshow responsive - remove inline styles How does one remove the inline hard coded styles of height and width from views slideshow? I'm trying to make views slideshow responsive.

I'm trying to make my slideshow responsive (no i'm not interested in flexslider or another slideshow module at the moment).

The flexslider module mentioned above seems great with it's mobile swipe support, but only images are supported and I needed videos slideshow, with overlays support. So I've added the following lines in my theme's CSS file and it worked:

.views_slideshow_cycle_main { width: 100%; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .field-content { max-width: 100%; width: 100%; }
.views_slideshow_cycle_main .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding: 0; }

With SCSS, it may be easily written as:

.views_slideshow_cycle_main {
  width: 100%;
 .views-slideshow-cycle-main-frame {width: 100% !important; height: auto;}
 .views-slideshow-cycle-main-frame-row {width: 100% !important; height: auto;}
 .field-content { max-width: 100%; width: 100%;}
 .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding:0;}
}

The overlays were added by views_slideshow_xtra_overlay.

Adapted from This discussion


How can I prevent Drupal from stripping/sanitizing anchor tag In a custom moudule I find email addresses  and return them as clickable mailto anchors on the page.

    $tableEntry['Email'] = l($emailAddress ,'mailto:'.$emailAddress , array('html' => TRUE));

    //Snippet of render array being used to create the table.. In a different function from the line above
    $rows = array();
    foreach ($tableEntries as $entry) {
    $rows[] = array(
        array('data' => $entry['Email']), //l($entry['Email'], 'mailto:'.$entry['Email'], array('absolute' => TRUE))),
    );

If i create the anchors before passing them into the table's render array, Drupal does something to strip away the html.
I have tried a whole bunch of argument options in l() and have also tried directly entering in HTML into l(), all the time the results get stripped. (I always check the generated email address to be sure it was first created successfully) .
The only way i am able to get an anchor to display as a link within the browser, instead of plain text, is to call the l() function at the last step of building the table render array eg. the commented out code. Any explanations are much appreciated.

Just for sanity's sake...from a 'Drupal' point of view, your code works fine. For example (without the loop),

$emailAddress = 'test@test.com';
$entry['Email'] = l($emailAddress ,'mailto:'.$emailAddress , array('html' => TRUE));

//Snippet of render array being used to create the table
$rows = array();
$rows[] = array(
    array('data' => $entry['Email']),
);

print theme('table', array('rows' => $rows));

Produces:

      test@test.com

You may have a custom implementation of theme_table() somewhere which sanitises the incoming cell data, but it's not being caused by Drupal core.

Or, it might simply be that you're trying to re-use $entry when it doesn't make sense to.

$entry['Email'] = l($emailAddress ,'mailto:'.$emailAddress , array('html' => TRUE));

...

foreach ($tableEntries as $entry) {

Are you sure you meant to overwrite the outer $entry array with the one in the foreach?


Path is not available in Views filter criteria I am creating a views with for node having fields Title,Author,Created,Path(page url). Now how can I add exposed filter for path(page url) so that user can find the specific page content in list.

Once I try to add Path in filter criteria it not visible it only available in fields section.

You can add path in Filters section if you installed views_url_alias module.

Please, take a look on screenshot.

I hope this helps.


Prepopulate from link in content only visible to users tagged within that content I have two content types, Parent and Child. Parent contains a list of tagged users which may create Child. Child contains the tag of the Parent.

On the Parent page I need a link, which is only visible to people tagged in it, to create a new Child with the Parent already tagged in it.

I know I need to use something like Entity Reference Prepopulate but my problem is that I can't figure out how to make the link.

This seems like it should be a simple thing to do but I can't for the life of me figure out how!

The requirement is that this should only use the UI and without editing any .php files as there is no guarantee that other devs will be able to code and allows easy visual recognition of what has changed.

Any advice would be greatly appreciated.

So here is how to do it.

Install and activate Entity Reference Prepopulate and enable it within the Entity Reference of Parents field in Child. You can now populate that field by  example.com/node/add/child?field_parents=[parent nid].
Install and activate Views PHP.
Create a new View without any pages or blocks called "Create new Child"
Click "+Add" and select "Content Pane"
Apply the following settings:

Filter critera

Content: Published (Yes)
Content: Type (= Parent)

Pane settings

Link to view: Yes
Argument input: From context>Node Content ID

Contextual filters (under advanced)

Content: Nid

Set Format - Show: Fields and then add a field - Global: PHP
In the configuration for Global: PHP, in the Output code section write:
<?php print 'nid . '">Create new child'; ?>. (N.B. You need title field/NID field added as well for the %data->nid to work, hide it if you wish)
Add a Global: PHP in "Filter Criteria" and add the following code

$uid = $GLOBALS["user"]->uid;
$node = node_load($data->nid);
$info = field_get_items('node',$node,'field_users');
$uids = array();
foreach($info as $user)
{
$uids[] = $user['target_id'];
}
return in_array($uid, $uids) ? FALSE : TRUE;
Save everything. In in Pages now, you can add this into Panels via "View Panes".


Customizing views output- rewrite output to show an image based on key value I want to use a views template to customize the output of the gender field on my user profile.  The gender field is a select list, and the key values are as follows:

f (female)
m (male)
o (other)

I created a template file, views-view-field--field-acc-gender.tpl.php.  I have the images saved in my theme's directory.  I can write an if statement to check against the key value, but how do I get the value of the field?  (This is probably a straightforward question, but I just learned about views templates today.)

I tried the following in views-view-field--field-acc-gender.tpl.php:

<?php
if ($output == 'M') {
  print 'male';
}
else if ($output == 'F') {
  print 'female';
}
else {
  print 'other';
}

However, my view still simply prints out M or F instead of male or female.

You should be able to access the data from $row array from inside the template file. So:

$data = $row->field_field_acc_gender;

// This may not necessarily be the correct structure of your field's data.
// So you may want to do print_r($data) or dpm($data) to see correct structure.
$gender = $data[0]['raw']['value'];

switch($gender) {
  case 'M':
    print('Male');
    break;
  case 'F':
    print('Female');
    break;
}


Image Repo and Uploader for specific role we'd like our staff to be able to add images to a content type whenever they add a new node to this specific content type. This is easily enough done with the image field. However, this requires a) for all of them to have the same images on their local computers, and b) it uploads multiple versions of the same image over and over again into the files directory. We just want one copy of each image on the site. Ideally, the staff would be able to select an image to use for the node they're creating from a repository somewhere on the drupal site itself (which then only keeps one copy of that image on the server).

It would basically work like a 1:M relationship in a database, with the image being the 1 and the nodes being the many.

Anyone know how this is possible? (preferably not using the IMCE module as that messes up my database configuration for some reason...)

You could use taxonomy easily enough.

Create a vocabulary called Node Images
Add an image field to the taxonomy term
Add all your terms (just name and the image)
Under manage display (for the term), set it up to only show the
image field
Under manage display -> full content (for the node), add the
taxonomy reference field and set the format to Rendered taxonomy term <- (requires display suite)

On the content type that your staff uses, add a taxonomy reference field with a dropdown or autocomplete.  When they create new content, they would be able to select the correct term/image to attach to the node.  You would just need to initially add all the terms/images to the vocabulary.


how to use Drupal menu system AND OR I'm trying to display all content labeled under my taxonomy terms with ids 1 and 3. Both terms work fine so that If I point my browser to
www.mysite/?q=taxonomy/term/1 or www.mysite/?q=taxonomy/term/3

But trying to use drupals built-in AND/OR feature using the urls below gives me a "Page not Found" error.

www.mysite/?q=taxonomy/term/1+3
www.mysite/?q=taxonomy/term/1,3

Any ideas?
thanks

Install the views module and then go to ?q=admin/structure/views.

You will find a disabled view created by default named "Taxonomy term" with an ID equal to taxonomy_term.

Enable this view; it will override the default taxonomy page. Configure the view to match your case, and click save.


Using Git to keep Core and modules up to date I'm looking for a way to use git to pull both core and modules. Let's say for example that I clone Drupal core from the Drupal git, and commit to my own git repo; then, I pull a bunch of modules, and also commit to my own git repo.

Is this even possible? Can I have sub folders within a repository that are checked out from a different repository? Can I still use Drupal to keep my code up to date? Perhaps I'm not really understand some git fundamentals.

You can done it easily with Git with the submodules. Every subfolder from yours sites/all/modules (for example) can be a submodule that clone the repo from drupal.org.