How to migrate taxonomy with hierarchy? I'm trying to create a hierarchical taxonomy from a perpared migration database table which looks like that:

ID | NAME | PARENT
------------------
 0 | FOO  |
 1 | BAR  |
 2 | LORE | FOO
 3 | IPSE | FOO
 4 | DOLO | BAR

It's a pretty messy data structure, but fact is there are parent and child terms in one table.

What I did so far is migrating the parent terms first. Now my custom taxonomy looks like this:

_
|_ FOO
|_ BAR

The migration code snipped I used to achieve this works like that:

$this->addFieldMapping('name', 'PARENT');

Until now everything works as expected!

Now, in a second migration step I want to add the child terms like that to my taxonomy:

_
|_ FOO
  |_ LORE
  |_ IPSE
|_ BAR
  |_ DOLO

What I tried is to add a hierarchical mapping to my migration:

$this->addFieldMapping('name', 'NAME');
$this->addFieldMapping('parent_name', 'PARENT')
    ->arguments(array('source_type' => 'name'));

But this does not work, the result is an unhierarchical list like that:

_
|_ FOO
|_ LORE
|_ IPSE
|_ BAR
|_ DOLO

Did anyone try to do something like this before? Any ideas? Thanks!

I had to migrate a nested Vocabulary from Drupal 6 to Drupal 7. My Strategy was:

Migrate the plain terms
Use the postImport() of Migrate-API to map the Parent-Relationship

public function postImport() {

// Get alle Terms from features_dd_private_contact_form_subjects
// Query zum Laden der Daten aus Drupal6
$source_query = Database::getConnection('legacy', 'legacy')
  ->select('term_data', 't');

// Join Terms with voab
$source_query->join('vocabulary', 'v', 'v.vid = t.vid');

// Join Hierarchy
$source_query->join('term_hierarchy', 'th', 'th.tid = t.tid');

$source_query->condition('th.parent', '0', '<>');

$source_query->fields('th', array());

$source_query->condition(
  'v.module',
  'features_dd_private_contact_form_subjects',
  '='
);

$source_query->fields('t');

$source_records = $source_query->execute();

foreach ($source_records as $source_record) {

  // Term-ID in destination db.
  $dest_tid = $this->get_destination_tid_by_old_tid($source_record->tid);

  // Parent-Tid in the destination.
  $dest_parent_tid = $this->get_destination_tid_by_old_tid($source_record->parent);

  $child_term = taxonomy_term_load($dest_tid);
  $child_term->parent = $dest_parent_tid;
  taxonomy_term_save($child_term);
}

}


How to access List type from an option set in conditions of the Rules module? Iam trying to access an option set(weight_options) within which we have a List type that holds weight , represented as below

 "entity" : [ "commerce-line-item:commerce-product" ],
 "field" : "field_weight_options"

field_weight_options is a option set within which we have a field_weight which is a List type that holds values like 1lb , 2lb etc

I was able to drill through till
commerce-line-item:commerce-product:field_weight_options:set-id
(which is a option set), using Data Comparison within the Rules module.

I am not able to figure out how to access the list field_weight and its values  Eg: 1lb , 2lb which are with in the option set using Data Comparison within rules module.

Any help/pointers?

These are the Rules Conditions you should use:

Entity has field "field_weight_options", which is the machine name of the field you want to check.
List contains item (for your field_weight_options, which is a list since it is a multi value field) and with the value (such as "2lb") you want to check for.

What is crucial in the context of this question, are these 2 Rules Conditions. Especially because of your "field_weight_options is a multiple value" (only "List contains item" is the Rules Condition that will do the trick ...).

PS: This answer applies to D7.


node API hook that can be used to alter fields before loaded by Views? I need to use a node API hook to alter some node content before it's displayed, in Drupal 7.

It just occurred to me though that if I used hook_node_view() it will not effect the output of a View that display's those nodes fields (right?).

I need to alter the fields in both the display of the node and the node's display in any views. Hopefull this can be done in one function, and not have duplicate code in both hook_node_view() and hook_views_pre_render() or function hook_views_data()whichever hook is used.

There are multiple ways in which this could be achieved:

Override the field itself in your theme with template_preprocess_field().
If the customization is more towards the markup, you can directly achieve that by overriding the field template.
Or you could just write a field formatter for this field, and select it in the field settings of the views and the view-mode (manage display) of your content type.


How to remove the caption in gallery caption module? I'm using Gallery formatter, how to remove the caption? But I want to leave the title and alt parameters.

You can copy file galleryformatter.tpl.php from Gallery formatter module to your folder theme. And remove some code line 28->35

<?php if (!empty($data['title']) || !empty($data['alt'])): ?>

                <?php if ($data['alt']): ?>
<?php print $data['alt']; ?>
<?php endif; ?>
                <?php if ($data['title']): ?>
<?php print $data['title']; ?>
<?php endif; ?>

          <?php endif; ?>

And clear cache.


How to theme a view with Zen? I have a view called 'Profile' that shows some user fields on my users' profile pages. I'm using the Zen theme and I'd like to change the way these fields are displayed.

As a total newbie in theming, I don't have a clue where to start. I read a lot about template files on the internet, but I don't know if that's what I'm looking for. I'm not asking for help with the CSS code, but for the place where I should put it.

Which files should I adapt?

When you go to the view, open the advanced section - near the bottom is a link called theme: information.

This lists all the potential files you COULD adjust to tweak the output of the view. Some are very generic, and some specific to the view you are looking at - in general if you only want to theme the one view, choose a file name with your specific view name in it.
Exactly which file(s) need to adjusted depends on the kind of tweaking you want to accomplish.
These files (i.e. views-view-profile--page.tpl.php ) would then be placed in the theme directory (i.e. /sites/all/themes/zen) unless the theme uses a sub-directory for template files - a simple look through should tell you where they are found for each theme.


Is there an advantage to Featurizing a view, over using Views' export? I've created a View in Drupal 6 with Views 2. If I want to get this view from my dev site to production, is there a compelling advantage offered by using Features over using the built-in Views export?

For a single View, there is no difference in functionality really. The view will be the same regardless.

I use Features anyway because it's makes it more conventient to organize multiple pieces of configuration into "features". I'm not aware that ctools offers any easy way of doing "This view with that panel and those three dependencies in one module". That is what features adds on top of Ctools.

It's worth mentioning that the Configuration module is an useful alternative that largely makes the configuration tracking easier. If you don't care about the features aspect of features, take it for a spin. (Thanks Clive for pointing this out)


Missing filter and sort criteria from views I'm following along a NodeOne video where it describes how to use the Views module. It looks like I'm missing a whole lot of filter criteria. Such as, all the "User:... " criteria, and the "Field:..." criteria is missing from the sort criteria menu.

This is a more or less fresh install of Drupal 7, and the only module I've installed is the views module, plus its dependencies.

How do I get those criteria to appear in the filter and sort menus?

I was running through that tutorial the other day too...

You need to add a relationship to the user (in the "Advanced" fieldset of your View), then the User: filters will appear.

I think the Field:... criteria are now called Content:....

I got the tutorial content working fine in quite a short space of time and if memory serves these are the only things that were different from what was stated in the video. The video uses a beta/RC version of views whereas it's now in full release, so there will be a few differences.


Upload new item (node gallery) link not showing with a user of different permission - Drupal 7 I created a new content type named "Home" which is connected to node gallery. I created a new role named "Home only" and gave permission. When I logged in as a user with role of Home only, I am not able to get the "Upload new item" link. Did I miss any permission. Please give me a solution.

I gave all "Home" Node level permission, File Entity permission, Filter permission,View the administration theme permission, Use the administration pages and help permission.

Please note: I am getting the "Upload new item" link when I logged as administrator. Also plupload is using for the bulk upload.

When I logged as "Home only" level user, I getting all the links as in the above image except "Upload new items"

Now it worked. Previously its was beta version of node gallery. Now I changed it into Node gallery-7.x-1.0. In the permission tab i had checked "Node Gallery API". In the case of beta version of node gallery these was not showing.


1 parent nodetype with 2 subnodetypes - show all subnodes in a viewlist Here is the situation: Using D7 and views 3.

I have made a nodetype 1.

I have two nodetypes 1a and 1b (node referenced to nodetype 1).

I want to show all nodes (1a and 1b) attached to nodetype 1 in a views-list when showing nodetype 1.

Contextual filters can only show one subnodetype correct.

Any suggestions?

You will have to use Relationships to pull in data from your other nodes. When you have defined your relations then you will be able to use these in each fields setting:

Relationships:
field_1a
field_1b

Fields:
// Uses no relation
// Will display title from content-type 1
Content: Title
// Relation field_1a
// Will display title from content-type 1a
Content: Title
// Relation field_1b
// Will display title from content-type 1b
Content: Title


Wrong order of entities, how to change that? I've created my first module which shows a list with nodes containing a certain term (like a taxonomy list, like usual), but the entities gets listed in an unknown way - I'm new to this and don't know - and I want them to be listed in alphabetical order.

How do I change that?

Code to retrive and print the entities:

function mymodule_cmp($a, $b) {
  $a = (array) $a;
  $b = (array) $b;
  return strcmp($a['name'], $b['name']);

}

$terms = taxonomy_get_tree(10,0,1);

usort($terms, "mymodule_cmp");

$counter = 0;

$result = taxonomy_select_nodes($tid, FALSE);

foreach($result as $nid) {

    $node = node_load($nid);

            // Prints all that is needed.
    }

Take a look at the Drupal API taxonomy_select_nodes(). You are missing the $order argument.

taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'));


Quicktabs Image in tab title I really need help with this.

I want to replace the link within the tab tile with an image. I can't find a solution for that. I saw some patches but I am not good at php and I did't got them right.

Can someone please tell me where I can find some tutorials about that?

Thanks.

I want to give some update regarding this. I tried different solutions and I need some advice.

Main goal is to add a different image to each tab. Empty tabs will be hidden.

Version 1. Field-Group module

I tried using that module and simple css with both class and id tab:

#vertical-tabs-list1 {
background: url('images/harta3.png');
background-repeat: no-repeat;
height: 64px;
text-indent: -9999px;
padding-top: 15px;
}

.vertical-tab-button.vertical-tab-button2 {
background: url('images/evenimente.png');
background-repeat: no-repeat;
height: 64px;
text-indent: -9999px;
padding-top: 15px;
}

This is working up to a point where is not working properly. If you hide empty tabs the following tab will take class and id of previous tab and that will mess up everything, because class and id are in li element and not in a href element like quicktabs.

Version 2. Quicktabs - Plausible solution

Contact

As you can see we have this id="quicktabs-tab-pagina_local-0" in

what I tried is simple css for each tab

#quicktabs-tab-pagina_local-0 {
background: url('images/media.png');
background-repeat: no-repeat;
width: 100px;
height: 100px;
font-size: 0px;
}

This option seams to work, even if we have hidden empty tabs.

Now I want to ask:

Is version 2 reliable, or I will mess up things in other places?
Is it possible to add id same way to field group? How?

Thanks

Probably best to add your own Quicktabs style and use CSS background images.

In a custom module

function MYMODULE_quicktabs_tabstyles() {
  $tabstyles_directory = drupal_get_path('theme', 'MYTHEME') . '/quicktabs';
  $files = file_scan_directory($tabstyles_directory, '/\.css$/');
  $tabstyles = array();
  foreach ($files as $file) {
    // Skip RTL files.
    if (!strpos($file->name, '-rtl')) {
      $tabstyles[$file->uri] = drupal_ucfirst($file->name);
    }
  }
  return $tabstyles;
}

CSS files in THEMEDIR/quicktabs/*.css will be read as a potential style

In your theme dir, add /quicktabs/image-tabs.css

Clear all caches

New style should be available, with accompanying CSS classes, add to your new CSS file.

Alternatively target the existing quicktabs classes with CSS.

Basic CSS background image tute here


Creating event lists using nodequeue, static pages and dynamic dates I'm new to Drupal, with some familiarity in other CMSes. I'm currently attempting to create a series of event lists, and have met up with a few issues. The number of modules available for the system are confusing my Googling, as terminology isn't uniform across the web and I'm picking up information for everything but what I want. From reading in StackOverflow, I gather it's a common problem with Drupal. I'm looking for recommended resources or perhaps more direct help - advice on whether to learn the system fully despite this being such a simple/small job would be useful as well.

In summary:

Need an online system to create itineraries, lists of events containing location information and dates that are specific to unique clients/users. Employees access the backend, assemble an itinerary and provide a link to customers with an appropriately formatted, final page/document. Drupal is a CMS that is potentially going to be used for a future website, and "location information" would be a duplication of web content - this system would make for a neat way of populating the website with content whilst the main frontend is being developed.

What I need

locations are created as static nodes (pages)
access the backend with an interface that allows for the selection of these location nodes and compiles them into an ordered list
each node, despite being static, is associated with a date field (start and end) specific to each ordered list
lists are unique and independent, using the same static content to fill description fields but able to be linked with specific date information

Where I'm currently at

locations are created as static nodes (pages)
the itinerary is a nodequeue, where an employee creates a new one, adds location nodes and can control the order without technical know-how
display using Views, using unique URL per list
trying to find a way to relate the unique nodequeue with a pair of dates for each location
been playing around with custom content types/custom fields, but don't know how to define the relationship between the static/dynamic content
using Date API for javascript calendar pop-up in these custom fields

Any help would be much appreciated! I've tried to word the concept clearly here, and am  looking for a friendly pointer in the right direction. Even so much as the appropriate keywords so I can find tutorials would help - been a few long hours of head scratching.

Thanks in advance for any help!

Yup, adding my solution for the collective knowledge!

Created each location as an individual page (appropriately classified by taxonomy/etc. for site navigation)
Assigned the desired custom fields, most ended being display hidden
Created new content type, "itinerary-location-reference", using module "Reference" (for D7)
Within this content type, assigned custom fields for dates/visitor name/etc.
One of the custom fields needs to be a node reference
Referenced the location

This creates two nodes that are linked...one is the static location content, the other a node containing date/personal information. I then added this overall reference node to my nodequeues. Done.

I can see a few issues down the road regarding number of entries into the database, but apparently Drupal's good for a few million, so fingers crossed!


Configuration Manager or hook_update() to enable modules In Drupal 7, if we wanted to push code to our environments enabling modules, we would call module_enable() in hook_update_N(). We no longer have that in Drupal 8, so how do we programmatically enable modules? Do we use Drupal 8's Configuration Manager or hook_update_N()?

A diff on the exported configuration yields this:

+++ b/cim/sync/core.extension.yml
@@ -10,6 +10,9 @@ module:
   config: 0
   contact: 0
   contextual: 0
+  ctools: 0

So it seems the module is enabled via code using Configuration Manager.
We're also working with the idea of this:

function mymodule_update_8003() {
  $modules = array(
    'ctools',
  );
  \Drupal::service('module_installer')->install($modules);
}

What is the correct method?

For site-specific changes, I would definitely go with using configuration deployments.

They have a very interesting advantage and difference to enabling modules in update hooks/through the API yourself. Config deployments can handle changed default configuration while installing the module.

A module might provide default configuration like views, settings and so on. They might also programatically do things during hook_install() that you want to customize (like configuring default formatters/widgets for fields they add) Configuration deployment allows you install a module locally, customize it and deploy the result as an atomic operation (as much as is possible) to production.

I'd only use the API and hook_update_N() if it's a functional change in a module, e.g. when a module is split up into a new one and/or has a new dependency that is mandatory for it to work.

Also note that I would advice against doing both in the same deployment. Update hooks might run code and create config that will result in differences on every run (like creating a new configurable field). Running config deployments first isn't possible anyway and will soon be prevented explicitly in core and running after might result in the deployment removing and re-adding configuration due to different UUID's.


/admin/modules and Views Edit pages take forever to load I recently noticed that two specific sections of my site are taking forever to load, /admin/modules and /admin/structure/views/view/{any-view}/edit. Before I disabled the PHP max_execution_time (only temporarily), it kept timing out at 5 minutes.

Now that the timeout is disabled, the mysql server is going away. I've seen a lot of suggestions that max_allowed_packet should be 100M+, so I set it to 500M for some ridiculously high value. Last time I hit that page had to have been ~15-20 minutes ago, and it's still just sitting there.

The only thing I have done recently to it was moving a TON of images into sites/default/files from another web server. (~ 25Gb)

Does anyone know why admin/modules and the View Edit pages are taking forever? It's only those two sections. The public side of the site is fine, the other admin parts are fine, it's just those two places.

I found more information on this and have fixed it.

I guess that when Drupal has enabled modules that are missing from the filesystem (this happened as we're using Capistrano to deploy and I didn't sync the two sites correctly), it recursively keeps calling file_scan_directory() trying to find the missing modules, and that causes the site to timeout.

References:

Avoid re-scanning module directory when multiple modules are missing

Drupal 7 speed issue: file_scan_directory called > 1000 times per page load

Used XHProf to see what the call stack looked like over the course of loading /admin/modules and found over 5,000,000 function calls. By contrast, any other page had about 30,000 ~ 50,000 function calls.


How do I turn off the add to cart message from Commerce site using Rules I finally got a duplicate cart rule to work in my Drupal Commerce site.  My "After item is added to cart" rule determines if there are duplicate sku's, if so, resets the quantity of that item to one.

When that rule is run, it posts a system message to the user saying the duplicate has been removed from the cart, but the original "Item has been added" message still appears, so the green, "item added to cart" msg appears and just under it, my "duplicate item has been removed" msg appears.

I want to turn off/not display that first "item has been add" message, when a duplicate has been detected.  Obviously the message would appear as normal when no duplication is found.

What is the simplest means of accomplishing this? Nothing I've tried thus far has worked.

default add to cart message:

{ "commerce_cart_add_to_cart_message" : {
    "LABEL" : "Display an Add to Cart message",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Cart" ],
    "REQUIRES" : [ "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "DO" : [
      { "commerce_cart_add_to_cart_message" : { "commerce_product" : [ "commerce-product" ] } }
    ]
  }
}

my stop duplicate rule

{ "rules_restrict_quantity_1" : {
    "LABEL" : "Restrict quantity to 1",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-line-item:quantity" ],
          "op" : "\u003E",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "commerce-line-item:quantity" ], "value" : "1" } },
      { "entity_save" : { "data" : [ "commerce-line-item:order" ] } },
      { "drupal_message" : {
          "message" : "Duplicates items are not allow.  This item has been removed from \u003Ca href=\u0022\/cart\u0022\u003Eyour cart?\u003E",
          "type" : "warning"
        }
      }
    ]
  }
}

You can't remove a message from the queue once it's been added via Rules, so you just need to reproduce the conditions in inverse from one rule to the next. In other words, you already configured the conditions in your custom rule to prevent the duplicate, so now put the opposite conditions on the rule that shows the normal Add to Cart message.


Developing Apps with Panopoly I'm developing a panopoly App for Services and case studies. I have added my required field and created the content type, added panels and views etc. Finally I created the feature and downloaded for the same. I have done this from the following Documentation. Creating Panopoly Apps. http://drupal.org/node/1704334

I have achieved step 1-4 and I am stuck on step 5 : Integrate the feature with Apps.

Please help to create the feature as an App. I don't have any server setup.

Thanks in advance.

You'll have to either create your own apps server using the Apps Server module or submit your app to an existing app server. In your case, you'll probably want to post on the Panopoly issue queue and ask about the process to do that; @populist will probably be the guy to answer your questions there.

Check out this post for more info on the Drupal apps scene:

http://chocolatelilyweb.ca/blog/drupal-apps-answer-plug-and-play-drupal-site-building


Points-based tasks: pledging and tracking I am a member of a social organization and run its Drupal 7 website. We will be starting a campaign in a couple of weeks to challenge members to pledge to accomplish certain points-based tasks (not related to the website), and want to track the pledges, completions, and rolled-up sums.

There are roughly 100 tasks, with different point values and descriptions. Tasks are individual: more than one member can pledge to do a task.
A member would sign up on a per-user page to complete certain tasks. The sums of a member's pledged tasks and completed tasks should be displayed on the per-user page, and there should be a summary of all members' pledged and completed points and tasks available as well.
A member needs to be able to return to his/her page to update pledges and completions.

I believe I can do something for this with Webform, but it may be somewhat awkward. I'm not sure I can do the per-member sums and the rollups easily. User Points might help a bit, but it's not really oriented toward this. I could write a module as well, but I'm  not sure I have time to do that. Suggestions for other modules or implementing this quickly are welcome.

There's a way to use Rules, Webform and Webform Rules together, by adding a number field with initial value 0 in your user fields. Every time user completes a task, validating a form submission, a value will be added to your field. That's the points field, which would be, in this case, unique. There is no sum in this case, but the field value will be automatically calculated by Rules.

Number field, your points field, should be available in your display, not in your user register form, with the right permissions.

That's what I'm thinking as a solution right now, if tasks are webforms. Not sure about awards or how to keep track of each completed task.

I hope that would get you started.


How to add product details to Drupal Commerce order confirmation email Default email that is sent when user completes the checkout process contains order number and other details. I want to include additional product details and product type in this email. How can I do that?

you can do that by using php code inside text message body.

$wrapper = entity_metadata_wrapper('commerce_order', $commerce_order);
    $line_items =  $wrapper->commerce_line_items->value();
    foreach($line_items as $line_item){
        $product = commerce_product_load($line_item->commerce_product['und'][0]['product_id']);
            echo "Product Title :".$product->title;
            echo "Product Title :".$product->type;
     }


Caching Drupal 7 using boost module and Varnish, yet still getting a "MISS"( I'm trying to do a little test, so I installed Drupal7 w/ following modules (expire, boost, varnish, purge, rules and token). I'm usingvarnish-3.0.4-1.el5.centos.x86_64 in front of httpd-2.2.15-29.sl6.x86_64.

I added following into my settings.php:

// Add Varnish as the page cache handler.
$conf['cache_backends'] = array('sites/all/modules/varnish/varnish.cache.inc');
$conf['cache_class_cache_page'] = 'VarnishCache';
// Drupal 7 does not cache pages when we invoke hooks during bootstrap. This needs
// to be disabled.
$conf['page_cache_invoke_hooks'] = FALSE;

and I set following settings for varnish module inside of Drupal7:

# drush -r /usr/share/drupal7/ -l XXXXX vget varnish
varnish_bantype: "1"
varnish_cache_clear: "2"
varnish_control_key: "XXXXX"
varnish_control_terminal: "XXX.XX.XXX.XX:6082"
varnish_flush_cron: "0"
varnish_socket_timeout: 100
varnish_version: "3"
#

yet I keep getting MISS

# curl -I XXXXX
HTTP/1.1 200 OK
Server: Apache/2.2.15 (Scientific Linux)
X-Powered-By: PHP/5.3.3
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Thu, 24 Oct 2013 14:42:21 +0000
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
ETag: "1382625741"
Content-Language: en
X-Generator: Drupal 7 (http://drupal.org)
Content-Type: text/html; charset=utf-8
x-url: /
x-host: XXXXX
Accept-Ranges: bytes
Date: Thu, 24 Oct 2013 14:42:21 GMT
X-Varnish: 1527289503
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: XXXXX
X-Cache: MISS

#

even though it seems like if I go to Configuration->Performance and then enable Caching, I'd end up with a HIT, yet Status Report would say following message (after enabling Caching) Boost will not function properly while Drupal core cache is enabled. Disable Boost or the core cache.

* UPDATE *

this is after enabling boost, as you see Cache-Control: IS in there, yet still getting MISS from Varnish(

$ curl -I http://XXXXX/node/1
HTTP/1.1 200 OK
Server: Apache/2.2.15 (Scientific Linux)
Last-Modified: Mon, 28 Oct 2013 15:53:48 GMT
ETag: "802449-1da7-4e9cf1b11461e"
Accept-Ranges: bytes
Content-Length: 7591
Cache-Control: max-age=1209600
Expires: Mon, 11 Nov 2013 15:55:46 GMT
Content-Type: text/html; charset=UTF-8
x-url: /node/1
x-host: XXXXX
Accept-Ranges: bytes
Date: Mon, 28 Oct 2013 15:55:46 GMT
X-Varnish: 1527308733
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: XXX.XXXXX.XXX
X-Cache: MISS

$

What am I doing wrong?

Pay attention to the Cache-Control header returned from Drupal:

Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0

If Cache-Control is set to no-cache, Varnish will respect it by default. Either you must force caching from within Varnish in vcl_fetch or (much better), make Drupal deliver the proper header (Cache-Control: public, max-age=X). The simplest way to achieve the latter is to enable "Cache pages for anonymous users" in Administration » Configuration » Development and also set "Expiration of cached pages". You can hard-code those settings using:

$conf['cache'] = 1;
$conf['page_cache_maximum_age'] = 3600; // 1h

You also may force the Cache-Control header by adding it explicitely using a custom module by implementing hook_exit. A reasonable save implementation looks something like this:

/**
 * Implements hook_exit().
 *
 * @see drupal_serve_page_from_cache()
 */
function MYMODULE_exit($destination = NULL) {
  // If the client sent a session cookie, a cached copy will only be served
  // to that one particular client due to Vary: Cookie. Thus, do not set
  // max-age > 0, allowing the page to be cached by external proxies, when a
  // session cookie is present unless the Vary header has been replaced or
  // unset in hook_boot().
  $vary_header = drupal_get_http_header('vary');
  $max_age = !isset($_COOKIE[session_name()]) || isset($vary_header) ? variable_get('page_cache_maximum_age', 0) : 0;

  if (drupal_page_is_cacheable() && $max_age && $destination == NULL && !headers_sent()) {
    drupal_add_http_header('Cache-Control', 'public, max-age=' . $max_age);
  }
}

Also note that due to the fact that boost will also add a Cache-Control header, you still need to introduce some VCL logic in vcl_fetch. The following fragment will force Varnish to still store pages in the cache, even when they were delivered using boost with Cache-Control no-cache:

sub vcl_fetch {
  if (beresp.http.X-Cached-By ~ "Boost") {
    set beresp.ttl = 1 h;
  }
}


How can I add a contextual filter with taxonomy term name as entity reference? I have a content type "award" which have a taxonomy (product) as entity reference.
I want to add a contextual filter by term name on my view. I tried to use a contextual filter on "taxonomy term name" but it's not working, looks like i'm doing something wrong
I added the field in advanced > relations, that way i managed to make a working filter on the taxonomy term name i wanted, but i need a contextual filter
here is the view :

here is the contextual filter configuration

The direct Product (which is a Taxonomy reference in your case) Contextual filter only works with term IDs, not their names. So you can make it work only if you choose the term ID in the validation settings.
To use the term name as the contextual filter you have to add the Relationship for the taxonomy reference field, which you seem to have done.
Now you can add the Term Name Contextual filter, from the Taxonomy term Category. (Remove the Contextual filter for the Product field that you currently have.) You didn't have the Term Name available under Contextuals before you added the Relationship. That Contextual will use the Relationship automatically.
When you add the Term Name contextual you will be able to set up the term name Validation, and you'll need to enter the term names in path arguments and in Views Preview field to test it.


How to set up menu with links to pages in different languages on multilingual sites? I have a multilingual site determining the language from the URL Path (www.sample.com/lang/page). I need a menu to have a mix of links to pages in both English and French. 99% of these are node pages, one or two are taxonomies. We do not have any translated content only localized. It doesn't seem to make a difference what Translation mode my menu is in (I've tried all three) the system always adds "fr/" in-front of every URL when I put the menu on french pages, even if that node id doesn't exist in french. I'm sure there must be a way to do this, but I can't figure out how... Here's a sample of what i am looking for in one menu:

About Us - www.sample.com/about-us (not translating to french, but want to link to it from french pages)
Contactez-nous -   www.sample.com/fr/contactez-nous ( node in french, not a translation of another page)
US Locations- www.sample.com/locations (not translating to french, but want to link to it from french pages)

I'm sure this must be possible, but I have no idea how to get there.

How about using "language neutral", or "Indépendant de langue" in French? That's an option you should have on the node "edit" form ("modifier" in French) for each of those 3 pages. And then combine this with creating a (single) menu link, in the appropriate menu of course.

That should make such link show up for both languages. That's how I always implement such pages, typically for pages similar to the ones you mentioned. Or sometimes in cases where some translation is still missing, and at least such page should be shown already in another language for which its content is available already.

FYI: I'm also using "determine language from the URL path").


How can I pass parameters to a block? Is it possible to programmatically pass parameters to a block?

Per the other answer, blocks are 'dumb' and don't have the ability to have arguments 'passed in'. They can, however, grab arguments from the context of the page, like node IDs, current user etc.

You have two 'easy' choices really:

Write your own block: It is pretty easy, if you can do a little PHP. Create a module and implement hook_block(). There are many examples on Drupal.org.
Use the Panels and/or the Views module: Panels allows you to create panes that can have all manner of variables and contexts passed in, BUT without a special theme the block will have to live in the content area, not a Drupal region; so it depends on your site, and where you want the block. Views can create blocks too, and receive arguments from the page URL, current user and also custom code via the Views PHP module. Views and Panels work together very well.


How can I render a view on user-profile.tpl.php that includes the user name as an argument in Drupal 7? In Drupal 7, on a custom user profile page (using user-profile.tpl.php) I would like to place a view that references all nodes of a specific content type that has that user as a reference. (The user may, or may not be an author of the node.)

use views_embed_view to embed a view:

$views = views_embed_view('VIEW_NAME', 'DISPLAY_ID');
print render($views);

The DISPLAY_ID is typically 'page' or 'block' depending on the displays you have setup in views.

You can build the view with a contextual filter to get all nodes with a user reference.

If you don't need to embed the view in the middle of your user profile you can just use a block output and show that block before or after your user profile.


Is there a limit on taxonomy hierarchy depth by default? Is there a limit on a taxonomy hierarchy depth by default? This question's answer states that the default limit is 9 due to database table structure, but I successfully nested 10+ terms in a vocabulary locally, so that doesn't seem to be correct.

I just posted an answer to a similar question at https://drupal.stackexchange.com/a/199247/6488 but if you are wanting it to be a sitewide default you would:

remove the if ($form['#bundle'] == 'MY_VOCAB') from
hook_form_taxonomy_form_term_alter()
Change the check against current_path() in the hook_preprocess_page()

Some clever person could turn this into a module!


Panels or Context module? Can I please get some input on the differences between the two?

I'm building a website where using 'context' is very important. After watching this video series about Page Manager by NodeOne, I feel that Panels 'context' and its ability to securely pass arguments to Views is very important. However, the Context module has a plugin that does a similar type of function called the View Default Argument From Context module.

I prefer Context module in most cases. I find it simpler and less heavy-handed than Panels, which takes over entire pages. A good use case for Panels is when site admins will be rearranging landing pages themselves or for sites with a lot of unique layouts.
I pick between Panels and Context for a given site when evaluating wireframes or designs. In some cases it makes sense to use both.

I can usually handle the Views arguments I need within Views itself (often by setting the default argument) and don't need the Panels side to do it.


Will a version 6.x module work in v7.x? Is it possible that an older version of a module works when it has not been upgraded to 7 or is it a lost cause to try?

The module versions must match the core version to work. Drupal 6 modules will not work on Drupal 7.


Contextual Filters for a Block on a Page I am trying to figure out how to create a page with dynamic content within a block.

For example, a simple "About Us" page may have sub pages of "Contact," "Blog," "History," "Locations"

I would like the Page to remain the same, but only the content within the block change.

So, assuming that from an expanding menu you have the choices noted above.  When you click on the "About Us" menu option you get:

About Us

Picture_Default
Text_Default

Now, if you click on the "History" sub menu, you get:

About Us

Picture_Default
Text_Content_Default

History

Text_Content_History

Thus far, I have created a page with the static "About Us" content.  I created a Views block with a contextual filter based on Node ID.  I also configured the blocks to display only on the about and about/* pages.

When I go to domian.com/about I get the default page.  (That works)
If I go to domain.com/about/history, I get a "page not found error" where the static content should be and the correct sub page.

I have been searching for this answer and I am sure it has already been answered, but I am not sure if I am using the right terminology to bring up the relevant results.  If anyone could point me in the right direction, I would greatly appreciate it.

Thanks!

First create a taxonomy whose terms will be those 'contact', 'blog', 'history', 'locations'.

Then create a views page with contextual filter based on term id and set path as about/%


drupal 7 views structure: Different nodes should collect different (term) lists I think I can solve this with views, but can't find a good solution.

I have the nodes: vegetable, fruits..(one content type).
Then I have different nodes of vegetables and fruits: carrot sort 1, carrot sort 2.../ salad sort 1, salad sort2.../ apple sort 1, apple sort 2...

The goal is this structure:

node vegetable:
-text-
-headline 1: carrots-
-list of different carrots-

-headline 2 salad -
-list of different salads-

node fruits
-text-
-headline 1: apples-
-list of different apples-

-headline 2 berries-
-list of different berries-

Have I built for carrots, salads, apples, berries... separate views? Maybe there is one better way?
How can I collect this seperate views on the nodes "vegetable" and "fruits"? I tried it with eva, but (sure) I got on both of my nodes the same result with all fruit and vegetables together.

Any ideas?
Thanks in advance

Yes, this is absolutely doable with one View.

What you are looking for is under Format: Unformatted list (or whatever your view style is) | Settings.

Click Settings and set a Grouping Field based on the field you would like to group - "content type" in this case.


theming a CCK input form How do I theme a CCK input form?
I tried the approach given in this page, but it is not working even after I clear the cache.
Here are the steps.

Suppose your content-type is: "account_registration" and you theme is "bluemarine".

I edited template.php and added this code:

function bluemarine_theme($existing, $type, $theme, $path) {
  return array(
    'account_registration_node_form' => array(
      'arguments' => array('form' => NULL),
      'template' => 'node-account_registration-edit'
    )
  );
}

I created node-account_registration-edit.tpl.php:

<?php
  $form['buttons']['submit']['#value'] = 'Done';
  $form['buttons']['preview']['#access']= FALSE;
?>

I cleared cache and edited a node, but the above changes are not showing up.

Your steps are right. I tested it on my local environment, and it works.

For example, for the content type "companynews", add the function to the template.php:

function garland_theme($existing, $type, $theme, $path) {
  return array(
    'companynews_node_form' => array(
      'arguments' => array('form' => NULL),
      'template' => 'node-companynews-edit'
    )
  );
}

Create the node-companynews-edit.tpl.php file and put the test code.

<?php
  echo 'it works!";
?>

Clear the cache, and access http://example.com/node/add/companynews: it shows "it works."

PS: You can also use hook_form_alter() to alter the form, and then use CSS to style it.


How do I automatically load a bunch of JS/CSS from sites/all/libraries without hook_library? My question is simple.

Is there a straightforward method to load a library e.g. ibeginshare (it contains 2 css, an images folder and 1 js) which I copied in sites/all/libraries to use it in my module?

I have created a module that implements hook_block_info and hook_block_view and I want to load this library in its hook_init.

Is it mandatory to use hook_library and define there everysingle file then call it via drupal_add_library? I am confused. What if I have dozens of js/css files ? What if I don't want necessarly to share the library with other modules?

NOTE
I managed to load the file like this:

METHOD 1

function MYMODULE_init() {
  drupal_add_js('sites/all/libraries/ibeginshare/share.js');
}

I would like a more elegant way so I tried:

METHOD 2

function MYMODULE_init() {
  drupal_add_library('MYMODULE', 'ibeginshare');

}

/**
 * Implements hook_library().
 * @return string
 */
function MYMODULE_library() {
  $libraries['ibeginshare'] = array(
    'title' => 'ibeginshare',
    'website' => '',
    'version' => '1.2',
    'js' => array(
      'sites/all/libraries/ibeginshare/share.js' => array(),
    ),
    'css' => array(
      'sites/all/libraries/ibeginshare/share.css' => array(),
    ),
     'css' => array(
      'sites/all/libraries/ibeginshare/share-print.css' => array(),
    ),
  );

  return $libraries;
}

this loads all libraries but the plugin doesn't initialize. I wonder why.
I think will work if I add a weight property in the hook_library but anything I tried didn't work.

Assuming you are on Drupal 7, drupal_add_library() will do just that for you. From the function's API page:

  Adds multiple JavaScript or CSS files at the same time.

  A library defines a set of JavaScript and/or CSS files, optionally
  using settings, and optionally requiring another library. For example,
  a library can be a jQuery plugin, a JavaScript framework, or a CSS
  framework. This function allows modules to load a library
  defined/shipped by itself or a depending module, without having to add
  all files of the library separately. Each library is only loaded once.

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_library/7

Note that you first need to define and register the library with hook_library().

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_library/7


Browsing private and public files in IMCE I have set up a public and a private file location (/admin/config/media/file-system).
The private file location is not under the Drupal directory ( it's /opt/private_files ).
I have set the "Default download method" to "Private local files served by Drupal."

I have configured a profile for IMCE ( /admin/config/media/imce ) called "User-1"
with a "Directory Path" of {root}/. "Including subdirectories".

I have assigned this profile to the role "administrator" under "Role-profile assignments" for both "PUBLIC FILES" as well as "PRIVATE FILES".

But when I access IMCE directly using mydomain.com/imce I only see the private files.

How can I switch or access the public files ?

While writing this question I found it:

You can access the public files like this:
mydomain.com/imce/public

and the private files:
mydomain.com/imce/private


Display node author picture through tpl file I am writing my custom node--blog.tpl.php for my Drupal7 based site. I want to print the author image of the blog so in my tpl file i include the following:

$user = user_load($user->uid);
  print theme_image_style(
                array(

                    'path' => $user->picture->uri,
                    'attributes' => array(
                        'class' => 'in-blog-user'
                    )
                )
            );

However, it does not display any image and i get a error as :

The requested page "/sites/default/files/styles//public" could not be found

What am i doing wrong?

Regards

PS: my pictures directory is "pictures"

The following lines did it:

$user = user_load($uid);
print theme('user_picture', array('account' =>$user));


Add attributes to options elements in a select box I am working with a Drupal 7 site; I have a vocabulary setup with an additional text field. On one of my content-type nodes, this is rendered as a drop-down select box with all the terms under that vocabulary. However, I would also like for the additional vocabulary field to be included as a data-country attribute. It is rendered rendered as follows.

<select id="..." name="..." class="...">
    <option value="145">UK8</option>
</select>

I'd like it to be rendered as follows.

<select id="..." name="..." class="...">
    <option value="145" data-country="United Kingdom">UK8</option>
</select>

Is this possible?

Unfotunately there is no way to do it using Form API. You need to involve some theming. Please check the following answer:

https://stackoverflow.com/a/9264589/2620782


Which module(s) should I use to create a customer support section? I've got a site where I need to get a customer (not client) support system set up. Support Ticketing System, unfortunately, is geared towards client support. I think Storm is too (it's huge, in any case).

The way I see it, I've got a few options:

Set up a different installation of Drupal entirely and use something like OpenAtrium or Drupal Commons for the support area. OMG overkill. Plus I'd like to just have it be a coherent part of my current site, same theme and shared logins and all that.
Patch Support ticketing system, or Storm, or whatever module I wind up using.
Use CaseTracker + Mailhandler to get a simple system, but I'll probably wind up still needing to do an amount of configuration to get it working.
Give up and use something like Trellis Desk on a subdomain.

One thing that maybe makes my search a little harder is that I'm adamant about having inbound email integration. The same way that we do, customers want to email an address and get a support ticket created. If this functionality isn't there, they'll send an email.

See Similar Module Review page and choose the one that works best for you.


Stopping Drupal 7 spammers registering at mysite.com I have a new Drupal 7 site at mysite.com (address changed) - a CentOS 5.5 Linux machine in my full control.

By reading registration mails (they run through my Gmail account) I've noticed, that Drupal spammers seem to refer to my site via the address forum.mysite.com. Since any requests to a subdomain.mysite.com are redirected by my hoster to mysite.com, this works for them.

I wonder, if anyone has noticed same pattern (seems to be some common spammer tool behaviour) and what have you done? I'm thinking of using mod_rewrite to block access to forum.mysite.com, but maybe there is a better way? (Because I'm not sure if that spammer tool will go away if I close access to forum.mysite.com).

I've also thought of maybe changing my httpd.conf somehow:

NameVirtualHost 11.22.33.44:80

<VirtualHost 11.22.33.44:80>
    DocumentRoot /var/www/html/mysite.com

    ServerName mysite.com
    ServerAlias mysite.com *.mysite.com

I'm not asking about Mollom or Captcha modules, because they seem to be not-up-to-date for Drupal 7 yet. And the spam users aren't a too big problem for my site anyway, because it has a card game embedded at the front page and I have a cron job deleting users not playing that game.

There is Honeypot as well

  Honeypot uses both the honeypot and timestamp methods of deterring
  spam bots from completing forms on your Drupal site

Usually, forms take at least a few seconds to fill out when a human is entering data into them—especially surveys, user registration forms, etc. Spam bots try to fill out as many forms as they can in as little time as possible, so they will often fill out a form within a couple seconds at most. The Honeypot module requires at least 5 seconds to pass (by default - you can adjust this too!) before a form can be submitted.

Alternative modules

There are many spam-protection modules on drupal.org, some of which have more or less robust methods of dealing with form spam. Some of the most used and recommended include:

Mollom - Offers spam protection through their premium service.
CAPTCHA - A simple image-based CAPTCHA builder.
reCAPTCHA - Implements reCAPTCHA for image-based CAPTCHAs.
Hidden CAPTCHA - Similar to this module in it's effectiveness.


Hide the Password tips How can I hide those password tips???  You know,when the enduser tries toregister and as soon as he clicks on the password field the following messages appear:

To make your password stronger:
•Make it at least 6 characters
•Add lowercase letters
•Add uppercase letters
•Add numbers
•Add punctuation

Simple CSS "display:none" won't do the trick here.

I still want to keep the password strength meter.Just need to get rid of the Password tips messages.

You can do it via CSS, just add the !important:

.password-suggestions {
  display: none!important;
}

Another option is to copy the modules/user/user.js file to your theme, add it to .info file and edit it the way you want.


How to send email in drupal I have drupal site in that ,i want to send a email to charities when donor post a donation..,and i want to send a email notification to charities,so how i send email using drupal7

$message = array(
  'to' => '"'. addslashes(mime_header_encode('new donation')) .'" <test@example.com>';
  'subject' => t('Example subject'),
  'body' => "Hi user! a donor added a new donaion! So please     check the site for more infomation!
Thanks,
",
  'headers' => array(
          'From' => 'test@test.org',
          'MIME-Version' => '1.0',
          'Content-Type' => 'text/html;charset=utf-8',),
);

drupal_mail_send($message);

First you must enable the following modules:

1. Mailsystem module  http://drupal.org/project/mailsystem
 2. Mimemail module http://drupal.org/project/mimemail (it contains the mail actions and sending mail function) or you can use htmlmail module  http://drupal.org/project/htmlmail
 3. Rules module http://drupal.org/project/rules

After that you will do some steps:

1. Create new rule in admin/config/workflow/rules/reaction/add and select the "React on event" is "After saving new content".
 2. Add a condition. Choose Node (Content is of type) for condition and choose your custom content type in the "Content types" list box.
 3. Add another condition.  Choose User(User has roles()). Choose data selector is "node:author" and choose the role of donor.
 4. Add the action. Choose System (Send HTML email). You'll change the To, CC, subject, content here.
 5. Try to test that.

Be sure that you can send email using your system. If you use the htmlmail module. It will have the send test email in its setting.


Ubercart external file download I am using Ubercart 7.x-3.2 on Drupal 7.

I am trying to sell files on my new website using this ecommerce system.

How can my users download files from an external website when they have paid for it?

I am trying to re-direct them to the website that actually provides the files

Thanks

Just a couple of ideas:

Alter the email template to include the external link to the purchased files.
Create a tab on the user profile with the links of of the files on the external site.
Create a module to allow the default "File download" module on Ubercart to link to external files and not only to upload ones.

Other readings:

Creating an E-Commerce Site Using Drupal & Ubercart

Selling Digital Goods (Mp3's, Photos, Movies, etc)


In views, add class depending on the user input in a checkbox. I need to add a class to a field of views depending if the user wants to have an overlay on the image or no. We need to use a checkbox for the user to input if it needs the class or no.

Create your boolean field (my case the name is field_no_overlay),  The checkbox should have the values for the classes you want to use and apply to your field.

In the views, rewrite your value .
Create the style for each class.


Printing taxonomy terms in node.tpl I am trying to print taxonomy terms using this code:

<?php foreach ((array)$taxonomy as $item) { ?>
<a href="<?php print base_path() . "taxonomy/term/" . $item->tid; ?> "class='tags'><?php print $item->name ?>,
<?php } ?>

It works fine if I put in contemplate, however it doesn't in the full node (node.tpl.php), the tags are empty in the full node. Can any one tell me what is the reason for this and how to fix this?

First verify that the $taxonomy variable is available and populated in your node.tpl.php file. ...

EDIT:

Your accessing the values in your $item variable like it is an object but your casting to an array. Try accessing as an array:

 <a href="<?php print base_path() . "taxonomy/term/" . $item['tid']; ?> "class='tags'><?php print $item['name'] ?>,


Modules and performance I know that disabled modules do not effect performance. I also know that typically the number of modules you have enabled will effect the speed of you site. One individual on Drupal.org said you should never have more than 40 modules enabled. I found this strange because I would assume some modules are more intensive than others.

Is it simply the number of modules that somehow effect performance, (because the hook is always called), or is it really dependent on what you are doing in the module?

It depends on the module.

You can create a module which has a simple info file and a blank module file, compare that to views which has loads of file and implement lots of hooks and create it's own as well. Obviously this requires more memory than a blank module.

Performance depends on a lot of factors. A module can use a lot of memory but not slow the side down much while the reversed can be true as well. Usually the bottleneck is r/w to the database. A single bad query can take seconds to perform, most tasks in code is not that slow. Iterating over a lot of objects and munching data can, however, take a lot of time.

So it's hard to say how a module will effect performance, but it's always a good idea to limit the amount of modules used when possible. I haven't heard of a thumb rule though and to be able to make one, you would need to know the hosting environment.


How to sum value of a field of all entries in a View? I have a view that displays nodes. These nodes have a field and I need to sum all values of this field for all entries the view is "displaying"(not only the currently visible entries/current page but all entries that match the current Views filter).

So all I want is to add this information into the Views template file. So I have the view object available. I was trying to get rid of the pager so I could get all results but without any success. I was able to re-run the query and everything I needed beside excluding the pager. Any idea how to do this? I tried to unset the pager, change it to another module('none'), manually set offset, limit and such but still no success.

Though I have never had this requirement but your question look interesting & I did some googling.

I found two related modules. I think you should try them & see what they offer.

Views Calc
Views Aggregator Plus

Note :- This is not an exact answer but helpful for these kind of situations :)


Drupal 7 Site Structure - Moving From Wordpress I need a little advice or guidance on the structure of Drupal 7. I have used Wordpress for a number of years and I know it very well. Moving to Drupal 7 has got me a bit confused if I'm honest. Take an example of a news page which may have a description and possibly an image at the top then afterwards gives a list of news posts.

In Wordpress (including the Magic Fields plugin to create custom fields) I would create a news page type and news post type. Each would have there own template file. In the news page template file I would output the fields of page then call the Wordpress loop which would give me the list of news posts.

In Drupal 7 I understand that I would create two new content types news page and news post. I would also have two template files - page--news-page.tpl.php and page--news-post.tpl.php. What is the best practise for getting a list of the content type "news post" (list of nodes)?

I've done some reading on this and looked into views. If I create a view to do this, would I set it to a block then call that block within my "page--news-page.tpl.php". Or is there something similar to the Wordpress Loop?

I understand you can create a view as a page but then I would not be able to have fields specific to that page - like the description and image.

Views allows to add custom text (with a format, so it can contain html) before and after a view. This could be a possible option.

Alternatively, if you for example want multiple news pages (kind of like news categories although taxonomy might be a better option here), have a look at the EVA project, which seems to be the successor of Views attach. This allows to add a Views to a node (or another entity like a user).

To assign news items to a specific page and only display it there, you could add a node reference field to the news item node type and then pass the node id as an argument to the view (EVA supports that according to the project description). But again, using taxonomy might be a better option for a categorization like this.


Empty lines in index.php file I had my Drupal 6 running for 2 yrs now. Suddenly it started to give parse errors on index.php page. I opened the file and saw that there were 100-200 empty lines after php closing tags. There is no chance that some one can have changed the file as access is with me only. What may be cause for this? Does any changes in server like upgrade of php version may cause this. I haven't changed the index.php file and it was running perfectly fine till date. The website is hosted on some other server.

If your index.php file is different from the default one, then it has been changed from somebody.
Updates to modules don't alter the content of that file. If there is a module that tries to alter the content of index.php, that is not the correct behavior for that module.

I would check that the permissions of the system user used to run the server, and PHP, don't allow it to alter any file contained in the Drupal root directory, and in its sub-directories.

In Drupal 6, the content of index.php is the following one. It is 39-line long, it includes an empty line after drupal_page_footer();, and it doesn't have any closing tag (?>).

<?php

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * The routines here dispatch control to the appropriate handler, which then
 * prints the appropriate page.
 *
 * All Drupal code is released under the GNU General Public License.
 * See COPYRIGHT.txt and LICENSE.txt.
 */

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

drupal_page_footer();


Installing new module I have downloaded and installed Drupal 8. The first thing I need to ensure when I create articles URL is automatically generated. In Wordpress this comes by default. But it appears not the case for Drupal.

I searched and found Pathauto (https://www.drupal.org/project/pathauto) will do what I want but facing difficult installing it. The page https://www.fastcomet.com/tutorials/drupal8/module-installation shows a tab List with button +Install New Module but on my system when I visit http://localhost/admin/modules I don't see the tab List or +Install New Module.

What could I be missing?

If you don't have this button, try to enable the module Update manager.
Maybe this makes the button show .. What backend theme are you using ?

Here's the path to the module installation page: http://localhost/admin/modules/install


Print out recaptcha webform verification I created a webform-form-230.tpl to readjust the webfrom layout.

    <?php print drupal_render($form['submitted']['name']); ?>
    <?php print drupal_render($form['submitted']['e_mail']); ?>
    <?php print drupal_render($form['submitted']['subject']); ?>
    <?php print drupal_render($form['submitted']['date']); ?>

    <?php print drupal_render($form['submitted']['message']); ?>

<?php print drupal_render($form['submitted']); ?>
<?php print drupal_render_children($form); ?>

I added recaptcha module.
How do I add recaptcha script in it?

You can use this code for adding in temlate.php or in custom module for adding captcha.

if (strstr($form_id, 'webform_form_id')) {
        $form['my_captcha_element'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'image_captcha/Image',
        );
    }

Also refer https://www.drupal.org/node/1254710 link.

One module is there you can check CAPTCHA Webform Bridge.
This is a simple module that automatically set (or unset) CAPTCHA challenges to webforms.


Redirecting %20 Based URL to Non %20 based URL I have a URL suppose http:www.domain.com/somepath%20%20

When i open the above URL, it exist with both URLs http:www.domain.com/somepath and http:www.domain.com/somepath%20%20

I would like to know how can I redirect %20 based URL to Non %20 based URL

P.S I have made this page using Panels.

I would check the alias on the page to see if two trailing spaces exist. That's where the %20 typically comes from. %20 is an HTML encoded space character.

In the meantime, you can handle multiple links to one page using Global Redirect.

Best to get that in so your site is not penalized by search engines.


Uploaded file not shown in custom content type / Image not attached to content type In Drupal 7, I am trying to upload an image that belongs to a custom type.

I click the Browse button, choose the file and upload. Until there, all seems to work well.

However, when I click next, instead of the add alt, title and text, I get only a screen that says Destination *, and with a Previous and Next buttons, as shown below. The save button is never displayed, and the image is not shown.

However, the image is there if I check the files through the admin, moreover, all goes well If I add the image through the file/add, it is just in the custom type that I get the error.

I am logged in as an administrator and I have all the permissions checked in Media and File Entity

My files folder permissions are 755, and the javascript console shows:
'Attr.nodeValue' is deprecated. Please use 'value' instead. in jquery.js

Resource interpreted as Script but transferred with MIME type text/html: "about:blank" in
browser?render=media-popup&types[]=image&activePlugins=&enabledPlugins=&schemes[]=public&schemes[]=…:92 (anonymous function)

Thanks in advance for your help.

Update, this doesn't work with Image widget nor Media Browser widget. Same site works in PROD, I suppose it is something with the file system settings?

These fixed it:

-I changed the content type to image instead of media browser.

-Reviewed the permissions for file and this particular content type.

-Changed the field display of the content type


In a manually created menu, when a taxonomy term is a parent with children, the children never display. Bug? I manually created a menu where each parent term is a taxonomy. so:

Menu name:cars

Path: cars

Note that 'cars' is a path auto generated url for taxonomy/term/3.  I thought you could only put nodes here, but this saves instead of giving the usual error when the path is not available.

Each one of these parent items has 1 level of children. Or, should at least.

In the Structure > Menu view, you can easily see the menu structure with parent and children.

however, when this is rendered as a menu block, only the parents are displayed. Is this because the Parent is a taxonomy term and not a node?

One of the reasons I think it may be a bug is that if you look at the source code the html shows 'collapsed' as an li class, indicating that it knows it needs to have children here. The second reason I think this is a bug is that if I change this to node/(number) then everything works fine.
Anyone know a solution to get this working?

Have you tried editing the parent menu item and enabling the 'Expanded' checkbox? This module may also come in handy: http://drupal.org/project/menu_expanded

Keep in mind that in many themes, the stock menu for primary links / secondary links is not a multi-level menu and so even if expanded renders the child items in HTML, they may not render properly in the actual menu. If this is the case, you may wish to look at implementing a menu block with one of the menu modules such as: http://drupal.org/project/superfish


How do I limit the allowed taxonomy terms basing on the content type? I have two different content types, Computer and Chemistry, and taxonomy terms for all articles (content types) which store the methodology of the article. The taxonomy hierarchy is the following.

Articles

Computer

Arithmetic (Term ID: 1)
DMA (Term ID: 2) // abbreviation for "Direct Memory Access"

Chemistry

NGE (Term ID: 3) // abbreviation for "Noble Gas Elements"
DMA (Term ID: 4) // abbreviation for "Dynamic Mechanical Analysis"

When users are creating or editing a node of type Chemistry, just NGE and DMA (whose ID is 4) should be allowed to select.

I only need one taxonomy vocabulary, since there are too many content types, and if I want to add a vocabulary for each of them, then it leads too many vocabularies; more importantly it removes the ability of freely navigating in different types using taxonomy hierarchy.

How do I limit the allowed taxonomy terms basing on the content type?

According to my choice you should use hook_form_alter to bind taxonomy list based on article type.

function MY_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $default_value = 0;
    $options = getArticles('Computer','Articles');
    $form['your_taxonomy_field_name'] = array(
      '#title' => t('Articlas'),
      '#type' => 'select',
      '#options' => $options,
      '#access' => 1,
      '#default_value' => $default_value,
      '#weight' => 1,
    );
  }
}
function getArticles($articleType,$vocabularyName) {
  //get the vocabulary
  $vocabulary = taxonomy_get_vocabularies();
  $vid = -1;
  foreach ($vocabulary as $item) {
    if ($item->name == $vocabularyName) {
      $vid = $item->vid;
    }
  }
  if ($vid != -1) {
    //get the parrent Term
    $query = new EntityFieldQuery;
    $result = $query
      ->entityCondition('entity_type', 'taxonomy_term')
      ->propertyCondition('name', $articleType)
      ->propertyCondition('vid', $vid)
      ->execute();
    $parrent_tid = array_shift($result['taxonomy_term'])->tid;
    //return children
    return taxonomy_get_children($parrent_tid);
  }
  return NULL;
}


Best practice to change 403 page depending which page 403? In D7 I would like to display some cause for the 403 and that changes by path (and other factors but those are easy). I can think of a few tricks like using request_uri() to see which page we were on, originally but I wonder if there is a good practice already established for this?

This: How can a module detect when the "access denied" page is output? along with arg() is probably how I would do it. D7 doesn't have the correct hooks for this so you have to use an API in a way that it wasn't originally intended.


Create Table With Aggregated Dates I'm trying to create a table which aggregates all full date (Year-Month-Day) values into the Year. The issue I'm facing is that, even though I managed to achieve that, view still somehow sees day and month of the date field, and shows them as 2 different records.

In the end I'd like to plot that data into the charts module and receive a result of Number of Items vs their Age

These are the screenshots of my view as I have it right now.

You can use different formatters for the exact same field when you are in a different context. So, while the full node is shown, you can use the full date (as set in CT's Manage Display). When displaying the date in views, you can use the time ago. For correct grouping, add the date field once more, exclude it from display, then set the formatter to a custom one which only shows the year and finally use that rendered output to group the view's rows.


HDI display the human readable node type at the end of the breadcrumb I want to modify the default breadcrumb to append the machine readable string of the current node type to the breadcrumb. I believe I can do this via template.php.

I am using drupal 7.

I'm not used to doing stuff in the theme layer, so my solution would be to use a module. Have you seen this one: http://drupal.org/project/custom_breadcrumbs ? I think it would allow you to do what you want.


Altering routing of user/login I have a use case where I need to adjust the landing of the route, user/login to direct to a custom developed user/register page once clicked. What's the quickest method of doing this without overloading the core User module with changes?

You can also use Login Destination module to redirect without touching any code

  The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.


Set value of field based on GET param for anonymous users I ran into a strange problem. All forms are cached for anonymous users even if there is a token present in the url. But I need that token to store a "value" field type on a form. Because the form is stored in cache, it does not verify for that get param and set the value accordingly.

I tried using an "after_build" function but that is also not triggered.

Is there a way I can use the GET param in my code? Or is there a way I can disable caching only for this form?

Thanks.

Have a look at this module Cache Exclude, it might help you.

And even have look at this link, it is having more details about your problem.


Utilizing admin panel values elsewhere in a module So I've got a custom admin panel page in a module I've written, and I want to get a value out of it.

Let's say I have a text box on this admin page, with a value, and I want to get that at some other point.

Do I need to use variable_set and put that into the database and then variable_get it in the function I want to use it in - or do I call it some other way?

Basically this thread:

https://drupal.org/node/2074589

Essentially, I just want to have a user be able to select a picklist value in the admin, and then call that picklist value later on in the actual module, for display.

You need to utilize system_settings_form when you write your admin form.

function mymodule_admin_form($form, &$form_state) {
  $form['my_textfield'] = array(
    '#type' => 'text',
    '#title' => 'Title',
    '#default_value' => isset($form_state['values']['my_textfield']) ? $form_state['values']['my_textfield'] : '',
  );

  return system_settings_form($form);
}

Submitting this form will call system_settings_form_submit which saves all the form fields as a variable, so you need to be careful when naming the form fields.

Now all you need to do is call:

variable_get('my_textfield', 'default value to return if no value is set');

from any function after drupal is bootstrapped.

Here's more information on how to create a configuration form: Creating the configuration form


How to show a View with Rules I want to add an action that shows a view whenever the user earns User Points. I checked it and there's no rules for Views so I'm wondering how could I do it.

I'm using Drupal 7.

Assume that the path to the view you want to show is "SomePath". Then just create a rule with a Rules Action to "perform a redirect", to the path SomePath.

For a rule with such Rules Action, you just use whatever Rules Event that fits your needs (something related to user points I assume), and optionally add whatever Rules Conditions that fit. For a rule that you can probably use as a good starting point, have a look at my answer to "How to change user info with a rule when Points are granted to user (using userpoints module)?" (if you'd just add a Rules Action to redirect, you may be close already).


How to remove a box? I created a custom box on the Open Atrium dashboard. The box contained PHP code, I forgot a comma and now I got a blank page. The problem is that I don't know how to remove that box now. It is not there on the database and on the Drupal admin I can't find an option to remove it. Any help would be much appreciated.

Easy peasy, all I did was disabling the PHP Code module, editing the block and reactivating the module again.


Can't upload user picture When I want to add my user picture, the picture can't upload and when I inspect it the link is broken and get this error:

  Warning: array_key_exists() expects parameter 2 to be array, null given in theme_image_formatter() (line 605 of /home/webpenir/public_html/modules/image/image.field.inc).

However, when I add a picture for another user, it works pretty good.

how can I solve this?

EDIT

Only user 1 can't upload but other users can do, which is really strange.

It is a known issue you can try this patch  and Suppose if that patch not workout for you check the other patches here  https://drupal.org/node/920840  and if any of that patches not solved your issue then the best option is you have to submit a bug report.


change drush rsync for use with aegir I'm looking to drop the -a flag from the drush's rsync, but not sure what the best place for it as far Aegir is concerned. Would it be the sitename.alias.drushrc.php files in /var/aegir/.drush? Or should this change be configured in /var/aegir/drush/commands/core/rsync.core.inc ? Ideally, it would get set in once place and be effective for  all sites, and without impact to other functionality.

The reason I am looking to drop -a flag is to not preserve file ownership when the files are pushed out to clustered web servers -- we keep running to weird file permission issues, when files have different ownership on the Aegir server than the target web servers.

Thanks!

I put this in my drushrc.php file to change the default rsync mode to -rlptz for all sites:

$command_specific['rsync'] = array('mode' => 'rlptz');

You could also put it in each site alias if you did not want the change to be affected on a global basis:

$aliases['mysite'] = array(
  'root' => '/path/to/drupal',
  'uri' => 'mysite.org',
  'command-specific' => array(
    'rsync' => array(
      'mode' => 'rlptvz',
    ),
    'sql-sync' => array(
      'mode' => 'rlptvz',
    ),
  ),
);


How do I name a mimemail-message.tpl.php template to be used with a specific webform? I cant seem to get the naming of the mimemail-message.tpl.php correct in Drupal 7. I know the naming scheme says "mimemail-message--[module]--[key].tpl.php" but either I'm not understanding what the brackets represent or I'm doing something else wrong.
I've tried:
mimemail-message--webform--mywebformname.tpl.php
mimemail-message--webform--250.tpl.php

Just mimemail-message.tpl.php works, but I need different template layout depending on which webform is used.
Also, is mime mail not supposed to make use of webform-mail-250.tpl.php at all?

As you can see in line 264 of webform.submissions.inc Webform uses submission as the key.
Thus it needs to be named
mimemail-message--webform--submission.tpl.php

There is no way to target a specific webform without some extra custom code work.
mymodule.module
function mymodule_mail_alter(&$message) {
  if ($message['module'] == 'webform') {
    $nid = $message['params']['node']->nid;
    $message['key'] = $nid; // set key to nid
  }
}

Now you can do
mimemail-message--webform--250.tpl.php


devel module use anonymous user as author in generate content? i have been created 'job' content type, i used 'Devel module' to generate content of 'job' type, but in some 'jobs' its taking anonymous user as a author, but i don't want anonymous user as author, so what should i do to avoid anonymous user as a author?

Answer for you question is Yes it do,and you can resolve your problem  with following solutions:

The First solution is

Install the views, views_bulk_operations, and admin_views modules.
Go to the content listing (admin/content).
Filter the results to get the nodes you are interested in.
Check the checkboxes next to the node (there is also an option to select all).
Select "Change author" from the operations dropdown and click the "Execute" button.
Select the user you want to change the author to and click the "Next" button.

Admin views uses views bulk operations to override the default drupal administration views with something a lot more useful.

And also another solution is using bulk author update module


Post content via JSON API: CURL works, PHP not? I've got those modules enabled:

HAL
HTTP Basic Authentication
JSON:API
REST UI
RESTful Web Services
Serialization

When I run this command, the content is created.
curl \
--user demo:9aqW72MUbFQR4EYh \
--header 'Accept: application/vnd.api+json' \
--header 'Content-type: application/vnd.api+json' \
--request POST http://www.demo.drupal/jsonapi/node/article \
--data-binary @payload.json

Now I try to read via PHP, which works fine too.
require 'vendor/autoload.php';

use GuzzleHttp\Client;

// Update to a user on your Drupal site that has permissions to create content
$user = 'demo';
$pass = '9aqW72MUbFQR4EYh';
$url = 'http://www.demo.drupal';

$content_client = new GuzzleHttp\Client([
    'base_uri' => $url,
    'timeout'  => 20.0,
]);

$res = $content_client->request('GET', '/jsonapi/node/mail/71adf560-044c-49e0-9461-af593bad0746');

$body = $res->getBody();
$stringBody = (string) $body;
var_dump(json_decode($stringBody, true));

I can't post content. The code I am using returns a 401, 402, or 500 error.
$headers = [
  'Content-type' => 'application/vnd.api+json',
  'Accept' => 'application/vnd.api+json'
];
$payload['data'] = [
  'type' => 'node--article',
  'attributes' => [
    "title" => "My custom title"
  ]
];

$guzzleResponse = $content_client->post('/jsonapi/node/article', [
  'json' => json_encode($payload),
  'headers' => $headers
]);

if ($guzzleResponse->getStatusCode() == 200) {
  $response = json_decode($guzzleResponse->getBody());
}

What am I doing wrong?

The 401 error is because you're not sending the basic auth creds like you are with your curl request. You need to add an Authorization header to your Guzzle request:
'Authorization' => 'Basic ' . base64_encode($user . ':' . $pass),
The 500 error is likely due to a malformed payload that JSONAPI can't parse. The value of json should be an associative array, not a JSON encoded string. See the Guzzle docs on uploading JSON data.


Programmatically add a translation with proper content moderation state I am trying to add a node translation programmatically when a node is created (using hook_ENTITY_TYPE_insert). My code works fine except that the translation doesn't really have a content moderation state. My code is the following.
function mymodule_add_translation($node) {
  // get the current language, and determine the translation language
  $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $langcode = ($lang == 'en') ? 'fr' : $lang;
  $node->setRevisionTranslationAffected(FALSE);
  $node->addTranslation($langcode, ['title' => $node->getTitle()])->save();
}

This is what the content_moderation_state_field_revision table looks like for two nodes; the first one was manually translated and the second one was translated using the above code.

I am clearly doing something incorrect. Any suggestion would be really appreciated.

What is the problem you're seeing with the moderation state table? What I think I'm seeing is:

Revision 15 is the initial save of the node.
Revision 16 is the second save, where fr has changes and en does not.

I can't see anything too unusual here, but if you are running into errors later in the lifecycle of the node, that would be helpful information.
One red flag I can see in the code is manually calling setRevisionTranslationAffected and addTranslation. Many of the Content Moderation tests use the following methods to add translations and to create revisions, because that's how additional bits of metadata like the revision_translation_affected column are set:
$storage = \Drupal::entityTypeManager()->getStorage('node');
// You may try either of these two methods for creating a revision or a translation.
$storage->createRevision($node);
$storage->createTranslation($node, 'fr', $node->toArray());


How to extend/override Rest EntityResource Plugin in Drupal 8 I would like to extend/override the Rest EntityResource Plugin in Drupal 8.  I have read everything I can find online and I can see how to create a resource plugin for something other than an Entity (such as dblog).  However, I can't figure out how to extend/override the existing Entity resource plugin.

To get this working I needed to:

Install the Rest UI module.
Go to /admin/config/services/rest and
enable my new resource.
Also at /admin/config/services/rest, click the edit button next to the new resource and configure it.
Go to /admin/people/permissions and configure the permissions for the new resource (Access GET, Access POST, etc.)

Couple of notes...  Both on the Rest UI config and permissions pages, it was difficult to distinguish between my new resource and the original.  In addition, when I tried to disable the original resource from the Rest UI config page I got the following error:

Fatal error: Call to undefined function Drupal\restui\Controller\drupal_valid_token() in drupal-8.0.0-beta2/modules/contrib/restui/src/Controller/RestUIController.php on line 211

However, even though both resources are configured, the system appears to be using my resource and not the original.


how to create a view of entities and nodes I need to create a view which displays both entity type data and node data. Is this possible? I know how to create a view of either entities or nodes, but not together.

Node are entities. Likely a Node View has access to node-specific properties while an Entity View only has access to fields and generic properties (or properties exposed through the Entity API).

If you can link your entities to nodes using a relation that is exposed as a relationship in a Node/Entity View, you should be able to have view results consisting of data from both a entities and nodes.


Require field on publish only I have a D8 site on which I would like to require an image field to be completed only when a node is published; if the publish box is not checked, the field should not be required. I was able to do this with a custom module in D7, but since D8 has decoupled entity validation from form validation, I'm at a loss.

I've tried doing this with the Rules module, with no luck.

Simply add a validation on the entity level, then you have easy access to the whole entity.

You can see an example in content_translation_entity_type_alter():

$entity_type->addConstraint('ContentTranslationSynchronizedFields');

You register a constraint like any plugin, the only special thing is that there are two classes, the plugin class itself doesn't really have anything except the messages usually while the validator has the logic, in the validate method::

ContentTranslationSynchronizedFieldsConstraint
ContentTranslationSynchronizedFieldsConstraintValidator::validate

Once you have that, writing the actual logic is often much easier, because you have a fully built entity object to work with and don't have to wory about getting the raw values from the form values. And as a bonus, it will also automatically work for REST/json_api and any other module that uses the validate() method to ensure that created entities are valid before saving them.

For example, verifying that an image field is not empty when the entity is published:

if ($entity->isPublished() && $entity->hasField('field_image') && $entity->get('field_image')->isEmpty()) {
  // add a violation...
}


Get translated field value with fallback How can I get the translated value of a field in Drupal 8 and if no translation is given, fallback to the default node language?
I tried this: https://drupal.stackexchange.com/a/145747/9586, but when no translation for a field if added, it just returns NULL.

Here is what I tried:

    $node = Node::load(2);
dsm(\Drupal::entityManager()->getTranslationFromContext($node)->field_my_awesome_field->value);

Drupal 8 does not have built in field-level language fallbacks. That feature was removed in favor entity level language fallbacks since that is the common case. Usually an entity is translated as a while (or not) and it removes a huge amount of complexity, especially in views or so.

If you have a specific field where you want to apply this, then you need to implement that yourself. You can check if an entity-level translation exists with $node->hasTranslation('en') and if so, get it with $translation = $node->getTranslation('de') ($translation is still a node object, it's a clone of the original one with a different active language). Then check if you have a value and repeat until find one.

Something like this:

$value = NULL;
$language_manager = \Drupal::languageManager();
$current_langcode = $language_manager->getLanguage(Drupal\Core\Language\LanguageInterface::TYPE_CONTENT);
foreach ($language_manager->getFallbackCandidates(['langcode' => $language_manager->getLanguage(]) as $langcode) {
  if ($node->hasTranslation($langcode) && !$node->getTranslation($langcode)->field_my_awesome_field->isEmpty()) {
    $value = $node->getTranslation($langcode)->field_my_awesome_field->value;
    break;
  }
}


How do I hide the link to the RSS feed on the term page? I want to keep the feed functionality, but I want to hide the "Subscribe to [term name]" link on the term page.

Under "Structure", "Views", open the "Taxonomy term" view, on the Feed display, under Feed settings set Attach to to none.


Remove "read more" when there is no more text to read I have just set up a new website with Drupal 8. I created a new content with a regular HTML that contains basic text. I promoted it to homepage, I see a "read more" link. But there is no "more" to read.

How can I remove "Read more" link if there is no more content to read?

I found some modules for Drupal 7 but I am following a certain solution for this general problem.

And also I am curious; isn't it obvious that there shouldn't be a "read more" link when there is no more content? Is it a bug or something?

Neither of the other answers actually addresses the question, which is how to turn off "read more" selectively depending on whether there is more to read or not.

The standard read more link, as the comments in NodeViewBuilder say, is always displayed on a teaser by default because there is no (easy) way to know how the teaser content differs from the full view. Your content type might have several other text fields apart from the body which are only shown on the full page view.

However, it should be possible to implement a custom "read more" link that has the behaviour you seem to be asking for. I don't think anyone has implemented one yet, but the most fruitful approach would be a modest extension of the "summary or trimmed" field formatter, although you could probably also do something in a preprocess hook in your theme.

Edit: A demonstration module is up on github now. It's not perfect and I would like to refactor it and possibly make it more general-purpose but it works for the simplest case.


"Failed to set field" Problem with SimpleTest, testing a form With SimpleTests, I want to test a form similar to :

  // Textfield :
  $form['fieldset_name']['test'] = array(
    '#type' => 'textfield',
    ...
  );
  // Submit :
  $form['fieldset_name']['submit_button'] = array(
    '#type' => 'submit',
    '#submit' => array('my_module_form_submit'),
    '#value' => 'Submit button',
  );

This form is accessed from 'admin/config/my_module'. So I add the following test in my_module.test :

  function testForm() {
    $path = 'admin/config/my_module';
    $edit['test'] = 'testing field\'s input';
    $this->drupalPost($path, $edit, t('Submit button'));
  }

When I run the test, it fails with these errors :

  Failed to set field test to testing field\'s input

  Found the Add button (failed)

Where am I wrong ?

Permissions would be my first guess.

Enable debug output in the Simpletest settings and then check if your module is installed and you have permissions to visit that page.


Can taxonomy terms contain special characters e.g. ampersands, apostrophes and dashes? What characters are legal in taxonomy terms in Drupal 7? I haven't been able to find a list of illegal characters. Does this mean all characters are legal? I am particularly interested in knowing if ampersands, apostrophes and dashes are safe to use. Thanks

They are safe to use, however you may have issues with your url paths. so in your url if you have a term Theology & Scripture", it becomes this: 'theology%20%2526%20scripture. This kind of urls are not good for search engine optimisation.

You can however use the pathauto module, to correct this issue.

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.


User login block doesn't appear for authenticated user Well, I go to structure/blocks/User Login/configuration and I tried select all checkboxes in "Show block for specific roles" but login form doesn't appear when user has status "authenticated".

How I can solve this issue?

The user login block will never appear for any user other than anonymous users, as users are already logged in, so it makes no sense to have a login block when they are already logged in.


Time Limit on Comment Edit Let's say a user is registered and posts a comment to a node but didn't like the comment so he/she wants to edit it. I would like to limit the amount of time the user has to edit the comment. After this time has elapsed they should not have the ability to edit the comment, only they will need to contact an admin to do that.

How would I implement this or is there a module to help me accomplish this.

Sounds like you're looking for the Edit Limit module.

Edit Limits adds certain limits to editing nodes and comments. This can set the number of times a node can be edit. This can also set a time frame for nodes to be edited, as well as a different time frame that comments can be edited.
Comments can be set to only be limited within a given time frame. Site administrators can set the number of seconds after a comment is initially posted before it can no longer be edited. Time remaining will be displayed to the user.

Unfortunately, the module is not well documented, but here is an example of how you may use to provide a three minute grace period for editing own comments:
First navigate to Administration » People  » Permissions. Under Comment, enable the permission "Edit own comments" for whatever role you want to have this permission (typically "Authenticated user").  Scroll down to the bottom of the screen and press "Save permissions".
Then, navigate to Administration » Configuration » Content authoring » Edit Limit and configure the module to enable comment limits, to three minutes, and select the content types you want this to apply to.  Press "Save configuration" when done.

This is how it looks like when working:

At the time of writing, it does not work for RTL languages.  See this issue: Edit Limit doesn't show edit link for RTL languages for the current state of this bug.


Dynamically change widget type in node edit form I have a content type with a geofield. I'm using an Openlayers Map as the input Widget. The map allows the user to place a marker and it populates the geofield with the lon/lat coordinate. In some cases, however, it would be preferred to input the lon/lat manually as opposed to using the map.

How would you provide an option in the node edit form to dynamically switch the display widget for the geofield from the Openlayers map to lon/lat, or from lon/lat to a map?

The use case you describe is specific in nature, but the question you actually asked in the title is more general purpose. I’m answering the question in the title.

To the best of my knowledge, there is not at present an Input Widget Switcher module for Drupal 7 or earlier, but there really needs to be. There are similar modules such as Display Suite for altering the displayed output of a node, including using different display formatters (example: showing the same date field as a short date format in a Teaser and as a long date format in a full node display), but nothing analogous for node input form widgets.

Drupal 8 has the underlying structure needed to implement something like this, known as Form Modes (basically the input form equivalent of View Modes such as Full vs. Teaser, which Display Suite builds on). But while there is a UI for creating them, there is not at present to the best of my knowledge an ability to use them or switch between Form Modes in core.

That said, the Form Mode Control module for D8 does seem to provide this ability. It allows switching between Form Modes based on Role or Permission and on Node (or Entity) Creation vs. Modification (for instance, on Creation the Widget for a GeoField might be Lat/Long with HTML5 GPS Geolocation enabled, but on Modification switch to a different Form Mode that uses, say, OpenLayers Map Widget so that the already-existing location marker can be moved on a map).

There’s also the similar Form Mode Manager module (also D8 only) that works a bit differently, but it’s only in Alpha at the time of this writing, while Form Mode Control is in Release Candidate 2 and thus better for production sites.


Geting values for multipart form elements using Twig Whereever you are, I hope you're fairing well under the circumstances. To some of the hardest hit areas, we are thinking of you constantly.

Webform Advanced Elements

I am having difficulty retrieving submitted values from Drupal 8.8.4 Webform 5.9 multipart elements using Twig. Standard, single form field, values work fine, however elements such as Name and Advanced Address do not. Both of latter elements have multiple form fields (e.g. first, middle, last name; or street, city, country...) and may be dynamic (e.g. pick a country before completing address).

In my case, I am using the Attachment PDF and a custom Twig template to generate a PDF file attachment that is returned to the user, however I can see the same result using Twig in an e-mail, or the generated test e-mail preview.

Testing:

A simple text field works correctly:

Dated: {{ data.date }}
 (works)

Name and Advanced Address are blank:

{{ data.my_name }}
 (blank)

{{ data.my_address }}
 (blank)

Tokens Work, Sort Of

For what it's worth, the multipart values are available using tokens in the e-mail body, albeit I can't get portions of the values, which is the objective. What I mean by this is that an entire complete address will be returned, on multiple lines, but getting just the street name doesn't work (for me).

Using the examples above:

[webform_submission:values:my_name] (returns John Smith)

It also wasn't possible to retrieve just a street address:

[webform_submission:values:address] (returns stree, city, state/prov., country on mutiple lines)

I've really been stumped, and I'm surprised it is so hard to find the answer. Perhaps I'm not working the question correctly, this is more of a hobby project. Thank you for suggestions.

I think you are just overlooking something simple here. The 'multi part form elements' is called a composite element. And it holds an array of values of its subfields.

Let's say the composite parent is called 'name', and it has a subfield called first_name, then you can use {{ data.name.first_name }} to get the first name in twig.

As for webform submission token, you can try something like [webform_submissions:values:name:first_name]