Reduce latency in loading a page in Drupal 6

The database query time is just the database interaction, don't forget that PHP takes time to process its own logic.

If the majority of the page load time is outside the database you should install xhprof to actually profile your PHP functions individually to see where the damage is being done.

Basic tips for improving PHP performance - install a module like Cache Router to take caching out of the database and put it somewhere else like in memory or the file system.

Install APC or similar on your server to improve PHP performance.

Cache object load calls wherever possible, this is handled much more easily in D7 thanks to the Entity Cache module, but it is possible to do in D6. Persistent caching of node_load() can really be your friend.

Avoid configuring your site to load a lot of tpl.php files on page loads - "fields" rendering mode in Views can do this.

Avoid "slow" core functions - some taxonomy functions can be very slow in D6, be aware that user_load() is not even statically cached so it can be expensive if you call it a lot.

Avoid eval()'d code as it runs much slower as well as being a potential security risk - This is anything using the PHP input filter.

Disable all "UI" modules. If you're running a large number of modules it is very easy for one of them to be doing more than it "should" be, so you want to start whittling the total number down if possible. Unfortunately, modules smart enough to split their logic into "core" and "UI" often aren't the culprits for performance problems but it's worth doing anyway since it is so easy to do.

If it isn't PHP or the database that is slowing things down, your server could be under too much load and doesn't have the processing power to keep up with incoming requests. If you can process X number of requests per second and have 2*X incoming requests then your pages will load about 1/2 as fast.

Make sure you have enough RAM to run your site comfortably, if your server starts "swapping" things can degrade very quickly.

Page Caching does not help at all for authenticated traffic, only anonymous traffic. Make sure that your block caching settings are correct for every custom block that you've created. It might be worth trying the auth cache module.

Unfortunately there are many, many ways to slow a site down so these tips are not really comprehensive. I used to have a bookmark to "56 tips" that you could basically review your site with and at least triple the speed but it was pulled offline at some point in the past couple of years :(

Also, you might want to try swapping to innoDB as the row-level locking can speed things up drastically over myISAM in some cases.


View block - show only field content from own page

You van do this with a contextual filter on your  block view.

There is a very gold tutorial located here: http://dannyenglander.com/blog/using-views-contextual-filters-create-related-content-block-drupal-7

If anything is unclear dont hesitate to ask! ;-)


'Manage fields' and 'manage display' links not working for content types

Solved.  I could get access via FTP and found out there were 2 missing files from the server.  After uploading them the problem is fixed.


This can be accomplished by overriding theme_breadcrumb() in your theme's template.php
An example implementation:

function mytheme_breadcrumb($breadcrumb) {

  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), '<front>');
    $breadcrumb[] = l(t('Blog'), 'path/to/blog');

    $tid = arg(2);

    if ($term = taxonomy_term_load($tid)) {
      $uri = entity_uri('taxonomy_term', $term);
      $breadcrumb[] = l($term->name, $uri['path'], $uri['options']);
    }
  }

  // resume normal operation
  if (!empty($breadcrumb)) {
  // uncomment the next line to enable current page in the breadcrumb trail
    $title = drupal_get_title();
    if (!empty($title)) {
      $breadcrumb[] = $title;
      unset($title);
    }

    return '
'. implode(' &gt; ', $breadcrumb) . '
';
  }
}


Online streaming and on air/broadcast function for a Drupal website

Octopusvideo might suite for your requirement, this is in D7 and have lot of functionality.


Why isn't the code in my implementation of hook_form_alter() being called?

First of all - have you checked that Drupal sees your function at all, and calls it?

Then, have you tried printing out $form_id? As for default D7's content types (article and basic page) comment form ids are not "comment_form", but:

comment_node_article_form - for article
comment_node_page_form - for basic page


How to add the admin role to Drupal 7 after upgrading from Drupal 6?

You can set an admin role in admin/config/people/accounts or by going to Configuration -> Account Settings under "People" label.

The help text under the select box says:

  This role will be automatically assigned new permissions whenever a module is enabled. Changing this setting will not affect existing permissions.

So remember to assign the existing permissions to this new role! But whenever a module is enabled and new permissions are created, this role will automatically be granted those.

To create new roles you go to People -> Permissions (tab) -> Roles (secondary tab)


How can you force a stylesheet reload in Drupal7?

You can do this with drush

$ drush help cache-clear
Clear a specific cache, or all drupal caches.

Arguments:
 type                                      The particular cache to clear. Omit
                                           this argument to choose from
                                           available caches.

Aliases: cc

So you can do

drush cc css-js

and this will rescan the cached CSS and JS files, nuke them if they are stale, and generate a new key that gets appended to CSS and JS URLs.


I suppose you added the french menu item before you added additional languages to your Drupal. Then it is very likely that it was saved using LANGUAGE_NEUTRAL as language and therefore will appear within all languages.

To fix this, go to the menu's item list on admin/structure and manually edit the menu item. You should find a drop down for the language within the edit form. Make sure to choose the appropriate language here and save the item.


Drupal embed view in email sent by views

Sounds like you need to disable contextual links:


node_load() in a form and display it in an attached form markup

You could do this with entity references and the views merge rows module.. An entity reference field to the taxonomy term and an entity reference view providing the term and all related nodes.. Here's a quick example I did up on a node add form. I can give more detail tomorrow if it's what you need.


Is there an automated way to create another multisite inside of an existing multisite Drupal install?

If you configure multisite instances to use https://www.drupal.org/project/dslm, you can use a command like 'drush dslm-new mynewsite drupal-7.34' to provision a new site.  @btopro has taken DSLM a step further calling DSLM and Drush commands from the CIS install profile to completely automate the process from within Drupal for Penn State and the growing number of schools using ELMS.  This configuration allows schools to generate several new Drupal sites from different ELMS install profiles from a centralized Drupal site.  [This screencast][1] explains how the ELMS CIS implementation works.  There is also a vagrant version of this configuration you can spin up from https://github.com/btopro/elmsln-vagrant

CU Boulder also uses a Drupal front end to DSLM to spin up new sites, but we don't use a true multisite configuration and our backend for this service is more complicated
and CU specific leveraging Eve (http://python-eve.org) and F5 server
(https://f5.com/products/modules/global-traffic-manager).

I doubt either of these solutions is a good fit for you out of the box, but if the "automated way" you are only looking for only needs to automated this process at a commandline level, DSLM will get you most of what you need. You can also use code from the ELMS CIS project to create your own front end.

If you looking for a graphical front end that works "out of the box", you might want to consider using the Aegir Project (http://www.aegirproject.org/) with an install profiles like Hostmaster (https://www.drupal.org/project/hostmaster).  Installing Aegir on your own server can be complicated (http://community.aegirproject.org/installing/manual), but there are several hosted Aegir options.  Converting an existing site to Aegir is also more complicated than DSLM.  Aegir is really an
"all in decision" while DSLM can be used along side existing, non-DSLM sites and includes a command to convert an existing site to use the DSLM symlink structure.


That looks doable by youtube-api.

What you can do is have the form loaded already when you should the color box, with display: none on form block.

Now with help of youtube api you can detect video end and can toggle visibility to display: block;

Refer here for youtube api example:-

source https://stackoverflow.com/questions/7853904/how-to-detect-when-a-youtube-video-finishes-playing


Drupal out of the box supports taxonomy and tagging using autocomplete. You need to create a vocabulary and add terms to the vocabulary.

Create a term reference field and choose widget as autocomplete.

Regarding making it look alike above you can consider this post.


How do I convert special characters into html in twig

NOTE: this should be avoided as it is considered bad practice as mentioned in the comments, leaving here as an example to avoided
Inside your twig template try this
  {{ var|raw }}

where var is the variable being printed.
For more information here


It turns out I was going about this the wrong way.

To create a Twitter-like follow button the best thing to use is the module Flag.

Create a Flag called "Follow Me" (follow_me)

Create a Content-pane View which has:

Sort Criteria: Content: Type (=MyContent)
Context Filters: Content: Nid
Relationships: Flags: follow_chapter (by current user)

This content pane then can be used with Panels.

You can then create another view with the relationship with Flags: follow_me to get a list of content followed by the user.


Getting "On Behalf Of" in ubercart email confirmation

Try to look in modules folder, in

site root folder /sites/all/modules/ubercart/uc_order/templates/uc-order--admin.tpl.php


Translate the frontend part of the site only

The Administration Language module can do this:

  This module lets the administrator see all administration pages in her preferred language.

  You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).

  You can use the standard Languages page to choose the language of the admin pages.


$header = array(
        array('data' => 'title',        'field' => 'title', 'sort' => 'ASC'),
        array('data' => 'cal name 1',   'field' => 'field_order_value'),
        array('data' => 'Cal name 2',   'field' => 'field_issue_value'),
    );

// $result = db_query("SQL here");

$rpt_data = array();

    foreach ($results as $key => $rpt_data1){
        $rpt_data[$key][] = 'Result item';
        $rpt_data[$key][] = $rpt_data1->product_title;
        $rpt_data[$key][] = $rpt_data1->stock_value;
    }

    if (count($rpt_data) == 0) {
        $output = t('
Record not found.
');
    } else {
        $per_page = 20; // Initialize the pager
        $current_page = pager_default_initialize(count($rpt_data), $per_page);  // Split your list into page sized chunks
        $chunks = array_chunk($rpt_data, $per_page, TRUE);  // Show the appropriate items from the list
        $output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page])); // Show the pager
        $output.= theme('pager', array('quantity',count($rpt_data)));
    }


"Aggregate and compress CSS files" and "Aggregate JavaScript files" in performance settings, is not working

Well, this issue is ongoing at http://drupal.org/node/986558 . The Drupal-7.9 should have fixed it, and it did fix my css, but I am still having issues with js.

Note: if you have this problem and upgrade to Drupal-7.9 , make 100% sure you replace all of your .htacess files.


Exclude Views field from displaying and just print it in field template?

Excluding the field from display empties the $field['name']->content, so that when the renderer gets to the default field template, there's nothing to print.

If you absolutely cannot achieve your intended result using tokens and Rewrite Output then I suggest you:

Do as you have already done to print the title in a different field's template
Create a field template for title that is empty


How can I get a select drop-down menu based in terms of the a vocabulary to display in a block or a theme?

Have you tried http://drupal.org/project/entityreference? works well for me. basically your turn the field of "term" into a drop-down select on Node edit forms and a link on content.


Using computed fields module to display certain fields?

Sorry for the late response, but this is an issue I struggled with as well.

In the first box, 'Computed Code' you determine the value of the computed field based on what is present in the $entity object. Calculations are possible, but drupal functions or methods are not available. In your case the entire determination can be performed here:

if ( isset($entity->field_shortdesc) && trim($entity->field_shortdesc[$entity->language][0]['value']) != "") {
  $entity_field[0]['value'] = $entity->field_shortdesc[$entity->language][0]['value'];
} elseif (isset($entity->field_audio_description)) {
  $entity_field[0]['value'] = :$entity->field_audio_description[$entity->language][0]['value'];
} else {
  $entity_field[0]['value'] = "";
}

The second box, 'Display Code', is for processing the value you determined in the first box. If you have to call drupal functions to load a user object or to format text this is where you would do it. In your case, no further processing is required, so you would leave the default:

$display_output = $entity_field_item['value'];

Then if your fields are using an input format (eg. 'Filtered HTML') you will want to set the display format (under 'Manage Display') to 'Filtered markup'.


Ubercart: maintaining cart content after user login

The feature looking for is default ubercart behavior. You may have missed with some of your custom code may be with hook_user Check that to see what happens and try disable any custom modules.


Automatically Fill a Second Term Reference Field in a Node Based On Filled Value from a First Term Reference Field

Have look at the following modules

Reference field option limit

  This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

Hierarchical Select

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.


Can we remove template.php from active theme folder?

Here is explained the template.php function:

https://www.drupal.org/node/1728096

If you remove the template.php many things on the theme will stop working, specially all the things that make the template different (or useful).

But if you're using a subtheme you can remove the template.php in it since your subtheme will use the original theme template.php (As long as you don't have your own hooks and functions in that subtheme template.php).


Get all orders that contain a certain product

I ended up creating a module for it as it didn't seem possible to implement using rules.

here is the function that is called on hook_node_update

//load all pending orders
$orders = commerce_order_load_multiple(array(), array('status'=>'pending'), TRUE);
//go through the loaded orders
foreach($orders as $order){
    //load each order as an entity
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach($order_wrapper->commerce_line_items as $line_item_wrapper){
        //check if the order contains this node's product
        $product = $line_item_wrapper->commerce_product;
        $node_product = $node_wrapper->field_product;
        if($product->sku->value() === $node_product->sku->value()){
            //change the status of the order to processing
            $order_wrapper->status = 'processing';
            $line_item_wrapper->save();

            $order_wrapper->save();
        }
    }
}
return TRUE;

Now since I got the respective orders to processing status, I can go on using rules for the rest of the implementation.


Content REST view does not work because of moderation states

The route is not in core. Probably it is in a contrib or custom module. You have to search for a *.routing.yml file, where it is defined and then look for an error in the yml file and then clear the cache.

You can get a complete list of all routes with drupal console:

drupal route:debug


How are the default search results are sorted on D7?

Drupal's defaul search result is sorting on the basis of:

Number of comments
Keyword relevance
Content is sticky at top of lists
Content is promoted to the front page
Recently posted

Under Content Ranking configuration (admin/config/search/settings) you can setup the influence of the above factors while searching.

Thanks,
ARUN AK


Replicating a Node with Replicate UI Leads to an Incorrect Hreflang Tag

As the module's page on https://www.drupal.org/project/hreflang says if it's for Drupal 8, then you should implement hook_language_switch_links_alter() or hook_page_attachments_alter() to modify the hreflang tags. If it's for Drupal 7 then use either hook_language_switch_links_alter() or hook_html_head_alter()


How can I have non-exact locations on a map?

I had a similar problem, and this is how I solved it:

Add another 'location' field to you content type; call it, e.g., 'public user location'.
Build up your custom module, and in the hook_form_alter() implementation, hide the new location field, so the user cant edit it.
Now you need to get the 'non-exact' location for the first location; I do this with a Google geocode.

It's up to you to do it via JavaScript when the first location is set (the way im doing it), or to do the geolocation when the form is submitted to 'manually' add the 'non-exact' location.

If you use a geocode on the partial address, Google Geocode will give you the coordinates in the middle of the area you searched.

Please note that, for more specific geocoding, you could even use the Geonames API.

If you choose the second way (create the 'non-exact' location when the form is submitted), maybe this can help you about the location creation: Creating nodes programmatically in Drupal (including cck and location fields).

As side note, I am not using the Gmap module anymore because my needs were a bit complex and were not fit by this module; if you'll find some trouble, I recommend you building your own small module using Google API v3.

This will let you, for example, show the 'public location' in the map with a circle around, as Google Latitude does.


Get the master parent node id for a node reference field

If you are looking for a DB query within a custom module, you could do something like the following example function that recursively goes through the reference tree to get to the top for a node.
It will work for N levels, (but not for multi-valued references or nodes with multiple node reference fields).

function mymodule_getTopReference($nid){
    $top_nid = 0;
    //load the node
    $node = node_load($nid);
    //get all reference fields
    $node_reference_fields = array();
    $field_infos = field_info_instances('node',$node->type);
    foreach ($field_infos as $field_name=>$value){
        $field = field_info_field($field_name);
        if (($field['type'] == 'node_reference')){
            if ($field_value = field_get_items('node',$node,$field['field_name'])){
                $top_nid = $field_value[0]['nid'];
                break;
            }
        }
    }

    if ($top_nid && ($parent_nid = mymodule_getTopReference($top_nid))){
        $top_nid = $parent_nid;
    }
    return $top_nid;
}

For example, if your node reference field was called "my_reference" and your example nodes had the following nids:

A = 1
B = 2
C = 3

and your references are as you said:

B->A (2->1)
C->B (3->2)

Then for node 'C'(3) you'd call this function like so:

$top_nid = mymodule_getTopReference(3);

which then would set $top_nid to 1 (A's nid).


You forgot requirements (which is required):

my_module.agreement:
  path: 'my_module/send_consent'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::check_agreement'
    _title: 'Agreement controller'
  methods:  [GET]
  requirements:
    _permission: 'access content'

See Structure of roots for full details.


Restrict User Role from Unpublishing Content


Node Import, and Feeds are two solutions I've used recently to import content. they may work with while you maintion that your module read from csv and store in DB


Why hook_form_alter implementation is being called twice?

I ran into the same problem today, a hook_form_alter() override in a custom module was being called twice on every form.

My custom module's name was "project_name" and my theme was also called "project_name" (folder/machine names). I uninstalled my custom module and renamed it to "project_name_different" and re-installed it. After that change, hook_form_alter() only gets called once.

Don't know the super technical explanation for this answer, but generally Drupal doesn't like duplicate names across modules and themes, so make sure machine names are unique across all modules and themes living within your site.


It looks like when I updated the jquery update module I checked both administrative  and default version to use jquery 1.7. There is a known issue here jQuery Update 7.x-2.4 makes Media 7.x-1.4's Library tab empty. When I changed the administrative pages to use 1.5 everything was ok again.


How to creating custom links that can be echo'ed individually

This can be implemented using blocks.

First create the required menus from  Home  > Administration >
Structure > Menus > Add menu
Place the new  menu as a block under footer section in Home  > Administration > Structure > Block layout
Save blocks

Find the reference images:

Add user account menu to footer block (You can also include your custom menus),

Image listng user account menu on footer


Unable to override default translation publishing status using entity_translation module

I ended up posting this to the module issue queue and got this suggested code:

function MODULE_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  // Set the publishing status for en-us to 0.
  if ($translation['language'] == 'en-us') {
    $translation['status'] = 0;
    $handler = entity_translation_get_handler($entity_type, $entity);
    $handler->setTranslation($translation);
    // Important: Avoid infinite loops by firing the insert hook again and again.
    $handler->getTranslations()->hook = array();
    $handler->saveTranslations();
  }
}

which was pretty close to what I had come up with on my own:

function mymodule_entity_insert($entity, $type) {
  // We don't want to do this for field collections.
   if (in_array($type, array('node', 'taxonomy_term'))) {
    // Attempt to unpublish the en-us translation that is set to published by default.
    $handler = entity_translation_get_handler($type, $entity);
    $translations = $handler->getTranslations();
    $enus_translation = $translations->data['en-us'];
    // Set the status = 0.
    $enus_translation['status'] = 0;
    $handler->setTranslation($enus_translation);
    // Save the translation.
    $handler->saveTranslations();
  }
}

And since it's not part of the saveTranslations() hook firing logic, no infinite loops should occur.


How to show nodes of a content type using contextual filters as filters?

After hours of tinkering here is my solution to the above. If anyone has the same requirement this will help:

Drupal 7.16, views-7.x-3.5

The View Setup :

The result (sample 1):

Sample 2:

No other settings required. Even in the section "WHEN THE FILTER VALUE IS NOT IN THE URL" does not matter, what seems to be important is you set the validation to always return TRUE regardless.

The path of this view is set to /myreports/%

Perhaps, the filter value in the URL that was found will be validated to always true. Then resolves to using this as a normal filter, as is the case with the normal filter setting. Hence, Filter content type = events (or jobs).


Taking a wild stab in the dark:

image_save($image);


How to add users in organic groups using services Rest api?

Install this module: https://www.drupal.org/project/og_services
Go to admin/structure/services/list/[MY-ENDPOINT]/resources
Enable at minimum the join resource
Flush all of Drupal's caches
Make a POST call to [MY-ENDPOINT]/og/join/[GROUP-NID]/[USER-UID]


Delete or unpublish content from old migration, if source rows no longer exist

Here is the solution that I came up with.

TLDR: Drush command to compare source data vs existing products, and activate or deactivate products accordingly.

Use case / goal

I am focusing on a specific use case, to make this easier to explain. Something similar could be done for other use cases.

Commerce products are imported with a migration. Both source and destination have one numeric primary key. The migrate map is MigrateSQLMap, so there is a migrate_map_* table in the database with destid1 and sourceid1.

Goal: Change the "status" property of commerce products which are no longer in the source data.

Considerations

A migration run can be incomplete. In such a case, we do not want remaining products to be deactivated.

Updating an entity (commerce product) in Drupal takes time. We do not want to update every entity just to change a timestamp.

We have to assume that the entire list of products can be quite big, so it can be problematic to have them all in memory at once. However, in this solution, I assume that having the ids (source id mapped to destination id) in memory is still acceptable.

Solution: Custom drush command

Create a custom drush command that does the following:

Query the database, join the commerce_product AS cp table with the migrate_map_MYMIGRATION AS mm table. For each row we want mm.sourceid1, mm.destid1 and cp.status. Load the complete list into an array as $maps[$row->status][$row->sourceid1] = $row->destid1.

Assign the two parts of the array to new variables $inactiveIdsMap = $maps[0]; and $activeIdsMap = $maps[1];.

Create two additional associative arrays, each with format $[$sourceid] = $destid:

$idsToActivateMap = [];. Start value: empty array.
$idsToDeactivateMap = $activeIdsMap. Start value: All ids for active products.

You may want to unset($activeIdsMap); to free memory. (We could have reused this variable instead of declaring a new one, but I like having variable names that are accurate throughout a variables's life.)

Iterate through the source data. You can get the migrate source from the migration. It is a bit tricky but it can be made to work.

For each source row:

If the id exists in $inactiveIdsMap, add the source + dest id to the $idsToActivateMap array.
In any case, unset this entry from the $idsToDeactivateMap array.

Now deactivate all to-be-deactivated products, and activate all to-be-activated products.

You ideally do this in chunks, so e.g. you load 20 products at once with commerce_product_load_multiple(), set each one's status, and save them individually with commerce_product_save().

This drush command can be executed after the migration.

Memory impact?

You can measure memory use with memory_get_usage() or memory_get_peak_usage(). If you use memory_get_usage(), you need to call it in the place where you expect memory usage to be highest. Memory pretty print: http://codeaid.net/php/convert-size-in-bytes-to-a-human-readable-format-(php)

The way to check for the impact of this specific operation is to run the command with a subset of data. E.g. put a ->range() on the select query for loading the migrate map. This should make all arrays smaller.

Why? Alternatives?

Another solution that I found tempting at first was to maintain a "lastseen" timestamp in a separate table.

However, this would mean either having to update each product on every migration run, or at least reindex the search index each time, because we would want to filter by "lastseen".

With the solution presented here, in the average case, only few products have to be updated.

It turned out that the memory impact was very manageable.


Keep track of which user fully downloaded a file

If you have file_entity installed, you can use hook_file_transfer() with a custom function my_custom_registration($file, $user) that registers which user downloaded which file
The starting code for that is :

/**
 * Implements hook_file_transfer().
 *
 * @param type $uri
 */
function my_module_file_transfer($uri) {
  global $user;
  $files = file_load_multiple(array(), $conditions = array('uri' => $uri));
  if (!empty($files)) {
    $file = reset($files);
    my_custom_registration($file, $user);
  }
}

hope this helps


How to update current url of view page so that it will filter correct result?

Add a new contextual filter, select 'Node: Nid', then check 'Provide default value' and in the select box choose 'Content ID from URL'


Actually, this can be done within the Views UI by selecting the user:data field and then choosing a key.


The only case where you want to work with entityDefinitionUpdateManager() in update and post update hooks, to update an entity type definition on existing installations to the one defined on the annotation.

To add a constraint to an entity type that's not yours use hook_entity_type_alter()


If your theme utilizes body classes and you don't need to modify the HTML structure you can simply do:

body.page-node-1 #block-block-1 {
  /* styles goes here */
}

Replace "1" above with the ID's for the node and the block.


How to add Permalink for custom content type(nodes)

You can create permalinks, better known in the Drupal world as "aliases", using the Pathauto module.

  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.

See Video Tutorial.


Page not found when there are clean extra parameters in URL alias-

I have discovered the problem and the solution. When you change domain, or you add a domain to the list in Domain Access, you later have to switch off SubPath, save, and later turn on SubPath again. In that way, it refresh "something", and everything works perfectly.

So if you have free parameters passed on the clean friendly URLs, you need to make those steps in order to assure that the site will work with the changed or added domains.


Loading fully themed node with Ajax - Drupal 7

There is a contributed module Ajaxify Drupal with JQuery Ajax available for this. You can load any pages, nodes or anything to a div by using ajax without loosing css and ajax behaviour of loading content.

  Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.


Sorry for posting link answer but, there is a complete tutorial here.


How can I clone and use the default taxonomy view to learn its behavior?

The % symbol in the URL works a placeholder for a parameter. So if you access taxonomy/term/1 or taxonomy/term/2 note that the number is actually the term id, so that is the way you "view" (access) the view. You can see, edit, add, delete or modify those parameters if you click the advanced option in the view and you will see the option "Contextual filters".

Now, to clone it, you can access the up right button and then click the "duplicate" option, wich for this case will have a URL /admin/structure/views/view/taxonomy_term/duplicate. Note that this will clone all the view and its styles, in this case, will duplicate a view with two styles: the page view and the RSS view.


Controlling the height of a jQuery accordion in content page

First you should try to set autoHeight to false , this will fix the height problem.
You should aslo consider to use behaviors in Drupal.

<?php
drupal_add_library('system', 'ui.accordion');
drupal_add_js("
  (function ($) {
    Drupal.behaviors.accordionRoles = {
      attach: function (context, settings) {
        $('#accordion').accordion({
          autoHeight: false
         });
      }
    };
  }(jQuery));
", 'inline');
?>

Then I could find the problem regarding HTML lists, I grabbed your HTML, put it locally and used the demo source for jQuery UI accordion (the section 3 have some HTML list inside) and it seems to work fine.


You can use hook_node_view to change the view before rendering.

/**
 *
 * @param type $node
 * @param type $view_mode
 * @param type $langcode
 * Implements hook_node_view().
 * To change paragraph title in node view.
 */
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
  if ($node->type == 'CONTENT-TYPE-ID' && $view_mode == 'full') {
    foreach ($node->content['field_medical_records'] as $key => $paragraph_values) {
      if (is_numeric($key)) {
        $item_key = key($paragraph_values['entity']['paragraphs_item']);
        $node->content['field_medical_records'][$key]['entity']['paragraphs_item'][$item_key]['field_visit_time']['#title'] = numToOrdinalWord($item_key) . ' Visit';
      }
    }
  }
}

/**
 *
 * @param type $num
 * @return string
 * Implement to get Ordinal word from number.
 */
function numToOrdinalWord($num) {
  $first_word = array('eth', 'First', 'Second', 'Third', 'Fouth', 'Fifth', 'Sixth', 'Seventh', 'Eighth', 'Ninth', 'Tenth', 'Elevents', 'Twelfth', 'Thirteenth', 'Fourteenth', 'Fifteenth', 'Sixteenth', 'Seventeenth', 'Eighteenth', 'Nineteenth', 'Twentieth');
  $second_word = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty');
  if ($num <= 20) {
    return $first_word[$num];
  }
  $first_num = substr($num, -1, 1);
  $second_num = substr($num, -2, 1);
  return $string = str_replace('y-eth', 'ieth', $second_word[$second_num] . '-' . $first_word[$first_num]);
}

You can change field names as per your requirement.


Make sure that the term reference field settings is set to "Dropdown" and Under views Other settings Use Ajax option is set to "Yes"


Privatemsg with user_relationships - views link → send a private message to use

solved problem with the code below:

<?php
$profile = content_profile_load('profile', $data->users_user_relationships_uid);
$url = privatemsg_get_link(array(user_load($profile->uid)));
print '
'. l(t('Send a private message to the author'), $url, array('attributes' => array('class' => 'lichnoe'))) .'
';
?>


See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme. In your case, the library name is wrong. The right format for the name is module_name/libraries_name.

/**
 * Implements hook_page_attachments().
 */
function my_module_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_module/my_module.admin';
}


How to filter views results by value of profile field of currently logged in user?

Instead of listing products filtered by Supplier field. You want to build your View from Users and add a relationship to Products linked through your Supplier field -- see this thread with further documentation:
https://drupal.org/node/1111722

So its something like the following from my above link:

  Create a user view.
  Add a contextual filter on user: uid. If no filter value is present, build a default value using the currently logged in user. (This will
  give you exactly one user object in your view -- the logged in user.)
  Add a relationship, using the relevant taxonomy reference field on the user accounts. This will bring you information about the
  "interest" term for the logged in user.
  Add another relationship, called "term: nodes marked with term" (or something like that). This will bring you information about all nodes
  marked with the interest term for the logged in user.
  Either set the view to display node teasers, or select a number of fields to display.
  Add a display as usual. Done!

Alternatively you could use Views Global Filter to set a filter based on the profile value most likely.


Storing Drupal form values when using tablesort or paging

No there's no in-built way around this. The tablesort and pager functionality works by providing links to new pages. When you link to a new page, any values you have in form elements on the previous page will not exist any more, unless they've specifically been persisted to the session and then picked up again on the new page load (this is a browser issue and nothing to do with Drupal).

The easiest thing you can do is implement AJAX for your pager/sort links which invokes the content area of the page to reload rather than navigate when they're clicked. Then your form elements will remain untouched.


function hook_menu() {
  $items = array();
  global $user;
  $user_id = $user->uid;
  $items['user/' . $user_id . '/edit'] = array(
    'title' => 'Edit account',
    'page callback' => 'MYMODULE_user_edit',
    'access callback' => 'MYMODULE_user_edit_access',
    'menu_name' => 'user-menu',
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'user.pages.inc',
    'file path' => 'modules/user'
  );

  return $items;
}

function MYMODULE_user_edit() {
  global $user;
  $account = user_load($user->uid);
  return drupal_get_form('user_profile_form', $account);
}

function MYMODULE_user_edit_access(){
  global $user;
  return user_edit_access($user);
}

Try above code. :)


Upload External File to Drupal File System

Take a look at foldershare and foldershare_rest modules, they provide entire data management pipeline on a Drupal site, along with a ready to use rest client cum command line utility. Here are couple videos that show the module's capabilities

Managing data via REST client for automation and power users (5 mins)
Managing data on SeedMeLab for users(3mins)

Disclosure: I am the maintainer for these modules.


How to add custom plugin controls to CkEditor

In ckeditor.config.js you need something like this:

CKEDITOR.editorConfig = function(config) {
  config.extraPlugins = 'vicheck';
  CKEDITOR.plugins.addExternal('vicheck', '/sites/all/plugins/ckeditor/vicheck/');
  config.toolbar_DrupalBasic = [ [ 'Bold', 'Italic', '-', 'vicheck' ] ];
}

where vicheck is a plugin.

This works for me using an old CKEditor module. I don't know if the latest versions have any change.


The %element-title is using the following invalid tokens

It seems that in order to nest those tokens a "dummy" token is needed that matches group name:

function MY_MODULE_token_info() {
  $tokens = array();
  $types = array();

  $types['master'] = array(
    'name' => 'Master group',
    'description' => 'This is the master group',
  );

  // This is needed in order to nest tokens:
  // a dummy token that is the same as nested group/type
  $tokens['master']['sub_group_1'] = array(
    'name' => 'Sub group 1',
    'description' => '1st tokens group',
    'type' => 'sub_group_1',
  );

  $types['sub_group_1'] = array(
    'name' => 'Sub group 1',
    'description' => 'This is the first sub group',
    // this tells this group that it's parent is 'master' group.
    'needs-data' => 'master',
  );

  $tokens['sub_group_1']['token_A'] = array(
    'name' => 'Token A',
    'description' => 'This token prints letter A',
  );

  return array(
    'types' => $types,
    'tokens' => $tokens,
  );
}


Entity reference item list with preview images?

The Entity Browser module almost does exactly this (for Drupal 8). The module allows you to create a view display (it adds a new Entity Browser display type) to select items and it also allows you to, via a configuration on the referencing entity's Form Display screen, display a referenced entity's view mode on the edit screen.


Best approach to move content between different instances/installations

After discussion on freenode #drupal, I have had the advice to avoid as much as possible migration or copy-content, so I am going to use a dump from preprod environment to install the production one, what I thought it wasn't the best solution, it seems in this case it will be the simplest and valid.

I'll still appreciate all kind of thoughts of this issue.


I use IMAGE URL FORMATTER module

Then on view's, click on your field, for formatter you can select Image URL.

Then on your tpl.php file use <?php print $fields["field_image_boss"]->content; ?>

Note if you see that your field gets printed with extra markup such as url instead of just url. Then you need to remove extra views container markups

On your view's edit page. Under Format click on the 1st settings and uncheck  Add views row classes and Add striping (odd/even), first/last row classes

Also, on the 2nd settings, uncheck Provide default field wrapper elements

Lastly, click on your field, and under STYLES SETTINGS make sure everything is unchecked


Have you looked into the Rules module? It's great for making conditional actions and can do stuff like sending out mails.


How to programmatically render a contact form in a theme in D8

Contact form is an entity, but you can't view it.

What you want instead is an add form of a contact_message with contact_form as bundle.

See ContactController::contactSitePage() (EDIT: API docs) as example:

$message = \Drupal::entityTypeManager()
  ->getStorage('contact_message')
  ->create(array(
    'contact_form' => $contact_form->id(),
  ));

// This works in a controller, use \Drupal::service('entity.form_builder') elsewhere.
$form = $this->entityFormBuilder()->getForm($message);
$form['#title'] = SafeMarkup::checkPlain($contact_form->label());

EDIT (thanks @nilsun): Note that entityManager is deprecated in favour of entityTypeManager.


How do I add a file upload field to user registration page?

In D7 all entities are field-able, and user profile fields can be manipulated in admin/config/people/accounts/fields

and in D6 you can use content profile module


In Drupal Commerce, how can I decrease stock of product B when buying product A with rules?

Are you using the Entity Reference module?  You will somehow need to set up the relationships between A + B + C in Drupal, and Entity Reference is one Rules-module compatible way to do this.

Another more flexible but more complicated way would be to use the Relation module.


Returning code in views search tpl but ONLY if user clicked 'search' button and results were returned

This should probably be done in a pre-processor rather than a template file, but I'll stick to the question as asked, for now:

<?php if (!empty($view->exposed_input) && !empty($rows)): ?>
 <?php if ($feed_icon): ?>
  <div class="feed-icon">
   <?php print $feed_icon; ?>
  </div>
 <?php endif; ?>
<?php endif; ?>


How to make services node output of file to use external URL instead of public:// URI

There is parse_url

Like

<?php
$url = file_create_url($field[0]['uri']);
$url = parse_url($url);
$path = $url['path'];
?>

OR  file_create_url

$usablepath = file_create_url($filesyspath);

OR

$path = str_replace('public:/', variable_get('file_public_path', 'sites/default/files'), $uri);


A "user type" is a role, right?

You can create a Year field as either a Date, Taxonomy, or plain Text field.  Then you can attach it to each of the content types that these users are allowed to post.

I have not used it myself, but I think that the Field permissions module will let you restrict this field to just the desired role.  If that does not work, you could do a little theme work to add the user's role(s) as CSS classes on the <body> tag, then hide the Year widget with CSS.


view content filtered by taxonomy children

There are two parts to your question, showing only nodes that have child terms, and getting the Contextual filter to work.

List only nodes that have child terms

This part of the question can be solved by using a regular Filter Has taxonomy term and then select only the 2nd level from the list with the Operator set to is one of.

The same applies if you add a filter Content: YourTaxonomyField instead of the Has taxonomy term.

Contextual taxonomy filter

With the main filter taking care of the depth, you don't need the Depth one as the Contextual filter.

Add Content: Has taxonomy term ID as the Contextual filter. Your example didn't have it set up correctly. It should be:
    When the filter value is NOT available
    Provide default value
    Taxonomy term ID from URL
    Only tick Load default filter from node page, that's good for related taxonomy blocks
    Filter to items that share any term
    Under More
    Allow multiple values if your nodes can be tagged with more than one term at a time.

Don't forget to place your Block and adjust Block settings for the Contextual filter.


Is it possible to call a custom module function in the theme template file?

You can do it, but it's not recommended, because in the Model-View-Controller pattern, your logic is in the Controller (in this case your module) and in the View (your .tpl file) you should only have code to show the values that comes from the Controller.
The idea is that all variables are prepared in template preprocess functions (in modules or in your template.php).
You can implement the hook_preprocess_page():
function YOUR_MODULE_preprocess_page(&$variables) {
    $variables['my_var'] = hello_world();
}

and in your page.tpl.php file you can now use $my_var to output the value set in your preprocess function:
echo $my_var;


How to count the number of checked Checkboxes with Rules?

Yes this is perfectly possible with Rules, and you don't need any PHP to get the job done. In your case, the crucial part of such rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should use (at least) these Rules Actions:

"Add a variable" (say with a machine name like nr_of_checked_terms), with initial value "0".
Add a loop related to your taxonomy terms. After you do, you should iterate over each item in that list (= each taxonomy term). And for each iteration you should then perform a Rules Action to "Set a data value", whereas you actually increment the value of nr_of_checked_terms with "1".

After the loop finished, the value of nr_of_checked_terms will be the actual number of terms that were checked. Just add another Rules Action near the end to do your actual multiplication using nr_of_checked_terms as one of the available tokens.

Done

PS 1: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.

PS 2: I assume this is about D7 ...


How do I set up a Drupal view with two relationships?

I found my answer at Multiple Node Relationships?

The answer is to go to the Relationships section and add two relationships, each for your node references. You'll find them under the 'Content' group. When adding the second relationship, select it to use the first relationship so that they chain. That will get you "base" node being the lowest level child, the first relationship is that node's parent, and the second relationship is the grandparent.
Then, add the Node: title field 3 times. Set 1 to use no relationship, 1 to use the first relationship, and 1 to use the second. Preview your view. That should get you the basis for what you want. Add sorts, filters and other fields to taste.


Migrate content types and contents from old drupal version to drupal 8

Take a look at this one, it pretty simple to migrate content types, fields, terms, users using below module:
https://drupalize.me/blog/201511/simple-drupal-7-drupal-8-migration

And this module does all the work:
https://www.drupal.org/project/migrate_upgrade


Access to a website only when I grant them access

Ah, you don't need to be doing stuff like that with PHP. Drupal has plenty of tools to handle permissions for users.

Drupal already has the ability to allow you to make sure users need to be approved by an admin - check the user settings.

As for restricting access to "enter" site... well you need to review your user permissions table. "enter" is a pretty vague word to be using in Drupal terms.


How do I reroute a logged-in user after page access denied at user/login?

That sounds like a familiar question ... Here is how I was able to solve it so far (not sure if there are better ways to do so ...):

within /admin/settings/error-reporting I entered a relative URL like no_access
then I created a no_access page, in which I described what might be causing the problem.

For a sample of such no_access page, visit http://www.inpetto.be/no_access (access allowed by anybody ...). Note bullet nr 2 there ...

Makes sense?


How to remove default form tag while rendering output in hook_theme

You're attacking the problem at the wrong level - if you want to modify forms/functionality, the theme layer's too late. Specifically what's happening here is that by default forms have a theme wrapper of theme_form() which adds the form tag. The form template itself should only contain the form's children elements. (And shouldn't contain for example calls to drupal_get_function()).

Here are some ways of adding the forms:

Implement hook_menu_alter() and alter the page callback for the login page to be your own callback. This callback returns the three forms. Don't forget to check for whether the user's logged in like core does.
Create a couple of custom blocks for the other two forms and add them to the login page.
Implement hook_page_build() and add the forms there (quick and dirty!).


I was following the docs, which told me to execute the command in my 'From your Drupal directory', so I executed the command on my Drupal installation root directory.

I have a multi-site set up, and running it inside my site directory /sites/mysite/ worked.


can't import sql dump to new database for backup

You can use mysql on the command line to avoid timeouts when updating big dbs.

Example:

mysql --password=yourpw --user=name --default-character-set=utf-8 db_name <your_dump.sql

See mysql -? or the manpage for more options.


How do I theme a menu to have a wrapper div with menu name?

theme_menu_tree() is a theme wrapper function: it's called after the render array for the menu tree is rendered, and thus, after you have a chance to modify the rendered output.

Additionally, you can't pass any arbitrary data to a theme wrapper function: it'll always receive the rendered output of the children.

So to do what you want to do, where you have a wrapper
 that has an ID, you need to modify the menu tree render array to call your own theme function that adds it.

Practical example

Let's say you're trying to do this for all menu blocks (a common use-case for menu trees): menu_block_view() populates the content of the block with menu_tree($delta), where $delta happens to be the menu name corresponding to the block.

Now, menu_tree() calls menu_tree_output(), which is where the render array that calls theme_menu_tree() is built.

So, what you want to do is modify the contents of the block after the render array is built, to replace theme_menu_tree() with your own theme function that adds your
 with ID. To do that, implement hook_block_view_alter():

/**
 * Implements hook_block_view_alter().
 */
function MYMODULE_block_view_alter(&$data, $block) {
  // Check to make sure this is a menu block
  if (in_array($block->delta, menu_get_names())) {
    // Replace the theme wrapper function with a theme function
    // and add the menu name to the render array
    unset($data['content']['#theme_wrappers']);
    $data['content']['#theme'] = 'MYMODULE_menu_tree_with_id__' . $block->delta;
    $data['content']['#menu_name'] = $block->delta;
  }
}

Replace MYMODULE with your module's short name. Once implemented, create the theme function theme_MYMODULE_menu_tree_with_id() to handle wrapper
:

/**
 * Implements hook_theme().
 */
function MYMODULE_theme() {
  $theme = array();
  $theme['MYMODULE_menu_tree_with_id'] = array(
    'render element' => 'element',
  );
  return $theme;
}

/**
 * Returns a menu tree with an id corresonding to the menu name.
 */
function theme_MYMODULE_menu_tree_with_id($variables) {
  $output = '
';
  $output .= '
' . drupal_render_children($variables['element']) . '
';
  $output .= '
';

  return $output;
}


Search API Autocomplete does not return any suggestions when input contains ąčęėįšųūž or similar characters

Install the Transliteration module and enable the homonymous processor for the index.


Dynamic default values in WebForm Drupal 8.x

You can place a webform anywhere in code, examples are a controller, a block or a preprocess hook in a theme. Put the dynamic default values in #default_data:

/src/Controller/WebformController.php

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * A webform controller.
 */
class WebformController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function webform() {

    // generate dynamic default values
    $name = 'John Doe';
    $message = 'This content is generated dynamically.';

    // add this to a webform
    $build['form']  = [
      '#type' => 'webform',
      '#webform' => 'contact',
      '#default_data' => [
        'name' => $name,
        'message' => $message,
      ],
    ];

    return $build;
  }

}

mymodule.routing.yml

mymodule.webform:
  path: '/mywebform'
  defaults:
    _controller: '\Drupal\mymodule\Controller\WebformController:webform'
    _title: 'My Webform'
  requirements:
    _permission: 'access content'


How to import multiple values in a text field with Feeds module?

Feeds Tamper will do this for you.

  Feeds Tamper provides a small plugin architecture for Feeds to modify
  data before it gets saved. Several plugins are available by default
  and are described in the examples section below. Additional plugins
  can be added in separate modules or through the issue queue.

One of the default plugins is explode.  Just set up a feed tamper to take your multivalued field from your CSV and explode it based on whatever delimiter you fancy.  This will import it as multiple field values.


You cannot call menu_tree() from within theme_menu_tree() because menu_tree() contains a call to theme_menu_tree(). Your code contains an infinite loop.


You can extend Omega Theme and override the css in your global.css file. So you will have  a new theme and core files are intact.

All you need to install is  Omega Theme. And the By going to Appearence you can create a new theme and override the css files.


Replicating an existing table-based form as PDF views output?

Just a shot in the dark, but the Slickgrid module may be of help in this situation. Here is an excerpt about it from the module's project page:

... is an implementation of Michael Leibman's jquery slickgrid plugin, a lightening fast JavaScript grid/spreadsheet.
It defines a slickgrid view style, so all data can be output as an editable grid.


Change taxonomy list automatically generated paths

Are you using pathauto?

Check patterns at admin/config/search/path/patterns and then update URL aliases


How do I check a custom field has a value?

To my knowledge the current answer to this question is: you can't do that yet with the most recent D8 version of Rules. Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here is a quote from it:

  ... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

One never realizes what has been done, only what remains to be done ... So start here if you wonder how to contribute.


Deleted FAVICON from themes folder is showing up

Now Its corrected...

On Themes Global Settings I have mentioned the same favicon in differnet folder.

Thats why the deleted favicon dispalyed even after deleting it from the themes folder.

Thanks for your efforts friends...


How to override the user edit page using Panels?

user_edit panel default context is the current edited user. Why do you need to add an additional context with a user?

If you need to access to user values you can use the default context. For example you can use %user:uid in order to load the user ID which is being edited.


remove description in views exposed filter

it can be done either via theme or custom module:

function MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id)
{
    if($form['#id'] == 'FORM_NAME')
    {
        $form['#info']['filter-FIELD_MACHINE_NAME']['label'] = '';
    }
}

use dpm($form); from the Devel Module to get the complete form name, and field names for non-content type filter criteria:

A suite of modules containing fun for module developers and themers ...

  Devel Helper functions for Drupal developers and inquisitive admins.
  This module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries). Also a dprint_r($array) function is
  provided, which pretty prints arrays. Useful during development.
  Similarly, a ddebug_backtrace() is offerred.

Be aware that removing the label (description) will change the layout of the filter itself, so some css might be required to fix things.


What does cron error "exit status 4" mean in syslog? (Ubuntu)

Ok, I'm such an idiot sometimes.

I've edited the .htaccess file this morning to redirect without www. to www.domain.com and that has caused my cron going to localhost to be redirected to www.localhost which caused the cron to fail. /facepalm

But to answer exit status 4's meaning for wget according to this page it means Network failure (Kudos to @Clive)


Override remove entities link on module uninstall page

If you're solely looking to alter those messages & links, you could to override the required_module_uninstall_validator service with a custom class that extends ContentUninstallValidator and alters its validate() method:
// In your ContentUninstallValidator child class
public function validate($module) {
  $reasons = parent::validate($module);
  // @TODO find/alter the message & link relevant to the module
  return $reasons;
}

However, you'll have to deal with the issue of searching through messages and being able to find the string relevant to the module. This could be problematic depending on how you're searching through the messages array.
A better approach might be to add new messages via a new uninstall validator service that can provide its own custom messages & links that will initiate your own custom entity cleanup code.
A good working example can be seen in the book module:

Defines the service in book.services.yml:

      book.uninstall_validator:
        class: Drupal\book\BookUninstallValidator
        tags:
          - { name: module_install.uninstall_validator }
        arguments: ['@book.outline_storage', '@entity_type.manager', '@string_translation']
        lazy: true

Handles validation & generates new messages in BookUninstallValidator::validate():

    public function validate($module) {
      $reasons = [];
      if ($module == 'book') {
        if ($this
          ->hasBookOutlines()) {
          $reasons[] = $this
            ->t('To uninstall Book, delete all content that is part of a book');
        }
      }
      ...
      return $reasons;
    }


It's not necessary to use a private temp store for anonymous user if you don't have a lot of data. And for anonymous it's not so easy to implement this.

To store data for anonymous users you can simply use the php $_SESSION variable.

$_SESSION['my_module']['data'] = 'My Data';

Drupal will take care of starting and saving the session.

Edit:

OK, to make this official, you should use the request object. See https://www.drupal.org/node/2380327. But drupal core and contrib code still uses the $_SESSION variable. This should be OK at least for D8.

In both cases you have not to handle the session yourself. Drupal will load the session if there is one present when it begins with the request. And drupal will start a new session and saves it at the end of the request, if there is newly added session data.


Drupal should have created an .htaccess file in that directory with Deny from All per the File documentation. Check to see if this is the case. This post may also be helpful: Noob question about private files and Content Access.


How to change title of "Log in" link in account menu for anonymous users?

As described by @Matt in the answer the menu link is provided by the user module and you can simply decide not to use it and build your own links.

The link in the user module is a dynamic link where a menu link plugin  generates a different title depending on whether the user is authenticated or not.

To change the title you can replace this plugin class:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function mymodule_menu_links_discovered_alter(&$links) {
  $links['user.logout']['class'] = 'Drupal\mymodule\Plugin\Menu\MyLoginLogoutMenuLink';
}

and override the method getTitle() with your own content:

mymodule/src/Plugin/Menu/MyLoginLogoutMenuLink.php:

<?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\user\Plugin\Menu\LoginLogoutMenuLink;

class MyLoginLogoutMenuLink extends LoginLogoutMenuLink {

  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('My Log out');
    }
    else {
      return $this->t('My Log in');
    }
  }

}

A third option would be to change the title in an English to English translation, see How do I translate to English?


How to make user's access to nodes depend on the year a node relates to?

Option 1 - Add a field to reflect the year

If you'd add a (select list) field to indicate the year that the basic page relate to, you could use the value of that field with some Rules conditions to perform all sorts of validations to prevent a user creating and/or updating pages for any years you do not want to allow.

The Rules Event would probably be "Before saving content". And the Rules Conditions would simply be (a) "Entity has field" (for this extra field) and (b) "data comparison" (to find out which year the basic page is about).

Option 2 - Use the Group module

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

So to answer this question, you'd create a group for each year. For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources:

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

PS: Group is available as of D7, and has a D8 version also.


Is there a way to export the whole panelizer settings for a page?

You can do this with Features:

Enable Strongarm module
Create new feature
Export and Deploy Panelizer settings

Alternatively you can do this with a custom module. See https://www.phase2technology.com/blog/exporting-panelizer-defaults-to-code/


How to display a node edit form in custom URL

Create a new menu item in a custom module
# mymodule.routing.yml

mymodule.banner_settings_form:
  path: /admin/config/system/banner-settings/{node}
  defaults:
    _entity_form: node.edit
    # Copy UUID from exported default content.
    node: 05d6a9e5-6e78-42bb-b3fe-b9a6344f4022
  requirements:
    _entity_access: node.update
    # Custom permission check.
    _permission: 'administer site banner configuration'
  options:
    _admin_route: true
    _node_operation_route: true
    parameters:
      node:
        type: 'entity:node'
        # Part of jsonapi module.
        converter: paramconverter.jsonapi.entity_uuid

Visiting /admin/config/system/banner-settings would take the default UUID value from the route and renders the form.
P.S: After saving the form it would redirect back to node/[nid] and this can be avoided by passing ?destination=<your path> in the link.


How to create many workbench moderation flows / scenarios

I think what you need is Workbench Moderation Types


Omega - Debugging blocks only for specified role

If you're user uid=1 (administrator), you'll see everything regardless of role. You may be confusing it with the "administrator" role, which is not the same as the admin user.


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

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

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

EDIT

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


Drupal File upload only allowing one upload at a time

Probably same issue as here
https://drupal.stackexchange.com/a/112999

As suggested in the post above,
you should consider Plupload and file field sources, you'll never look back,
imagine dragging 10 files from your explorer/finder to your form field and uploaden them all at once ... ;)


How to get vocabularies for an entity reference to a taxonomy?

So here is my process (it won't work when you're loading in the relevant entity types via a view, only by the "default" method):

$type is the content type, $field is the field of the ER.

$field_data = \Drupal::config('field.field.node.' . $type . "." . $field)->get();

$bundles = $field_data['settings']['handler_settings']['target_bundles'];

At which point you can iterate over the given bundles for an ER.

You'll probably want to do some flow control somewhere to ensure the ER has the correct handler you want - located here:

$handler = $field_data['settings']['handler'];

But this should work to get the data I asked for above.


How to limit a user to specific OG groups based on user role?

Due to other restrictions in OG I couldn't overcome, I ended up using the Group module instead. In addition to other advantages for my use case, it offers some functions to easily add group memberships (these are entities) by using something like

$entity_type = 'group_membership';
$entity = entity_create($entity_type, array('gid' => $gid, 'uid' => $uid));
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->status = 'active';
$wrapper->added_on = time();
$wrapper->added_by = 1;
$wrapper->save();

Adding that into a hook_user_update(&$edit, $account, $category) function, I am able to add and revoke memberships based on the updated account's roles.


You should be able to accomplish this by using Auto Node Title . This will generate automatic node titles, and allows PHP to define that title. Using str_replace  you can remove the slashes from a date field and replacing them with nothing, creating the desired effect. Then use a token or static text in the title for the rest of it

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.


How to include IP address Token with Rules?

Option 1: Create new Rules variables

Have a look at this prototype of a custom rule (in Rules export format):

{ "rules_send_email_with_user_agent_and_ip_address" : {
    "LABEL" : "Send email with User Agent and IP Address",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "\u003C?php print ip_address(); ?\u003E" },
          "PROVIDE" : { "variable_added" : { "useripaddress" : "User IP address" } }
        }
      },
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003C?php print $_SERVER[\u0027HTTP_USER_AGENT\u0027]; ?\u003E"
          },
          "PROVIDE" : { "variable_added" : { "useragent" : "User Agent" } }
        }
      },
      { "drupal_message" : { "message" : "User Ip Address is [useripaddress:value] and User Agent is [useragent:value]" } },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "User [account:name] performed a login from Ip Address [useripaddress:value]",
          "message" : "User [account:name] performed a login from Ip Address [useripaddress:value] (User Agent is [useragent:value]).",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some details about this rule:

Rules Event: User has logged in (replace with whatever event fits for you).
Rules Conditions: none (add whatever conditions you want).
Rules Actions:

Add a variable, with label "User IP address", machine name useripaddress and with initial value the result of this PHP evaluation: <?php print ip_address(); ?>.
Add a variable, with label "User Agent", machine name useragent and with initial value the result of this PHP evaluation: <?php print $_SERVER['HTTP_USER_AGENT']; ?>.
Show a message on the site, with a message value like User Ip Address is [useripaddress:value] and User Agent is [useragent:value] (just for QA testing, remove this Rules Action after you're convinced it works OK).
Send email, with an eMail body like User [account:name] performed a login from Ip Address [useripaddress:value] (User Agent is [useragent:value])., and a similar eMail subject (replace with whatever eMail subject/body that fits for you).

If you have the Rules UI enabled (and the dangerous PHP filter ...) you should be able to import it in your own site also.

Attention: this rule requires the dangerous PHP filter to be enabled (which personally I try to avoid at any cost ...). But if anything else fails, this is "a" solution to get it to work. As an alternative, you could create a custom module in which you create your custom Rules Actions for creating such eMail, and in which you'd include some PHP code similar to the PHP code in the rules Actions shown in the above Rules Actions. Refer to my answer to "How to create custom rules action event conditions?" for more details about that. Or refer to this part of the Commerce Google Analytics module which adds 2 Rules Actions related to User Agent and User IP address.

Option 2: Use the Message module

If you're willing to also use the Message module (and have sufficient experience in using it ...), you could implement a rule like so:

Create an appropriate message entity, which refers to a "message type" in which you can refer to token [current-user:ip-address] (= The IP address of the current user). This token comes, out of the box, with the Message module.
Include some type of pointer/reference to the created message in your eMail, or use the Message Notify module to get the created message entity delivered as an eMail.
For your User-agent token their might be a similar token available already in the Message module also. Though so far I've not found / discovered that one. However, using the technique of "replacement tokens", you should be able to create such token (via Rules), and then include that in your Message type also. For an example to see those replacement tokens at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".

Refer to this question for a zillion of other samples/cases about the amazing Message module.


How to automatically link specific words in a node to other nodes?

I would definitely use taxonomy for the relation between node and word, I would then use hook_node_save to alter the value of the body and add the links with a preg_replace. By adding a specific class to those links you can then remove those links with hook_form_alter before the body field is displayed for editing.


Configuration settings in filedepot for folders

Is this a job for the Content Access module?

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


How do I bulk delete field collection items that are part of a content type?

I created a view that lets us filter by username(so that we can delete for a particular company/user) and course dates(so that we can filter courses with selected dates). It will delete all fields within the field collections for the selected courses. Courses display in rows for each date instance, e.g. if a course has many dates then it displays in a new row with each date field collection item.

I created a content view with a relationships to the field collections-field collection items, author and content field of the field collections attached to my content type for which I selected Delta=All).

I then added fields with the course title, date, venue, location and field collection item ID and displayed in a table with the VBO set to delete the selected field collection items for each instance.

I have filter criteria for the content type, username(author)-exposed, and field collection item for the date-exposed so that I can filter by date to delete old items.

I hope I was able to explain the solution that worked for me so that it can at least offer a clue to someone else with a similar problem.


How can I transition an order from fulfillment to completed?

Perhaps one way to do this would be similar to what you can find in modules/contrib/commerce/modules/order/templates/commerce-order--admin.html.twig
{# If the order has possible transitions, render the field for transition buttons. #}
{% if order_entity.getState.getTransitions is not empty %}
<div class="entity-meta__header">
  {{ order.state }}
</div>
{% endif %}

If the order is configured to pass from state fullfilled to completed the appropriate button for moving state should be available there.  Make sure your order_entity is passed to the twig template.
Read more about order workflow states


feeds importer importing from several sources

Yes, there is. The supported way of importing multiple sources for one importer is to attach the importer to a content type (which can be configured under the "Basic settings"). Attaching an importer to a content type means that a node must be created to import content. Since you can create multiple nodes, you can import multiple sources with one importer configuration.

Be sure though that if you are importing nodes (using the Node processor) that the nodes you create are of a different type than the node type that you attach an importer to. It is wise to create a new content type that is specifically only used for your importer.

See also my answer at https://www.drupal.org/node/2854548#comment-11948926 for more information about why you should not attach an importer to the same content type as the one you select on the processor settings.


I don't know if it's simpler, it really depends on your set up, but you could look at the Field default token module:

  This module enables to use tokens as field default values.

with this you can assign default values using tokens, such as current user, etc.


How to show field collection items with comma separated in views?

The basic setting for fields with multiple values actually has that as default. When you are adding the field into your view click on the multiple field settings tab and it will show you the functions to do just this.


Sending data via post and redirecting user

Your submit function name is wrong , your submit function not called at all, In Drupal if you have form name x then the submit should be x_submit, so in your case the submit function should be

payment_upload_form_submit


It seems like instead of rendering the views programmatically you could also leverage the Views "Attachment" display .  The allows you to attach a view to another display, in other words render one view after another.  The "block_1" display of the view you posted above would be the main view displayed as a block, and then you would change the "block_2" display to an attachment and configure the settings similar to the image below.

This would eliminate the need to create custom code to display both views in a block.


which one has better performance to load views

views_embed_view is just a wrapper for views_get_view:

function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

So how would you set dynamic arguments on views_embed_view? With views_get_view you can at least do this:

  $view = views_get_view($view_name);
  if (!$view || !$view->access($display_id)) {
    return;
  }
  $view->set_display($display_id);
  $view->set_arguments($variables);
  $view->pre_execute();
  $view->execute();
  return $view->render();

module_invoke for block is too roundabout and limited for my liking. Why limit yourself to a block when you can choose from any display available?

views_block_view contains this snippet:

if ($view = views_get_view($name)) {

So it also uses Views_get_view.

Performance-wise I reckon the differences are negligible.

So, IMO, views_get_view wins.


Install a distro from an online repository core make file

Unfortunately the Drush Make infra does not support this use-case well.

The quickest wordaround is to clone the project Git repository and provide a local path to the makefile in the Aegir UI.

For elmsmedia I guess the best makefile would be http://cgit.drupalcode.org/elmsmedia/tree/local.make.example

OpanAtrium has http://cgit.drupalcode.org/openatrium/tree/build-openatrium.make for this same purpose.


Adding a custom data-attribute to a field in Views

To summarize for future reference:

You can add data attributes using Rewrite in Views Fields.

If you added a custom data-attribute but something isn't working, the problem might be in the value ;)

What gets stripped by the filter_xss_admin() on Rewrite is most notably the <object> tag and style="" attribute because users can submit malicious code through those.

It seems Views for D7 will have that check removed in the next release: Remove filter_xss_admin() from result rewriting because views editors are already trusted admins


Change the url path of /sites/default/files/myfile.pdf

Go to this path /admin/config/media/file-system, and change the public file system path.

It might be this, sites/default/files, change it to files.

Then create a writeable folder in your webroot called files.

This could also be done by adding this line in the settings.php file:

$settings['file_public_path'] = 'files';

Just note that this is only for local development if you want to deploy this change you might use the above solution and then export the configuration.


Apply custom date formats to reporting for specific webforms and fields

It seems that the only way to make this happen was to reset the system's Short Date Format to my custom format A. Thankfully, the webform custom DOB field uses a similar format (the same thing but without the hour and minutes.)

If anyone knows a better way where I could have done this on a "per form" and "per field" basis, please add your answer as the one I am providing now isn't really what I was looking for.


How to display an overlay image in modal window (Colorbox) upon hover

You would probably have to write some custom javascript / jquery in your theme's JS file and call the colorbox function on hover. For example:

$('.img-1').hover(function(){
  $('.img-2').colorbox();
});

That's only the starting point. Once it is working with just 2 images, the next step would be to dynamically pair all the images so the javascript knows which image to show on hover.


Grant permission for custom role from hook_install programmatically

Try this:

use Drupal\user\Entity\Role;

function mymodule_install() {
  $role_object = Role::load('my custom role name');
  $role_object->grantPermission('my custom permission name');
  $role_object->save();
}


what does hook_field_is_empty actually mean?

I think it's used for fields that can accept multiple values, to determine whether or not the last item in the list has been filled out, or is in the 'new' state without having been filled out.

If this function didn't exist the field API wouldn't be able to make a distinction between what is classed as a filled-in row, and what is a 'New' row that hasn't been filled out, and for which the values should not be saved.

It can also be used to ensure that a minimum of columns in a field are filled out before it's classed as a save-able value.

If I remember rightly the hook is 'required' for modules that provide a field, so I'm not sure if you'll get away with leaving it out.

You could easily just implement it and return a TRUE or FALSE though for testing purposes.


How to alter view query to display only 5 top records

If within the Views Pager options, you select "Display a specified number of items" and set "Items to display" to 5, you will get the behavior you are desiring.  You just need to make sure your sort criteria provides whatever "top" means on your site.  What I think you are doing instead is selecting "Use Pager" with 5 items.


How do I replace part of a webform component label with a variable token?

hook_form_alter() should allow you to so.

Within your theme you should be able to do something like :

/*
 * Implementation of hook_form_alter()
 */
function my_theme_form_alter(&$form, &$form_state, $form_id){
  // target my form / my field
  if ($form_id == "my_form") {
    if ( $form['my_field']['#title'] ) {
      $title =  $form['my_field']['#title'];
      $token_val = get_tokenised_value(); // Which ever way you handle that...
      $title = str_replace('[your pet]', $token_val, $title);
      $form['my_field']['#title'] = $title;
    }
  }
}

Also check the forms api reference to see what things you can set / alter on forms.


form_state->setRedirect(to_a_new_node_page) from the submitForm function, route "does not exist" issue

I think if you want to use the setRedirect function then you might want to look at its documentation found https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AsetRedirect/8

You can then base the ff. code from FormSubmitter::redirectForm or FormSubmitterInterface::redirectForm. So your code might look something like:

$form_state->setRedirect('entity.node.canonical',
  array('node' => $mynewnode->id()),
));

You can also find out where is "entity.node.canonical" from by searching in core/modules/node and where it is declared and what it's about.

Hope everything's going great!


Views to use currentlylogged in UID or override via URL

I think what you're going to need to do is clone your display. One display using path 'myproject/test' where you contextual filter uses 'Provide default value' when the filter is not in the URL, with 'User ID from the logged in user' as the type.

The other display will use the path 'myproject/%/test' and since the filter in this case IS provided by the URL, you can do something like 'Show "Page not Found"' if the filter value is not provided by the URL. You'll probably also want to specify a validation criteria using the numeric validator with 'Show "Page not found"' as the action to take if it doesn't validate.


Where is views exposed form's submit handler located?

All of its functions are handled in programmatic way. You can look all functions are declared in theme.inc file located at module/views/theme/theme.inc location. Its hard to understand that core functions. But if you want to play with these functions then you will have to use the hooks .

NOTE: Never try to change any core file.


Load custom library when form contains special field type

I addedsome values in the render array of the formElement method in my customWidget class.

'#attached' => array(
    'library' => array(
      'core/jquery',
      'rate_field/admin-star-field',
    ),


Single content type with urls that can differ

If your Location, Listing type, and title are Fields in your Content type you can use Pathauto Patterns options (/admin/config/search/path/patterns) to automatically generate the aliases from values in nodes.

You use tokens available for the content type to construct the pattern. You can browse through (a very long) list of tokens to find the one you're looking for. Maybe it would be something like:

[node:field_type]/[node:field_location]/[node:title]


Today I've discovered this site: http://www.drupaldeploy.org:

  A next generation comprehensive yet easy to use content staging
  solution built for Drupal developers and end users

There are several modules that work together, the "base" module should be Deploy:

  The Deploy module is designed to allow users to easily stage and
  preview content for a Drupal site. Deploy automatically manages
  dependencies between entities (like node references). It is designed
  to have a rich API which can be easily extended to be used in a
  variety of content staging situations.

On drupaldeploy.org you can find related modules.


How to suppress "new" indicator for imported content?

You could suppress this in the theme layer, by doing a rewrite on the rendered output? That might be much safer than any kind of database hack.


Javascript not loaded in loading ctools modal

this looks like a hook_menu() implementation:

$items['share/%ctools_js/%'] = array(
// 'page callback' => 'ym_alter_sharing_content',
'page callback' => 'ym_alter_sharing_callback',
'page arguments' => array(1),
'access callback' => 'user_is_logged_in',
'type' => MENU_CALLBACK,

);

you should wrap it in a corresponding function and return menu items:

function your_module_name_menu() {
  $items['share/%ctools_js/%'] = array(
    // 'page callback' => 'ym_alter_sharing_content',
    'page callback' => 'ym_alter_sharing_callback',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

other code seems to be ok.
Hope this helps someone.


So I partly was able to access webform values. I still have a problem, that I cannot access to one single submission, altough I tried $sid = GET[sid] method. So here is my partly good code:

    //simple first section

Registration

1. Registered Data:

[submission:values:personal_info:key]

2.  Declaration:

<?php
$submissions = webform_get_submissions(array('nid'=>1));
foreach ($submissions as $submission){
foreach ($submission->data as $row=>$data){
        if ($row == 4){
              if (in_array("0", $data)) {
                    print("long boring text content");
}}}}
?>

So still not what I wanted but that is another question.


How to get a list of Users as values for a select list field?

You will want to install a module that allows you to reference a user. A popular choice is entityreference.

With Entity Reference you can create a view of User's with a display type of Entity Reference. You can then add a filter to your view to only show users with the role that you are interested in.

Then you can setup a new field on your content type of the type, reference. Within that fields settings you can specify your view to be used as the mode for "Entity Selection".

You only need to setup the view if you want to limit the users that are selectable. If any user would be valid for your field, Entity Reference has some built in modes for entity selection that makes the process even easier.


Drupal 7: Using Views to display articles with a taxonomy that is also selected for the current user

Found my own solution:
See this link: http://blog.ampli.fi/filtering-a-drupal-7-view-based-on-a-user-profile-field/


A multisite is really just multiple sites that happen to share the same code base. Unless you do crazy things with sharing prefixes (which I would really, really recommend against), the fact that you are sharing code is completely irrelvant to the running site/configuration.

So, there is no such thing as sub-sites. Just sites. And it doesn't matter if the have the same UUID's in different sites.


How to resolve the error when adding an entity reference relationship?

It looks like your issue is because of the Multifield issue Add Views API integration for the multifield field type. And that the patch attached to comment nr 96 of this issue solves it.


When to use a php function vs a drupal_ equivalent function?

Most PHP string function don't handle unicode characters. For this you need to use their mb_* variants, which are (were?) not always available on some host. The drupal_* variants ensure unicode compatibility. They wrap mb_* functions and provide pure PHP implementations for when they are not available.

So, this recommendation is there to ensure portability of your code across hosts.


Are you talking about getting the actual filesize or just formatting the size?

If the first, you can add a relationship to the {files} table in your view so that you can pull in the filesize column.  IIRC, you add a relationship to the fid and then you will see File: Size in the fields.  This will not work, though, if you manually overwrite the files via SFTP, etc.

You are getting the error because of the difference between the web path and the actual filesystem path.


List groups own content and all non-group content on groups page

Solved! I used hook_views_query_alter().

function MY_MODULE_views_query_alter(&$view, &$query) {
  if($view->name == 'VIEW_NAME') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if (strpos($condition['field'], 'og_membership_node.gid') === 0) {
          $condition_group['conditions'][] = array(
            'field' => 'og_membership_node.gid',
            'value' => NULL,
            'operator' => 'is'
          );
          $condition_group['type'] = 'OR';
        }
      }
    }
  }
}


Rendering Taxonomy Custom Fields in page.tpl.php

I suggest taking a look at the 2 answers to this question. I think it's a similar case.


What arguments should I pass to l() so that the generated link would open a new popup window?

The link formatter function l() takes 3 arguments:

l($text, $path, array $options = array());

The $options array specifies the parameters to be passed to the link. One of them is $options['attributes'] which is itself an array and is used to specify the attributes of the anchor tag.

Use something like:

$options['attributes'] = array( 'target' => '_blank' );

when you are assembling the parameters to pass. This will open the link in a new window., which is the closest you can get with HTML.

For a real pop-up, you will have to add javascript to do the job, and adding something like:

$options['attributes'] = array( 'class' => 'popup' );

will give the javascript a target to use.


inheriting fields from a base content type

Short answer: I would simple go with sharing these four fields across the content types that you have. This is boring and repetitive work, but I'm not aware of a well-established way to do it otherwise, so this is the safest bet in my opinion. This gained a bad reputation in D6 as it caused performance problems, but in D7 there is no difference.

Longer answer: I did try copy/pasting of features code at one point, it works, but is quite messy and carries a large risk of "getting it wrong" as it's not documented nor entirely obvious what code needs to be updated.

As Joe Beuckman suggests, creating a custom entity is one way of solving this as well. If you add your shared data columns as entity "properties" instead of fields, they will be shared across all bundles of that entity type. A core example of this is the "title" property on nodes. A lot of modules today work in a entity agnostic fashion, but it's important however to note that the entity API was far from finished in D7. There is no general way for example to handle "entity access" which may or may not be a problem.

Also, on the last approach, you may also want to take a look at the Entity Construction Kit (ECK) module. I haven't used it myself yet, but I believe it could be helpful in creating new entities.


jQuery should be available to you right out of the box in D7 if I remember correctly. But you need to use jQuery(...) instead of $(...). If jQuery is not being included for some reason, try using drupal_add_js().

See Drupal 7 JavaScript API documentation for more information.


Previous/ next navigation in taxonomy terms

We will make a view, load the term from contextual argument, get its weight into $static variable, and check on each row if row's term's weight is higher than our arg's one.

Create a view of terms, order them by weight.
Display only 1 item.
Add and hide taxonomy term: weight field.
Add a contextual filter : Taxonomy term: Term ID
Add a PhP filter and :

Setup code :

$static = taxonomy_term_load($view->args[0]);
$static = intval($static->weight);

Filter code :

if(intval($data->taxonomy_term_data_weight) < $static) {return TRUE;}

If you're sure that your terms have following weight, you can use that filter code :

if(intval($data->taxonomy_term_data_weight) == intval($static - 1) || intval($data->taxonomy_term_data_weight) == intval($static + 1) ) {return TRUE;}

to get the next and following terms. But careful with 0 and last values... :)

And of course, in that case, you have to display all items in the view.


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

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


How to get a remote file and set it as a value for a file field using entity metadata wrappers?

Since @xurshid29 never post the correct answer here, I am posting it cause I find it "hard" to retrieve the comments:

(from @ЕлинЙ post)

// Retrieve file from web service (this works, I can see and open the retrieved file)
$file = system_retrieve_file($file_url, 'public://path/', TRUE);
$file = (array) $file;
$file['display'] = 1;
$file['description'] = '';

$ewrapper = entity_metadata_wrapper('node', $nid)

// Set this file as a value for the node's file field.
$ewrapper->field_pdffile->set($file);

More info on system_retrieve_file

And thanks to both of you for your work!