How can I bypass the Minimum cache lifetime when programmatically clearing the cache? Is it possible to clear the cache of individual node without regard to the minimum cache lifetime in the cache settings Drupal 7?

It seems like node_save clears the cache:

entity_get_controller('node')->resetCache(array($node->nid));

However, that respects the minimum cache lifetime.

This is an issue when unpublished saved nodes go from an unpublished to a published state. Users served from the cache can't see the page until it expires, and it's immediately shared on Facebook or Twitter, those who click get a page not found 404.

I'm stuck using the Clear all caches button on /admin/config/development/performance. That seems like a heavy-handed approach.

Is there a better way?

Is cache_clear_all(); (called with no-params) the programmatic equivalent of the Clear all caches button?

Thanks in advance for any help!

First, a couple contextual comments on all this:

You are probably getting a 403 (Access Denied) message instead of a 404 (Not Found) message when visiting a previously unpublished page that was cached.
The method call that you referenced (entity_get_controller('node')->resetCache(array($node->nid))) within node_save() does not have anything to do with the page cache, and is instead related to the static entity cache, which only has an impact on the current request. However, you are certainly correct that Drupal makes an effort to clear the page cache upon a node save, but that happens in node_form_sumbit() when it calls cache_clear_all() at the end.
The cache clearing methods in Drupal are very strange and non-intuitive. I've seen entire threads erupt in passionate arguments and misunderstandings over the workings of cache_clear_all() and DrupalDatabaseCache::clear().

If cache_clear_all() is called without any arguments, as is the case on a node update, only the page and block cache bins will be targeted for clearing. That's fine as it's presumably the page cache that matters in your case, but as you noted the "Minimal Cache Lifetime" will be respected. The exact logic used to respect this "Minimal Cache Lifetime" (in DrupalDatabaseCache::clear()) might make your mind melt... but that's an aside.

As indirectly noted in another answer, you can call cache_clear_all() with a specific node URL to force the needed page_cache entry to be cleared. This will do the job independent of the "Minimal Cache Lifetime" which, IMHO, is quite non-intuitive. Thankfully there are tools that account for all this non-intuitive logic for us, like the Expire module. Not only does it have the ability to target certain actions in Drupal (such as a node update), and clear the cache when they happen, but it will do it in such a way that the "Minimal Cache Lifetime" is factored-in and bypassed as needed. There is an old issue thread here that seems to talk about this a little more.

Also, if you have another page cache active (Varnish, Boost, etc.) they may be suspect too, and may be returning a previously cached version of the request independent of the local Drupal page cache. If you have an external cache like this in place you should check its own settings along with the the core "Expiration of cached pages" setting (just below the "Minimal Cache Lifetime" setting). Once again, the Expire module can help here as it also integrates with external caches to sync their expirations with Drupal updates.


Using batch api without a form I have a page which uses the form api. When I go to that page via hook_menu I want to run a batch script.

I have looked at the batch example module and have come up with the following:

My page code

...

batch_set(my_batch());
die(); // removing this has no affect

...

Rest of the code

function my_batch() {
  $max = 10000;
  $increment = 1000;

  drupal_set_message(t('Creating batch'));

  $operations = array();

  for ($i = 0; $i < $max; $i = $i + $increment) {
    $operations[] = array(
      'batch_example_op_1',
      array(
        $i,
        $increment
      ),
    );
  }
  $batch = array(
    'operations' => $operations,
    'finished' => 'batch_example_finished',
  );
  return $batch;
}

/**
 * Batch operation for batch 1: load a node.
 *
 * This is the function that is called on each operation in batch 1.
 */
function batch_example_op_1($count, $increment) {
  drupal_set_message('Count is : ' . $count);
  $context['results'][] = time();
}

function batch_example_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('All done');
  }
  else {
    drupal_set_message('Error');
  }
}

Currently the $operations array is being created and is being passed to batch_set() then nothing else is happening.

Based from the first sample code found in Drupal's Batch API page, it says,

  If this function was called from a form submit handler, stop here,
  FAPI will handle calling batch_process(). If not called from a submit
  handler, add the following, noting the url the user should be sent to
  once the batch is finished.

And that we need to add the batch_process('node/1'); (still based from the sample code). So you just need to add this line of code with the Drupal path where you want the user to be redirected after the batch process after the batch_set() line.

The die() line also isn't needed anymore based on the sample code. I have also tested your code on my local D7 site with the batch_process() addition.

Unrelated Update

In your for loop declaration for ($i = 0; $i < $max; $i = $i + $increment), I noticed that the afterthought section doesn't increment the loop because the variables $i and $increment has no incremental operation.


Smart IP Not showing Country of the user I want to get the (lat $ Long) and country name of the visit users. For this I am using the Smart IP module but it will not show the full detail of the users.

Please help me out for this. How I get the whole data of the user?

PS: I need this info in the Drupal views for creating the conceptual filters.

To address your edit about the Views filter requirement, there's a submodule included with the main module, called "Smart IP Views Bridge". It has the functionality you're looking for. An extract from its README:

Smart IP Views Bridge exposes Smart IP visitor's location details to
Views field (coordinates, country, ISO 3166 2-character country code,
region, region code (FIPS), city and zip) and filter (country, ISO 3166
2-character country code, region, region code (FIPS), city and zip).

Enable that module and the filters you need will become available in Views.
The README goes on to provide full installation and configuration instructions for Views integration, so it's worth reading it thoroughly.
If solving programatically becomes a requirement:

It's right in the module description:
Other modules can use the function smart_ip_get_location($ip_address) in Drupal 6 and 7 and \Drupal\smart_ip\SmartIp::query($ipAddress) in Drupal 8 that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code.


Migrating nodes with image- and textfield to file-entity with image and description What is the approach to convert existing nodes consisting of a multivalue field-collection-field (containing an image-field and a textarea-field as caption) to the file-entity which the media module uses?

Load an array of nodes, loop over the array and in this loop loop over the field collection items. For each item create a file-entity.

Something like this:

$nids = db_query("SELECT nid FROM node WHERE some condition is true")->fetchCol();
$nodes = node_load_multiple($nids);

foreach($nodes as $node) {

  foreach($node->field_collection_field[LANGUAGE_NONE] as $item) {
    $collection = field_collection_item_load($item);

    $values = array(
      'field keys' => 'field values',
      'field keys' => 'field values',
    );

    entity_create('file', $values);

  }

}

Note that is half PHP half pseudo code - copying and pasting it won't work but will guide you on the code structure and functions that you'll need.


How do I add attributes to an entity reference field? Let's say we have a RECIPE content type that has a multi-value entity reference field to a FOOD content type, so as to represent the ingredients.

Each ingredient on a recipe needs to hold a quantity (eg: '1 cup') in addition to the reference itself.  How can we add that attribute?

We'd like to avoid having an additional entity to hold the relationship for performance reasons.  Also, sticking to core's entity reference field seems a good idea so the rest of the ecosystem can recognize the relationship.

The best and standard way to do this is with paragraphs.

Enable the paragraphs module, then add a paragraph type called ingredient with the two fields, an entity reference field and a field for the quantity.

if you want an ingredient to be reusable, keep in mind that paragraphs are not reusable.  If you want to reuse an ingredient, say "1 cup flour", then you could use an entity reference field to another reusable entity type, such as media or taxonomy, or another node type.


List content of node in another view I have a view of some custom content type and want to link the name of each object in the view to another view containing its details. At the moment, I have the "link this field to its node" box checked but it doesn't display it in some sort of table, just a list like Title: value.

Could you please tell me how I can achieve this?

You can alter the node link to anything you would like with "Rewrite the output of this field", it should link to something like /yourviewpath/$nid, where $nid is the node id and the argument for the view that contains the node details.


How to create heirarchical taxonomy menu/list using VIEWS How can I create a view of taxonomy terms for a content type (Story and Page) and display it to a block with parent and child relationship?

What I want is to take a "Taxonomy Term" based on "Content Types".

Example:

Fruits (5)
  - Apple (3)
  - Banana (2)
Vegetables (4)
  - Beans (1)
  - Eggplant (2)
  - Onions (1)

Demo:
http://worldstogethertravel.com

Menu on right sidebar: (Of Cultural Interest)

This menu is created using taxonomy_menu module not VIEWS.

You can try using Views Tree module..

Project page says

  Views Tree module provides a tree-based style plugin for Views. It is
  equivalent to the tree-based style template from Views 1.

  It is based off of the list style. Although it generates a nested
  view, there is still only a single query run for the view making it
  quite performant.

For node count, you can implement same using views.. Check this post Views and node count for taxonomy terms..


How do I refresh a view (or a page) after a new comment has been posted? I have a view that displays comments for a node.
When user1 posts a new comment then that comment appears automatically in the view for user1. But for user2 viewing the same node, the new comment does not appear automatically without a page refresh (ie, the view does not get refreshed automatically).

I have tried to find an event in rules to trigger an event that could look like "refresh page" or "refresh view".

Any hint?

Try using Views Auto-Refresh module.

  A module to refresh a view after a specified time interval. Includes
  advanced options to avoid reloading the whole view, and to avoid
  causing a full Drupal bootstrap at each refresh.

If you are looking for REAL realtime update you should use some server side javascript like nodejs, to push event to the dom.

also there is nodejs module for Drupal.

A great tutorial


How do I show a list of users and display only partial email addresses? I have created a list of users with views and I can add the user email field. However, I don't want to show the full email address. Instead, I would like to show the first few letters followed by ****@domain.com. (e.g. patr***@gmail.com or kell******@yahoo.com)

The purpose is to help users remember what email address they used when creating an account without revealing the full address.

My solution for this is to go with adding a Views handler to the email field. The idea is to add a checkbox maybe saying "Mask part of the email address".

So you need to:

Check the Views field handlers page for reference.
You will see that there is a field handler for the user email which is called views_handler_field_user_mail. So this is what we need to add some settings and logic to "mask" parts of the email address.

That would be it. All you need to study now is how to structure and create the handlers and you can search for the guide you understand most but this(Drupal 7 Views 3 custom field handler) contains a good sample code too.

Of course the logic of masking the string/email will be all you already depending on your preferences or requirements.


Will a patched up Zopim Chat work? I want to use Zopim chat for Drupal 8, but there is no version for it. However, I see something is done about it on https://www.drupal.org/node/2624230.

Does it mean I can use it safely on Drupal 8? Is it OK to use patched up Drupal 7 third-party modules on Drupal 8?

Does it mean I can use it safely on Drupal 8?

This is subject to the code written to port the module, and might be prone to some issues. The best way to find that out is by testing the patch and reporting back (on the same drupal.org thread) if you find it to be working or if you come across any issues.

  Is it ok to use patched up Drupal 7 contrib modules on Drupal 8?

Again, IMHO the best way is to work with collaboration here:

If you are a developer, help contribute the code.
If you are a tester, help with testing the solutions; and contributing to tests.
If you are good a documentation, write about the solution.
Many more ways to contribute... Check the "contributed projects" section from https://www.drupal.org/8/ready for good resources.

As per your main question:

  Will Zopim Chat work with Drupal 8?

It surely will, if those who require it help make it work!


Multiple forms/pages in one hook_menu() Within hook_menu(), I added multiple (form/page)s.

function mymodule_hook(){
  $form[...]=aray(...);
  // ...
  return $form;
}

function other_hook_form(){
  $form[...] = aray(...);
  // ...
 return $form;
}

function mymodule_menu() {
  $items['section/form1'] = array(
    'title' => 'form1',
    'page callback' => 'mymodule_form',
     'access arguments' => array('arg1 arg2'),
     'type' => MENU_CALLBACK, );

  $items['section/form2'] = array(
    'title' => 'form2',
    'page callback' => 'other_hook_form',
     'access arguments' => array('arg1 arg2'),
     'type' => MENU_CALLBACK, );

  return $items;
}

With the first Item I don't have a problem because it calls mymodule_hook(), but the second one renders the markup without <form> tag. So no submit/validation hooks are fired.

You should use drupal_get_form as your page callback and pass the id of your form to that. This will ensure the form is processed by Drupal.

For reference, take a look at how the aggregator module declares its form callbacks in aggregator_menu().

Example:

$items['myurl'] = array(
  'title' => 'Page title',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_form_id'),
  'access arguments' => array('my_permission'),
);


drupal_add_js cannot find my javascript file I am trying to add a simple footer.js to my page.  I created a new block and put it in the footer.  I then use PHP snippet in the body of the block with the PHP code:

<?php
drupal_add_js('footer.js');
?>

When viewing the source code, footer.js is there but when I click on it, it is a 404 error (not found).  The footer.js is located under: /var/www/drupal/sites/www.example.com/footer.js. Then I tried:

<?php
drupal_add_js('footer.js', array('type' => 'file', 'scope' => 'footer'));
?>

I don't think that is working, either.  I think the issue is with the path.  Any ideas, or do I have to write a custom module?

It is most likely a path issue, you should be able to use the DRUPAL_ROOT constant to get the correct one:

$path = DRUPAL_ROOT . '/sites/www.example.com/footer.js';
drupal_add_js($path);


Is it safe to protect the images only with a watermark image style? I'm building a website for selling stock photography and I'm looking for a way to protect the images. Here's what I'm using right now:

Imagecache Actions to watermark photos
Private file system for uploading all images
The images are displayed on the front only through image styles with watermarking.

Question: is this enough and are there any ways users could bypass this (e.g. by directly trying to access certain image style)?

Thanks!

This is probably not as secure as you would like it to be.
Basically if a user has access to view the image they can view any derivative image (image style), so long as they can work out the url to that derivative.

There is a module image style access that allows you to set up access rules per image style.

That should give you the extra protection you need.


Restrict content access by user language I'm building a large multilingual Drupal intranet, but have some trouble configuring the language settings.

There are about 6 different languages and a lot of sensitive content for each language. There are about 20 different roles (for each country), where each role can have access to 1 or more languages. E.g. All regular users in Germany should only be able to access German content, however a German manager should be able to switch between the German and English content.

Right now I'm struggling just to get a regular German user to only see German content, and a regular English user to only see English content. How would that be done?

If I select "Language negotiation: none" all users see the English content and no language-dependent stuff works. If I select "Language negotiation: by prefix only" all users are able to switch between all different languages by simply typing the prefix in the url.

Is it possible to accomplish what I'm looking for without writing my own access module?

I managed to solve this over the weekend, thought I'd share my solution if someone has the same problem.

TL;DR.

In my setup I use the contrib module Content Access. Basic configuration; In the System user preferences I deny access content to anonymous users, and in the Access Control settings for each content-type (admin/content/node-type/[type]/access) I disable View access for authenticated user. This way Content Access module will control exactly which role or which user can view/update/delete any content, even down on an individual node level.

I then wrote my own module that implemented the ACL api. It was a bit tricky to learn the node access system, and even more so with the complete lack of ACL module documentation/tutorials, but when I figured it out the module works really well.

The module utilizes Translation Access (i18n_access module) for deciding the user language access permissions. Translation Access provides access control for Edit/Delete, but not for Viewing content. If that would have been the case, this module would not have been necessary...

So first I added a custom submit handler to the default permissions rebuild form

/**
 * Rebuild all permission when using the standard form
 */
function mymodule_form_node_configure_rebuild_confirm_alter(&$form, &$form_state) {
    array_unshift($form['#submit'], 'mymodule_rebuild_permissions_submit_handler');
}

/**
 * Route submit function through custom handler to get rid of unwanted $form arguments
 */
function mymodule_rebuild_permissions_submit_handler() {
    mymodule_rebuild_permissions();
    drupal_set_message(t('Language permissions have been rebuilt.'));
}

Now this is where the fun begins, I created a "rebuild permissions" function that iterates all nodes restricted by language (in my case, all nodes). If a uid is provided, permissions will be rebuilt for that user only.

/**
 * Rebuilds permissions for all nodes and users, or only for a specified user
 */
function mymodule_rebuild_permissions($uid = null) {
    //Select the nodes to apply language restriction on
    $nodes = db_query("SELECT nid, language FROM {node}");
    while($node = db_fetch_object($nodes)) {
        $acl_id = mymodule_get_node_acl($node);
        if(!$uid) {
            mymodule_update_user_access_all($acl_id, $node);
        } else {
            mymodule_update_user_access($acl_id, $node, $uid);
        }
    }
}

As seen above we need a function to retrieve/create the ACL id of the node

/**
 * Gets the node ACL id
 */
function mymodule_get_node_acl($node) {
    $module = 'mymodule';
    $acl_name = $module.'_'.$node->nid;
    //Get the ACL for this node
    $acl_id = acl_get_id_by_name($module, $acl_name);
    //If it doesn't exist, create new ACL
    if(!$acl_id){
        $acl_id = acl_create_new_acl($module, $acl_name);
        // View = 1, Update = 0, Delete = 0, Priority = 0
        acl_node_add_acl($node->nid, $acl_id, 1, 0, 0, 0);
    }
    return $acl_id;
}

As well as for updating user permissions

/**
 * Update language permissions for all users
 */
function mymodule_update_user_access_all($acl_id, $node) {
    $users = db_query("SELECT uid FROM {users} WHERE uid > 1");
    while($user = db_fetch_object($users)) {
        mymodule_update_user_access($acl_id, $node, $user->uid);
    }
}

/**
 * Updates language permissions for a specific user
 */
function mymodule_update_user_access($acl_id, $node, $uid) {
    //Remove from list
    acl_remove_user($acl_id, $uid);
    //Add again if user has permissions
    if(mymodule_node_access($node, $uid)) {
        acl_add_user($acl_id, $uid);
    }
}

Check if the user has role and language access

function mymodule_node_access($node, $uid) {
    //Get the user roles
    $user_roles = user_load($uid)->roles;
    //Get the content access roles
    $node_roles = content_access_get_per_node_settings($node);

    //Check if user has permission to view node
    $node_access = false;
    if(isset($node_roles['view'])) {
        foreach($node_roles['view'] as $role) {
            if(isset($user_roles[$role])) {
                $node_access = true;
            }
        }
    }
    //Check i18n selected languages
    $perm = db_result(db_query("SELECT perm FROM {i18n_access} WHERE uid = %d", $uid));
    $user_languages = $perm ? explode(', ', $perm) : array();
    $lang_access = in_array($node->language, $user_languages) || $node->language == '';
    //Return true if we have both node and language access
    return $node_access && $lang_access;
}

Obviously we have to update access control when inserting/updating nodes and users

/**
 * Implementation of hook_nodeapi()
 */
function mymodule_nodeapi(&$node, $op) {

    if($op == 'insert' || $op == 'update') {
        $acl_id = mymodule_get_node_acl($node);
        mymodule_update_user_access_all($acl_id, $node);
        if($op == 'insert') {
            node_access_rebuild();
        }
    }
}

/**
 * Implementation of hook_user()
 */
function mymodule_user($op, &$edit, &$account) {
    if($op == 'after_update') {
        mymodule_rebuild_permissions($account->uid);
    }
}

Finally these functions had to be included to make the ACL api work

/**
 * Implementation of ACL hook hook_enabled()
 */
function mymodule_enabled() {
    return !mymodule_disabling();
}

/**
 * Implementation of hook_disable().
 */
function mymodule_disable() {
    mymodule_disabling(TRUE);
}

/**
 * Remembers if we have disabled access.
 */
function mymodule_disabling($set = NULL) {
    static $disabling = FALSE;

    if (isset($set)) {
        $disabling = $set;
    }
    return $disabling;
}

...and that's it!

Don't forget to rebuild permissions before anything (/admin/content/node-settings)


Drupal 7, displaying an image to search results I have a content type called "people". When a search is made and one of the search results is of "people" type, I want to display two fields of the "people" type; an image called "photo", and a text filed called "email".

Under "Manage Display" of the "people" content type, I selected custom display types and selected "Search Result" box. After saving, I selected the new "Search result" button and hid all other fields except "photo" and "email". I then customized the photo to have image style of "thumbnail".

I saved, cleared the cache, and reindexed the site. The search results are correct but no images are shown. I am very new to Drupal; all the help I could find is for Drupal 6 and by reading the comments people say that the solutions shown do not work for Drupal 7.

This is a core issue. See http://drupal.org/node/1166114.

Workaround is to add this to your theme's template.php. Also copy search-result.tpl.php from the core search module into your theme folder and clear cache.

function YOURTHEME_preprocess_search_result(&$variables) {
  $result = $variables['result'];
  if (isset($result['node'])) {
    $variables['snippet'] = $result['node']->rendered;
  }
}

The rendered node will pick up the Manage Display settings.


How to use Computed_field as a product of an existing one? I would like to have a field (field_result) that would display a number that is the result of the product of an existing field (field_1) on the same content type (let's call it book) and a fixed number (let's say 3.5).

My idea was to use the Computed Field module in order to display the result. After reading its Community documentation I managed to do the following:

That's what I achieved so far:

I configured field_result to accept only one value and save it on the database.
I set its value as follows:

$field_1 = field_get_items($entity_type, $entity, 'field_1');
$entity_field[0]['value'] = $field_1[0]['value'] * 3.5;
I set its $display_output as follows: $display_output = $entity_field[0]['value']

Unfortunately when I edit the node and save it I get the following notice:

  Notice: Undefined index: value in eval()

and the field displays 0.00 as a result.

What am I doing wrong?

A NOT commonly known/used solution that might help to prevent your problem from happening, is to use the (fairly new) Math Field module (for D7), instead of the Computed Field module (so change your mind about which module to use). Some more details about this module (from its project page):

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

Known issues

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

The cTools math expression library causes an error when using function that take more than one parameter. This effects pow(), min(), max() (#1958538: Improve math expression engine).
Math Field does not yet support multivalue options fields (checkboxes, or multiselect) (#2483453: Add aggregate functions for multivalue fields).
Math Field does not yet support Field Collections (#2573643: Support the Field Collection module).

Bonus: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...


Custom Drupal Analytics with Views- how to track the number of users by role over time? I am building a social networking website in Drupal.  As users complete their profile, they are awarded different roles.  Now that I have launched the site and have some members, I would like to track the number of users by role over time so that I can see how my site is growing.

I built a view to do this and it shows me the information I want.  However, since I want to measure membership growth I would like to do this over time.  So, currently I simply log into my site and then type the numbers I need into Excel.

Is there a better way to do this?  Ideally, I would like to automatically save an Excel-ready snapshot every week (or in a dream world, have a graph automatically prepared).  Is there some other way (even without views) to track the number of users by role over time?

You should record custom variables in Google Analytics. Download the GA Module https://www.drupal.org/project/google_analytics and Tokens
https://www.drupal.org/project/token
in the bottom of the configuration [yoursite].com/admin/config/system/googleanalytics
expand the SHOWCUSTOM DIMENSIONS section
populate the values with tokens like [current-user:roles]
You can also record an event upon account creation which identifies the type of account
https://developers.google.com/analytics/devguides/collection/analyticsjs/events
you can do a JS event on submit that will record or it probably makes more sense to create a library to record all instances of certain types the way Google Developers is implying.


Issue with module's hook_uninstall (not uninstalling db entries) I have a custom Drupal 6 module (based on this issue) that puts some custom date and time formats into the date_format_types table and then can be accessed from /admin/settings/date-time/formats.  This works nicely but I'd like to remove these from that table if the module gets uninstalled.

In my module's .install file, I tried this code:

<?php

/**
 * Implementation of hook_uninstall().
 */
function eventdates_custom_uninstall() {
  db_query("DELETE FROM {date_format_types} WHERE type LIKE 'eventdates_custom_date_%'");
}

This does not seem to work and the entries that had been added do not get removed from the date_format_types table when I uninstall the module but I am pretty sure I have the query correct.

% is used as the placeholder marker for D6 queries, so you need to escape it with another %:

db_query("DELETE FROM {date_format_types} WHERE type LIKE 'eventdates_custom_date_%%'");

As a test I just added the following to the date_format_types table:

And then ran this query from the devel/php page:

db_query("DELETE FROM {date_format_types} WHERE type LIKE 'eventdates_custom_date_%%'");

And both rows were deleted:


Jump menu and conditional links I am looking for a way to add some logic to a view's (styled as Jump Menu) selection options. The View's UI allows me to "output this field as a link" but I need to do something like this:

if (current_url == 'something') {
  link_here();
}
else {
  link_there();
}

Basically all I want to do is to figure out where to theme (a template or other files) the following part:

<option value="6ee3dbb066bb38cb7fb90872a6f0144e::/Cakes/AllCakes/[tid]">Chocolate</option>

In the Views UI, when you edit the View, open up the "Advanced" options. The penultimate option (one up from the bottom) is "Theme: Information." Here's an example:

If you click on "Information" you'll be given a list of template suggestions like this one:

And if you then click on one of the output types (i.e. "Display output," "Style output," etc), you'll be shown the boilerplate code for a template that should be named with one of the names to the right of the style type, which you can cut and paste into a file you save with the appropriate name. Like so:

Once you've got the template name to use, and some code to go in it, create your template in your theme directory and modify to rewrite the links as you require. I happened to choose the "Display output" template as my example, but you'll most likely want to use the "Field Content" template/associated template name.

Note that this is an information-only option in Views - it won't create the template for you. You'll have to do that yourself. You can cut'n'paste from the boilerplate to get started.

I hope that helps...


Showing different page layouts based on form data I'm trying to build a multi step form. Before the second step I have to process the data inserted in step one and render different layout and form fields based on the results.

I use "drupal_get_form" callback in _menu hooks to display the form, but I think I have to use a different approach, because I can't find a way to specify a template and\or HTML code this way.

What can I do? Thanks!

MENU DECLARATION:

/**
 * Implementation of hook_menu().
 */
function clientform_menu() {
    $items['clientform/step1'] = array(
        'title' => "Estimate",
        'type' => MENU_CALLBACK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('clientform_step1'));

    return $items;
}

function clientform_step1($form, &$form_state){
    if(isset($form_state['values'])) {
        $currstep = $form_state['step'] + 1;
    }else {
        $currstep = 0;
    }

    $form_state['step'] = $currstep;
    $allsteps = getForm();
    $currform =  $allsteps[$currstep];

    return $currform;
}

function clientform_step1_submit($form, &$form_state){
    $form_state['storedvalues'][$form_state['step']] = $form_state['values'];
    if($form_state['step'] + 1 != getNumberOfSteps()) {
        $form_state['rebuild'] = TRUE;
    }else {

        //Reached end of multipage form

    }
}

You can set a "theme callback" in a menu declaration, but that would only work if you had some way to distinguish which page/step the user is on.

The only other way I can think of would be to have some if/then statements in your form that check for what step the user is on, and alter the form how you need.


How to add custom predefined content panes? I've seen in a few tutorials and videos online that the following Content Panes are available:

Those that say Add links, add file, etc. For example this video also shows one called 'add page banner'. However, I don't fine how to install those content panes!

I've installed the Panels module, In-Place Editor, CTools and Custom Content Panes among others, but those are not available. How can install them? (using Drupal 7) Thanks.

You need to a Drupal distribution called Panolopy. You may also want to review this page.


How to use "taxonomy_get_childern" function //TID of current loaded node

<?php
$nid = arg(1);
$tid1 = db_query("SELECT data.name,data.tid FROM field_data_field_books book
 INNER JOIN taxonomy_term_data data ON data.tid = book.field_books_tid
 WHERE book.entity_id = $nid ");

 foreach($tid1 as $t){
    print "Name ==> " . $t->name;
    print "Tid ===> " . $t->tid;
 }

 //function to load child term
 $child = taxonomy_get_children(32);
 foreach($child as $ch){
   print "Name===>" . $ch->name;

?>

my question is that I want load tid dynamically instead of hardcore value
I am using the above code in block please tell me how I am handle this situation?

In Drupal 7 you can use this code

  $nid = arg(1);//get the arugument
  if (arg(0) == 'node'  && is_numeric($nid)) {//check for node page
    $query = db_select('field_data_field_books', 'book');
    $query->fields('data', array('tid'));
    $query->innerJoin('taxonomy_term_data', 'data', 'data.tid = book.field_books_tid');
    $query->condition('book.entity_id', $nid, '=');
    $tid = $query->execute()->fetchField();//only one field
    $child = taxonomy_get_children($tid);//get your children
    foreach ($child as $ch) {
      print "Name===>" . $ch->name;
    }
  }


How to fix warning message related to Pantheon module? When I am running update.php, I am getting warning message. I am sure this is showing because the module was deleted without uninstalling. I am unable to find the Pantheon module or the module for which this warning is related.

  User warning: The following module is missing from the file system: pantheon.   For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1143 of /homepages/46/d644118784/htdocs/includes/bootstrap.inc).

Try using module_missing_message_fixer

with drush

you just need to run the following 2 commands

drush en module_missing_message_fixer
drush mmmff pantheon

without drush using the user interface

Enable the module
make sure you have the permission Administer Module Missing Message Fixer
Go to: admin/config/system/module-missing-message-fixer


How to create submenu based on content type and taxonomy? I would like to create a submenu that lists items based on content type and taxonomy.  Here's the setup.

Shop for a Car [Basic Page]
    Financing Options for cars [Basic Page]
       loan 1 [Content Type: Loan / Taxonomy: Car, Home]
       loan 2 [Content Type: Loan / Taxonomy: Car]
       loan 3 [Content Type: Loan / Taxonomy: Car, Home]
Shop for a Home [Basic Page]
    Financing Options for homes [Basic Page]
       loan 1 [Content Type: Loan / Taxonomy Car, Home]
       loan 3 [Content Type: Loan / Taxonomy Car, Home]

Notice that loan 1 and loan 3 appear under two different parents.  I know I can create this menu structure manually using NodeSymlinks. In that case the Taxonomy terms are not needed.  However, I would like to generate the menu automatically using the terms for a particular content type.  I looked into the taxonomy menu module but it only allows one parent and it lists the taxonomy tag rather than the items tagged.  Any suggestions?

Thanks!

You could use views to create your links for the content types and then use the views field view module http://drupal.org/project/views_field_view as a field on that to show the child taxonomy terms associated to the content type.


How to remove chosen comma between taxonomy How can I remove comma from theese ingrediens and let them float left? I am using chosen for my taxonomyes

You need to go to the content type's display settings and change the display format.

/admin/structure/types/manage/article/display

is an example url you might go to to edit the article content type display settings.


Field type "date" is not in the list of available field types I'm trying to create a new content type with a field that would contain a date. However, the drop-down list for field type doesn't have "date". What's wrong?

p.s. drupal 7.17

You need to install the date module:

http://drupal.org/project/date

Then enable the date module and that will give you the option to add a date field to your content type. Depending on your case you might want to check also the popup calendar module that is part of the date module to ease the date input.


How to load a second user log in form? I have used default user login block on top navigation. I need to load another log in form on some pages.

I am trying to load the form by

drupal_get_form('user-login')

I get the following error:

  Notice: Undefined index: user-login in drupal_retrieve_form() (line
  763 of /path/to/drupal/includes/form.inc). Warning:
  call_user_func_array() expects parameter 1 to be a valid callback,
  function 'user-login' not found or invalid function name in
  drupal_retrieve_form() (line 798 of
  /path/to/drupal/includes/form.inc).

Is it possible to load a second log in form? (Drupal 7)

The key point in the error message is:

  ...expects parameter 1 to be a valid callback, function 'user-login' not
  found

You need to use:

drupal_get_form('user_login');

Where user_login is the form builder function in this case.

e.g:

print render(drupal_get_form('user_login'));


Search for duplicate or similar node titles when creating content? Much in the same way that it is on this site (as you type your question, it shows similar questions) is there a module that will search for similar nodes as I type the node title in Drupal?

I know of the Unique Field module, however it only checks after the node has been submitted. I need some way of doing it as they type.

There is module Uniqueness , it does exactly what you want. It allows you to enable for any content type, and you can configure checking on node add or edit or both.

  Uniqueness module provides a way to avoid duplicate content on your
  site by informing a user about similar or related content during
  creation of a new post. A UI widget is added to the node/add form that
  does asynchronous searches on inputted fields (like the node title or
  vocabularies) and returns the titles of similar content.


Custom URL using Taxonomy and Custom User information (Real Name) Secondly, in the future I'm looking to organise Users by Taxonomy and having the url path relate to that:

/?q=taxonomy-tag-here/user-fullname-here (not username, would be a custom field on the registration form).

How hard would this be to do, are there any modules that can do this, or would I have to create one?

I'm new to Drupal, but I've worked with Wordpress and Joomla a lot in the past and I'm looking to move onto Drupal, so please, be patronising when you explain!

You will be able to do quite simply with two modules Pathauto and Token I guess. Token will propose you any field as token and you can use it into pathauto config to generate your urls.


Views images as label on a table I am trying to create a table in views. My main problem is that I want to have a image in the label

       "CONTENT"

so far I've managed to add a space to the field and a custom class to it, and I've added background image to that field. It works but is not the best implementation. Can you point me in the right direction or it can not be done?

Thank you and keep up the good work. (i'm new to drupal but I know php css html javascript, mainly I've made small sites with custom cms and I'm moving go drupal)

CSS is the right solution if you have a fixed set of icons you want to use. If you need full control over the images for each node, you can add an image field and use the rewrite results settings to insert the image before your field. In this case, you would hide the label altogether.


How to Edit Content in $content['main'] I am maintaining a Drupal 7 site that was developed by another developer and I'm trying to
 move the search field on the results page to appear under the H1.  Currently the site has a search field that appears at the very top (above the top navigation) > after the user submits a keyword in the search field, they are taken to the Results page which has a second search field that appears right above the H1.

I know that the second search field on the Results page is within the $content['main'], but I can't seem to locate how to move the search field to save my life!  The script in the template.tpl.php file that contains the $content['main'] is pasted below.  I've checked the MySQL database (field_revision, field_data, & node tables), Structure (Panels, Mini Panels, Views, Pages, & Blocks), and content types -- all to no avail.

<?php if (!empty($content['main'])): ?>
<?php print render($content['main']); ?>

<? // debugging  ?>

<?php print_r($node); ?>

<?php
print '
var_dump
';
var_dump($content);
print '
';
?>
<? // debugging  ?>

Output from debugging script that was pasted below the $content['main']

var_dump
array(5) { ["search"]=> string(798) "

" ["header"]=> string(0) "" ["main"]=> string(4492) "

I've looked into Where does Drupal store the content of a node's body? but haven't found the search field in any of the suggestion yet.

The header normally comes from the page, and the search field comes from the form.
In order to place the h1 under the search field I'm usually using the next steps:

Hide the title on the search results page using the theme_preprocess_page
Use the search-results.tpl.php to insert the title under the search field


How to hide a view from certain roles? I am trying to hide some views (and their menu links) from anonymous users and some other roles i have created, how this can be done ??
Thanks.

On the views you have page settings option

In that there is access option

You can change the access to role and
by changing the settings u can assign roles who has the permission to access the view.


How to add a cache context from an existing menu? I want to update my breadcrumb when the menu structure changes. This did not work:

$breadcrumb->addCacheContexts(['route']);

Whats the correct way?

Edit: some more context (pun actually intended):

  I have a breadcrumb which adds the menu structure of the current
  node's menu parents as links. Obviously, when the structure somehow
  changes, the breadcrumb has to get updated also.

Apparently it's:

$breadcrumb->addCacheContexts(['route.menu_active_trails:main']);

and

$breadcrumb->addCacheTags(['config:system.menu.main']);


Custom php in rules how to check users' geolocation lat lon field and return only users in certain area I have some custom php, sending privatemsgs to users who have some term_reference field terms that match node term_reference field terms. I need to add into this so that it only contacts users who are within a certain range of area based on their lat lon that they entered on sign up. I am sure this is a very common thing to do e.g. showing users nearby etc. If you can point me in the right direction, would be great.

How about using javascript? You could submit it with ajax and write it to the db.

Here is a good example of a javascript geolocation function to get long and altitude:

window.onload = function(){
    if(navigator.geolocation)
        navigator.geolocation.getCurrentPosition(handleGetCurrentPosition, onError);
}

function handleGetCurrentPosition(location){

    location.coords.latitude;
    location.coords.longitude;
}
function onError(){...}

More complete demo:
http://od-eon.com/labs/geolocation/

For the calculation of the distance with php:
http://www.dzone.com/snippets/distance-calculation-using-1


Equivalent of search_data() in Drupal 8 Is there any function equivalent to the (D7) search_data() in Drupal 8? I would like to get the search results as a renderable array or html for a given keyword programatically.

In D8, the SearchController.php provides the view which does the same, but I'm not sure how to call that from my module?

It uses

$plugin = $entity->getPlugin();
$plugin->setSearch();
$plugin->buildResults();

to get the result.

How do I create the SearchPageInterface entity which contain the getPlugin() method? Or is there a way to create an instance of the default search plugin directly?

My requirement is to show the search results in a custom page where the search results are wrapped by the custom page content. I've implemented this in D7 using search_data function. How can I achieve similar result in D8?

You don't create the search page entity, you load it. SearchPage::load($id). Either hardcode the id that you use on your site or make it configurable through configuration/settings/URL.


Access callback evaluated on every page I have a custom module with a menu entry that has a page callback and a access callback. However, every time I visit any page, the access callback is evaluated. Could somebody enlighten me?

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

  $items['foo'] = array(
    'page callback' => 'foo',
    'access callback' => 'foo_access_callback',
  );

  return $items;
}

function foo() {
  //...
}

function foo_access_callback() {
  error_log('This gets evaluated on every page.');
  return TRUE;
}

Something just dawned on me...if you have a menu on the page that links to the '/foo' page, Drupal will query the access callback to find out if the menu link can be shown.

Since you're not providing a type in your menu item, it will default to MENU_NORMAL_ITEM which will place it in the site's Navigation menu.

I would guess that's what's causing the function to be run at least once on every front end page, but not for the admin pages (where you probably won't have the same menus).

It's definitely what was causing the issue on the test installation I just set up for this.


Drupal 7: Display Latest Revision's Author on the Admin Content Overview page with Admin Views Module Does anyone know the methodology to display the author of the latest content revision, using the Admin Views module on the content overview page (e.g. /admin/content)?

It's easy enough to display the initial author, or the VID of the latest revision, but I'm not sure how to create the relationship to the author of that latest revision and then display it.

Thanks!

You need to add a relationship (Advanced > Relationships) for "Content Revision: User". Make a note of the name of the relationship.

Add a field for "User: Name" and then make sure the relationship matches that of the relationship you added.


Whats the best method for displaying different page layouts for a node based on taxonomy? I am building a product site which should use a slightly different page layout for different types of products, depending on what product category they are.

All products are of the same node type. They are categorized based on selected taxonomy terms. The reason I did this instead of creating a different node type for each product category is because some products may exist in multiple categories.

My understanding is that panels relies on the URL structure for determining context. I'm listing all products under ../products/[title] so I dont think that will work. The only way to know the product category is to check the value of a CCK field on that product.

It seems there are many ways to skin a cat in Drupal but I'm unable to figure out what method will allow me to do what Im trying to do.

Any advice/help would be appreciated.

In D6, if you are displaying a full node page, you can use the preprocess_page() hook to select a different page template based upon that CCK field.  For example,

function mythemeormodule_preprocess_page(&$vars) {

  $node=$vars['node'];

  switch ($node->field_i_am_interested_in[0]['value']) {
    case 'something':
    case 'anotherthing':
      $vars['template_file']='page-bytax-' . $node->field_i_am_interested_in[0]['value'];
      break;
  }

}

and then create page-bytax-something.tpl.php page-bytax-anotherthing.tpl.php etc with whatever page layout you want.

If though, you are really talking about how the node itself is laid out in the $content area of the page, you could do the same thing inside preprocess_node() and create node-bytax-FOO.tpl.php templates instead.

Also, depending on what kind of cck field you are looking at, you might need to change up the [0]['value'] part.

If D7, subtle changes apply :)


D7 - Losing images when moving site location; placeholders point to old absolute path rather than relative path My file directories have not changed, but every time I move from local host to production, or just change the filename of a test site online, I loose the images.

For example if I use the backup of prodcution server in local I am getting the path name like below:

  http://localhost/sites/all/sites/default/files/images/image_name.jpg

here the project name is missing. thats why I am not getting the images.

I have changed the base_url in local as

  http://localhost/project-name

But even that doesn't helps. (Cleared the cache after changing)

Merely this is a duplicate of this question

But I didn't get what I need on that question. Thats why I reposted again.

Any help will be thankful and grateful...

Have you tried using http://drupal.org/project/pathologic?

Which way are you using to migrate your database and files? I would also suggest that you clear the cache before exporting.


Hide language for anonymous users How do I hide a language from anonymous users while I'm working on the translation?

I want the language only to be displayed in the language switcher block and the links to be active, while you are logged in as an administrator, so that they can check the translation while they are working on it.

On our site, we're using the Language Dropdown module to display translation links.

When we want a language to be accessible to authenticated users only, so that they can translate the contents before showing them to site visitors, we hack the module this way, in lang_dropdown.module, line 192 :

  // @TODO TEMPORARY FIX TO DISABLE ITALIAN TO ANONYMOUS USERS
  global $user;
    if ($user->uid == 0) {
    unset($languages->links['it']);
  }
  // ENDTODO
  //
  // Now we iterate on $languages to build the needed options for the select element.
  foreach ($languages->links as $lang_code => $lang_options) {

Be aware that in this case, the italian contents are not really hidden for someone who would know their paths, but it's sufficient for us.


Using background images formatter for taxonomy in views I have an image field per taxonomy vocabulary that I want to set as background to each views-row. I have the view filtered by taxonomy term, and I have set the taxonomy_image field as background.

However, I don't know which CSS selector would be appropriate. The tokens available are c.date, c.page, c.user, random, site info, and users.

If you have not disabled Add default classes under Style Settings of image field then you can use views_field_FIELD_MACHINE_NAME class to play with css.

For example If you have a field with machine name field_book_category_icon then after adding this field to your view you can get a class views-field-field-book-category-icon on front end when ever you render that view on your page.


Anyone having a problem with Drush 7 and Drupal 8 alpha-11 On a Linux system I installed Drush with Composer and when I try to use it with Drupal 8 alpha-11 I get this error. I looked around but can't find anything about it.

$ drush st

PHP Fatal error:  Class 'Drupal\Core\Site\Settings' not found in /home/$USER/.composer/vendor/drush/drush/commands/core/drupal/environment.inc on line 278
Fatal error: Class 'Drupal\Core\Site\Settings' not found in /home/$USER/.composer/vendor/drush/drush/commands/core/drupal/environment.inc on line 278
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Class 'Drupal\Core\Site\Settings' not found in /home/$USER/.composer/vendor/drush/drush/commands/core/drupal/environment.inc, line 278

I found the same issue. Upgrading Drupal 8 to the latest change (8.x branch instead of the alpha11 version) Drush works properly.


Limited access to 'Edit' Commerce Order & limit line items to only 1 type With further to my earlier question regarding Services for Products, I have implemented as per the suggestions:

Following are the components:

Orders
Service Vendors - The individual or the Person who would provide service for an order request
Rating and Review - Fivestar rating and Editable text field added as fields for Commerce Order.

I am facing the following problems:

In order for user to rate and provide a review on the order I would have to expose the Order as editable for authenticated user which would let the user to edit all other order attributes. The fivestar rating module, allows rating the star without edit privilege but the review - (editable textfield) requires edit privileges on Order entity for the user. I have tried to use Field Permissions to limit edit access only to these 2 fields but with no success!
I am providing Voting and Review operations on Order because the Line items can be configured only in "Add to cart" form. Hence, I would have to limit a single order to contain only 1 line item type (which can contain multiple products / services of the same type). How can I achieve this?
As against the accepted answer here I am planning to create an order request when user needs it and then later update the price (also quantity in line item) after the service quotation actually takes place. Is there a way to edit the order to accommodate this functionality?

PS: I would need the rating module to be applied on Order (or Line item) because unlike regular E-Commerce this does not deal with product, it is service oriented. There is a possibility that different vendors can provide service for each order of same type, hence I will have to associate the rating and review system with either Order or Line Item and then pick up the average rating of a particular vendor who has serviced different orders in the past.

Also, if there are any better ways of achieving the same kindly let me know.

While it is possible for you to add those fields to the order, you should really create a new review content type and then use those for your reviews and then use an entity reference to connect the review content to the order. In the future, if you did want to allow line items to have reviews, you could then just add another entity reference field to the line items and you can reuse all of the UX you've built for the main review form for anywhere else.

Furthermore, by using a reference, you're not limiting yourself to a particular type of form. If you ever wanted to differentiate between certain types of services and provide different review criteria, you can much more easily do that with new content types + entity reference.

Brief overview of steps:

Create a new review content type with your fields and fivestar info.
Create an entity reference field on your Order. I believe you can use Entity connect to have it show a "create link" if no reference exists.
If that doesn't work, you can use Views to make it so that a user can only connect the entityreference field to orders that they own.


Pass node field value to page.html.twig I'm new to Drupal. I've just started a custom theme in Drupal 8 and created a new field under Content Type. This field value is a custom class for each page. From the documentation I should be able to display the field contents of "field_body_class" with the following, neither of which display.

{{content.field_body_class}}

{{page.content.field_body_class}}

I've checked to make sure the field was not hidden, which it was not.

You are probably a bit confused.

Variables are only available in specific templates. So the value of a field which is attached to an entity (like a content type) is only available in the template for that entity.

To make the body class field value available in a different template you need to

make a preprocess function for the template.
fetch the entity that has the field
expose it to the template.

For you it could look something like this.

function theme_name_preprocess_page(&$variables) {
   // Define {{ body_class }}  in the template.
  if (!empty($variables['node']) && !empty($variables['node']->field_body_class)) {
    $variables['body_class'] = $variables['node']->field_body_class->value;
  }
}


Custom filter for Profile2 data I have to develop a drupal site that allows authenticated users to create
personal profiles with data such as interests, personal details, educations, etc.

I created a profile2 type with all needed fields and organize the view of the
data with views3. I want to create a filter (search form) that allows other users and visitors to search the name (first- and last name in one "name" single textfield, an OR'ed query), the city, a proximity field as an addt. option if the zip code is entered (by probably using the location module) and also an additional field that searches thru various other profile fields in one single textfield (all fields OR'ed).

For that reason I thought it might be a good idea to create a views custom filter to build such search form and sql queries. I can not find any way using the regular filter criteria such the way I want it described above. For example, I do not get a single textfield for the OR'ed name query, etc.

The code skeleton I have up to now does not generate any filter entry in the criteria dialog at all. The filter modue is enabled in the modules section.
I have the strong feeling that the "hook_views_data()" is not defined the right way for "profile2 fields". I been looking at various filter examples, but found nothing profile2 data related.

Here is what I have up to now .. like said, just a skeleton I try to work out step by step.

xconsultantview.info

; $Id$
name = XConsultantView
description = Custom consultant filter
version = 7.x-1.x-dev
core = 7.x
dependencies[] = views
files[] = xconsultantview_handler_filter_profile.inc

xconsultantview.module

<?php

/**
 *
 */
function xconsultantview_views_api() {
    return array(
        'api' => 3,
        'path' => drupal_get_path('module', 'xconsultantview')
    );
}
?>

xconsultantview.views.inc

<?php

function xconsultantview_views_data() {
    $data = array();

    // consultant filter
    $data['node']['consultant_search_filter'] = array(
        'group' => t('Custom'),
        'title' => t('Eliteberater specific consultant filter'),
        'help' => t('Filter consultants on specific fields'),
        'filter' => array(
            'handler' => 'xconsultantview_handler_filter_view'
        ),
    );
?>

xconsultantview_handler_filter_view.inc

<?php
class xconsultantview_handler_filter_view extends views_handler_filter {

    function options_form(&$form, &$form_state) {
        parent::options_form($form, $form_state);
        // ...
    }

    function value_form(&$form, &$form_state) {
                // not quiet sure if this is needed here
        $form['xconsultantview']  = array(
            '#type' => 'textfield',
            '#title' => t('Term Name'),
            '#default_value' => NULL
        );

        return $form;
    }

    function expose_form(&$form, &$form_state) {
                // seems like here I should define my complete form
                // ...
    }

    function query() {
        $this->ensure_my_table();
                // ... sql query ...
    }

};
?>

As I already found out the hook_views_handlers() is no more needed in D7, because the include files are defined via the files[] in the module info file.

Can anybody shed some light on my question, if such custom filter in general is possible at all or if there are other more simpler solutions. My main problem of understanding lies in the hook_views_data() fct and the profile2 fields or if I have to define a subset of the profile2 fields, at least the ones that I need to filter.

Is there any example with an custom filter filtering profile2 fields in a view?

It is my first drupal project, so my in-depth knowledge at this time is quiet limited...

Thanks so much in advance for your help!

Use the Search API module with Views to accomplish this functionality. Here is an example.


How to install a third party library for Printable module using composer (D8)? I installed the "Printable" module but it doesn't work. When I try to configure the PDF for the Printable module it says:

"You are seeing no PDF generating tool because you have not installed any third party library using composer".

This depends on how you have installed your Drupal site. There is a long description on how to use composer on Drupal.org handbook section.

The short version is this:

If you have installed Drupal 8 as you did with Drupal 7 using composer_manager module (which is depricated now)
If you have installed Drupal 8 using composer, you can require Drupal modules using composer, which automatically will download dependcies (assuming module developers has done their job by adding this information in their module's composer.json file)


What is the template suggestion for node 'teaser' view mode? node--[type|nodeid].tpl.php targets to node's default view mode. However I want to override the template for teaser view mode.

What is the template suggestion (.tpl.php file) for 'teaser' view mode?

I don't think there is one by default but you can easily add one in your template.php file:

function MYTHEME_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__teaser';
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->nid . '__teaser';
  }
}

That will let you use a template file like: node--[type|nodeid]--teaser.tpl.php


UI issues with the "Registration" module I am working on my second Drupal 7 site and try integrating the "Registration" and "Registration Views" module (7.x-1.0-alpha5) the first time to create an event system where members can join events and see who else joined.

For this I've created a content type "Events" with the event-fields as well as a Registration Type for the events (with some additional registration fields on it). Then I added the registration as a field to "Events". So far so good - no problem here.

The issues I now have is with the User Interface:

a) The registration is rendered on top of the content as a tabbed-UI. I like to see just a link to register or maybe an embedded register-form. I also like to show the list of members who actually have registered for this event. ...maybe as a block on the sidebar or something like this. Can I change the way the registration module renders? Is there a way to create a block to render the registrants into?

b) In the event-nodes (only on the event-nodes - not on other node-types) I have the comments elements above the regular node content (in this case the event-field-contents) and below the registration-tabs. How do I control where the comments appear?

Any help or pointing whould be great!

Cheers, Marc

It sounds like a lot of the issue is you you'll have to go into the theme and edit how it displays from there. The comments in particular you'll have to do this, you can create a tpl.php file specifically for for "Events" content type. You can learn how to do that here:

http://drupal.org/node/17565


Mailchimp programatic subscription and updates of existing users I'm using Mailchimp module for user registration and at this page I found a function for registering users programatically:

mailchimp_subscribe (
    $list_id,
    $email,
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name, // fields in your mailchimp list
        'LNAME' => $last_name,
    ),
    false,
    false
)

In my mailchimp account I have defined new field of radio buttons type (field name 'type' with options 'client' and 'expert').

I have 2 questions:

How should be the 'type' column in mailchimp_subscribe() function specified?
How could be an existing user in mailchimp programatically updated?

The key in the array can be MERGEX (where Xth field number in MailChimp) or whatever custom tag name you've set in MailChimp (it shows up as *|TAGNAME|*" in MailChimp field settings) . The MailChimp dropdown user fields aren't like Drupal's (with select fields containing a key/value pair); all it needs is the literal display value of option.

mailchimp_subscribe() eventually calls MailchimpLists::addOrUpdateMember() in its dependent library. Thus, the logic of adding/updating is handled for you in the function.

To put that together in the above code snippet:

mailchimp_subscribe(
    $list_id,
    $email,  //Will add or update $email in $list_id based on subscriber status
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name, // fields in your mailchimp list
        'LNAME' => $last_name,
        // Assuming the 'type' field in MailChimp is your 3rd field
        'MERGE3' => 'client',
    ),
    false,
    false
);


Pass query string to Webform text field I have a webform (www.mysite.com/myform) ad I want to be able to pass a URL string to a text field in the webform when a user visits the page and submits it. For instance, the URL provided to "customer A" might be www.mysite.com/myform?customer_name=customera and the URL provided to "customer B" might be www.mysite.com/myform?customer_name=customerb. I would like for the value of the text field "Customer Name" to be auto-populated with "customera" or "customerb" depending on the URL used to access the webform page.

Is this possible? If so, how can I accomplish this?

Going a bit deeper... if this is possible, is it also possible to pass two strings via the URL so that two separate fields are auto-populated? For instance, www.mysite.com/myform?customername=customera?customer_type=lead would auto-populate "Customer Name" with "customera" and would auto-populate "Customer Type" with "lead".

Thanks!

You can set a default value for each field on your webform.  The default value you would use would be

For Webform v3 and under:

%get[customer_name]

For Webform v4+:

[current-page:query:customer_name]

To get a first and last name you could do something like:

URL:

http://mysite.com/myform?first_name=John&last_name=Doe

First Name Default Value:

%get[first_name]                 //webform <= v3
[current-page:query:first_name]  //webform >= v4

Last Name Default Value:

%get[last_name]                 //webform <= v3
[current-page:query:last_name]  //webform >= v4


Drupal 7 Commerce - What permissions do I need to set to give access to a specific role to view ANY order for administration? In drupal 7 commerce i setup a staff role to access and manage commerce orders, but they are getting an access denied even though i have all the Orders permissions checked off. Is there somewhere else I need to check off to enable permissions for a specific role?

This is how my permission look like --

As you can see, Site Admin & Shop Keeper can manage orders along with administrator(I have several kind of users). Site Admin & Shop Keeper doesn't have access to toolbar, so I have created a menu with name "Manage Order" & set it to the path "admin/commerce/orders"(I have several menu items of this kind).

Placed this menu in one region with permission set to be viewed only by these users type who are intended to use it. These users have permission to use admin theme, so they access it just like administer do by clicking on those menu item.


THEME_preprocess_page_xxx? I need to make changes to several admin pages, instead of conditionally tests for the page/node (ie: User, Appearance, Views admin pages right now) can I override each using more specific theme functions?

MYTHEME_preprocess_page_admin_user
MYTHEME_preprocess_page_admin_views
MYTHEME_preprocess_page_admin_appearance

Is this possible? It's the themeing function not the template TPL I need to execute as I am re-structuring some list items in each -- not really changing the markup per se.

Alex

Out of the box, Drupal won't do this.  You can do something like this, though:

function MYTHEME_preprocess_page(&$variables) {
  $parts = explode('/', request_path());
  $subhook = __FUNCTION__;

  foreach ($parts as $part) {
    $subhook .= '__' . $part;

    if (function_exists($subhook)) {
      $subhook($variables);
    }
  }
}

This is untested (it may need some tweaking), but it will build up function names based on the request_path().  So, the idea is that if the URL is http://example.com/foo/bar/bar, it will check for

MYTHEHE_preprocess_page__foo()
MYTHEHE_preprocess_page__foo__bar()
MYTHEHE_preprocess_page__foo__bar__baz()

and call each, in sucession, passing in the $variables.

As this will call functions based on user input, you will want to think about some logic to prevent malicious activity, such as only doing it for certain paths, etc.

Just note, that if you are doing this to the admin pages, then you need to do this in the admin theme you have defined for your site, and not the main theme.

I don't normally do this with the preprocess page hooks, but I use something similar for the node ones based on content type and view mode.


Field validation error on nodereference field during D6 to D7 migration I'm migrating a D6 site to D7.

There are several content types that have cck noderefenrce fields that use referenced views for content types that can be referenced.

When I run the migration, I get a field validation error:

  Field validation error for field: field name: this post can't be referenced.

In the CLI, I've used --user=1 to see if it was a permissions problem, but no luck.

Has anyone experienced this? Any hints or suggestions?

It doesn't look like there's support for migrating nodereference fields in D2D migrate. You'll need to write a custom migrate class. In general, I haven't had much luck with the D2D GUI; it's only useful for super-simple migrations.

Writing a custom migration class (especially if you're using migrate_d2d) is really quite easy to do and a worthy exercise. Take a look at the migrate_d2d_example code. The nice thing is that migrate keeps track of the mapping between the old NIDs and the new so that you need only write one line of code in your constructor to ensure the reference field has the right value.

See: Migrate D6 node reference to D7 entityreference


Using Blocks vs Template Edit I have a banner and some social media buttons added through a template edit. I was wondering if it would be better to put it in a block or leave it as is. My goal is better performance.

Technically putting things straight into a template may have better performance.

However if you create a static block and make sure it is cachable on the whole site the difference will be negligible. There are many other ways to improve performance and this is right a the bottom of the pile.

There are many other things that you can do to improve performance. Taking the view of the site as a whole. The flexibility that a block gives you may give you may outweigh the performance gains you achieve.


Sorting by "aggregation type: count" is not working I am trying to solve this problem: Drupal 7 Most Popular Tags in a list as a block: How? with Views 7.x-3.0-rc1.
The solution is the answer by Dylan Tack.

create a view of terms
add a required relationship to "content using tags"
set use aggregation: yes
add the "term name" field a second time, set one of the to "aggregation type: count"
add "term name" as a sort criteria, set "aggregation type: count"

A sample view is at http://drupalbin.com/19467

It works until I try to sort the list; in that case, I get an error when adding a sort criteria. If I set "aggregation type: count" the sort-criteria changes to "Broken/missing handler" and it is not sorting.
Do you have any idea? Am I doing something wrong?

This issue has been resolved in the development snapshot version 7.x-3.x-dev.


create multilingual node programmatically i'm trying to create a multilingual node using a php script.

I'm doing this:

 $node = new stdClass();
 $node->title = "Test ".mktime();
 $node->type = "job";
 $node->language = 'de'; // Or e.g. 'en' if locale is enabled
 $node->uid = $user->uid;
 $node->status = 1; //(1 or 0): published or not
 $node->promote = 0; //(1 or 0): promoted to front page
 $node->comment = 1; //2 = comments on, 1 = comments off
 $node->path = array('alias' => 'das-ist-ein-test-'.mktime());
 $node->body[$node->language][0]['value']   = "Body Body Body";
 $node->body[$node->language] = text_summary("Body Body Body");
 $node->body[$node->language]  = 'filtered_html';
 node_save($node);

As long as i set $node->language to 'und' everything is working fine.
But as soon as I set the language to 'de' or 'en' (both languages are activated in my Drupal installation) the body text doesn't get saved.

So my question is: can anybody provide me with a working example of how to store a multlingual node (de,en) into Drupal using program code.

Thank you

It depends on is your body field translatable or not. Please, look at this explanation about translatable fields: https://drupal.stackexchange.com/a/31639/2466

$node_lang = 'ru'; // I am a Russian girl

$node = new stdClass();
$node->title = "Test ".mktime();
$node->type = 'article'; // Your type
$node->language = $node_lang;
$node->uid = 1;
$node->status = 1;

// Get proper langcode
$body_field_info = field_info_field('body');
if (field_is_translatable('node', $body_field_info)) {
  $body_language = field_valid_language($node_lang);
} else {
  $body_language = LANGUAGE_NONE;
}

// Some lorem ipsum.
// You can add custom summary:
// $node->body[$body_language][0]['summary'] = 'Summary';
$node->body[$body_language][0]['value']   = 'Lorem monotonectally iterate resource-leveling innovation before timely core competencies. Globally coordinate sustainable strategic theme areas and intermandated infomediaries. Monotonectally brand customer directed solutions and high-quality bandwidth.';

node_save($node);

There is an issue for Drupal 8 to make Field Language API more usable.


Organic Groups user sectioning I have just set up a site working with Organic Groups. I am now adding users and user permissions.

I create a type called group which serves as the group node and page that serves as the group node content.

The issue is I want my authenticated users to add new page content but only within groups I have assigned them to.

Can anyone advice how I can do this?

when your users post new "page" content they can select the associated group. You could make that a required field.


hook_preprocess_html in my module I am having a content type with fields select list, js, css, and body. In the select box it list a number of templates to apply on the current node. I have these custom templates in the templates folder of the active theme, in the format my-module-blank.tpl.php, my-module-custom1.tpl.php

And on select list I have blank and custom1 as options. In the hook_preprocess_node, using theme_hook_suggestions I have did the same,

  $variables['theme_hook_suggestions'][] = 'my_module_' . $field_template_list;

But it is not taking the template, In addition I need to use hook_preprocess_html
to include the custom css and js added to fields of content type to the header portion. I didn't find any proper documentation on it.

Please show me a better documentation so that I could implement.

hook_preprocess_page() is called before hook_preprocess_html(). hook_preprocess_html() would probably be the last one that's run in a page build.

If you want your CSS and JavaScript when displaying a node, you can add the files it in the preprocess function for the node template.

function THEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $node =& $variables['node'];
    if ($node->type == 'something') {
      $path = drupal_get_path('theme', 'THEME');
      drupal_add_css($path . '/misc/jquery.fancybox-1.3.4.css');
      drupal_add_js($path . '/misc/jquery.mousewheel-3.0.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-1.3.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-calls.js', array('type' => 'file', 'scope' => 'header'));
    }
  }
}

You can add a custom template for any content type like:

node--[node-type].tpl.php

I would suggest you to use hook_preprocess_page at template.php for this:

function MYTHEME_preprocess_page(&$variables, $hook) {
    if (isset($variables['node'])) {
        if ($variables['node']->type == 'something') {
            $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
        }
    }
}

Note: Don't forget to clear your cache after this :)


Dynamic content-type creation I have this scenario in my application:

Every registered member, can manage up to 3 content-types. And manage nodes based on their own content-types. They can manage their own content-types and nodes.

edit: the number of registered members might reach more than 1000

How can I approach this?

opening administer content-types permission for authenticated-users is definitely not an option. Also there could be a lot of confusions regarding dynamic permission, custom roles, etc...

Is creating content-type of node-content-types possible?

Are there any contributed modules or distribution for this specific features?

Thanks

edit02: Some explanations, I hope it's clear..

user can manage his content-types by: creating new content type, edit/delete existing ones. he also can manage his nodes too.
also, different user, cannot see other's content-types, but can see other's published nodes
All content types (and it's fields) shouldn't be overlapped. maybe the user's name is included in the content-type machine name generator (and field's) to avoid duplicates
I'm not sure about the idea "creating content-type of node-content-type"

this could be done, but I think it's too broad for the Q&A approach of Drupal Answers. In general, if I was to try this, I would start with this:

add an integer field to the user (to track number of content types)
using Field Permissions, hide that field from anyone but admin

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

create a role with the appropriate permissions to add content types
if permission allows viewing the content type list, use Rules to check that url against role to ensure new 'content type moderators' cannot access the list and redirect with a message

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

override the hook_form_alter() to check the integer value of the hidden field on content type creation, redirect or show message if user is at limit
override the form submit() function to increment the integer value of the hidden field on content type creation, and create perhaps a custom block, menu entry or other element to allow the user access to edit the content type later on


How can I create a download link to a private file? I have a views page that is only accessible by a certain user role. This user role also has permission to "view private files" and to "document: download any files" (coming from File Entity Module). The views page displays a table of all private .pdf files that lie in the private file directory and I would like to add a column to this table, using a Views PHP field (at least for prototyping), that displays the corresponding download link next to the file name. As mentioned above, any user that can view the table also has permission to view private files and to download documents, so this should be doable and not be a security issue.

For now, let's assume I always want to display the download link to a fixed private .pdf file, say with file id $fid=17. According to Working with files in Drupal,

  once configured, files stored in the private directory are inaccessible via a direct link; however, if Drupal constructs a link to the file, the file will be accessible to anyone who can see the link.

What precisely is meant by "if Drupal constructs a link to the file"? I have read many times that file_create_url() will create a direct link that, if the user has access to view private files, will take the user to the private file. So I tried in my Views PHP field as output code

<?php
$fid = 17;
$file = file_load($fid);
$uri = $file->uri;
$url = file_create_url($uri);
print l(t('Link'), $url);
?>

and the link gets displayed as it should (with reference to mysite.com/system/files/Name_Of_Private_File_17.pdf). But even though the user has permission to view and download private document files, clicking on the link will result in an "Access denied. You are not authorized to access this page."

Can anyone tell me the correct workaround?

When I add the field 'File: Download link' to the view it works fine.

The views field handler for the 'File: Download link' has this snippet to check access:

if (!file_entity_access('download', $file)) {
   return;
}

and this snippet to construct the uri for the download link:

$uri = file_entity_download_uri($file);

The code for file_entity_download_uri():

function file_entity_download_uri($file) {
  $uri = array(
    'path' => "file/{$file->fid}/download",
    'options' => array(),
  );
  if (!variable_get('file_entity_allow_insecure_download', FALSE)) {
    $uri['options']['query']['token'] = file_entity_get_download_token($file);
  }
  return $uri;
}

show the download token being added to the options query key of $uri which is returned.

Adding that to the PHP code field:

<?php
    $fid = $row->fid;
    $file = file_load($fid);
    if (file_entity_access('download', $file)) {
        $uri = file_entity_download_uri($file);
        print l(t('Download'), $uri['path'], array('query' => $uri['options']['query']));
    }
?>

results in a download link to the private file.


Contrib statistics: Reported installs and downloads I've noticed that the number of reported installs is usually (not always) somewhat larger than the number of downloads. I figured maybe this is because of multi-site installations in which one download runs on several sites. On the other had, there have to be cases where a module is downloaded and not implemented in production, which perhaps would account for cases where there are more downloads than installs.

But I just noticed that "CKEditor Link" has over 50,000 reported installs and only 658 downloads. That doesn't make any sense. Does anyone know what's going on there?

These statistics are relevant to the decision of which modules and themes to use in a system. (Edit: They are relevant for me because I can't afford to be in a situation where my sites go down because a Drupal revision breaks a module and the module maintainers don't get it fixed pronto. This is much less likely to happen with an installed base of 50,000 than 500.)

This is simply due to a bug with the statistics module - see Project Download count Decreased - that has affected Drupal.org infrastructure since the middle of April 2015.

Prior to that bug surfacing, I did not observe a single project where the number of downloads were less than the number of installs.

Just now CKeditor Link is reported to have 487 downloads.  That is 171 less than the 658 reported by the OP in the question (asked two days ago).

Until this bug is fixed, the download statistics should just be regarded as a random number.

As reported by Pierre.Vriens, another bug sometimes affect the installed statistic on the Drupal.org.  This affected many projects a couple of days ago, but seems to have been fixed for most of them today.


How to join two Drupal CCK content types in view without a node reference field, fast? Users uploaded two csv files to create nodes for two CCK content types (Delivery Note and Payment), i.e.

 Delivery       Payment
----------     ---------
 Order No.      Order No.
 Recipient      Charge
 Address

I would like to create a view as a report for the boss:

 Order No.  Recipient  Charge
 ---------  ---------  -------
  ...        ...        $...
  ...        ...        $...
  ...        ...        $...

Order No. field is unique and both content types.

How's it possible to do it in Drupal's view?

The above question was asked on SO and I found a solution. However, the solution was way too slow (for example, it takes more than a hour to download ~2000 records via Views Data Export).

Since you don't have a reference between the two, Views has no way of knowing how the node's relate to eachother. Views has no direct support for joining on arbitrary columns.

So to solve this, you need to declare the relationship to Views your self. You do this by implementing hook_views_data, or in this case, since Views has likely already created most of the array, hook_views_data_alter. The documentation for the first function has an example with code for a relationship.


Alter Acquia Search Results I am using acquia search on D7 site. By default I get all the search results as Title, Teaser with search info at the bottom. I am trying to alter this results to add some of the field data.

Eg: Content type is a product and there is a Date of arrival field and Stock availability field for all the Product node.

Now how can I add these two fields as part of every result on search results page?

You can use hook_apachesolr_query_alter($query) to alter your results variable, if you're using Apache solr views and this error

Notice: Undefined property: apachesolr_views_query::$group_operator in apachesolr_views_query->build() (line 80 of /var/www/html/root/sites/all/modules/apachesolr_views/apachesolr_views_query.inc).

this means that you didn't use filters in your view.


Why Views Data relationship between custom entity type and node doesn't work? Fields names are equal in both tables.

Inside hook_views_data:

  $data['stream']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

 $data['stream']['nid'] = array(
    'title' => t('Related node'),
    'help' => t('Node related to stream item.'),
    // Define a relationship to the {node} table, so example_table views can
    // add a relationship to nodes. If you want to define a relationship the
    // other direction, use hook_views_data_alter(), or use the 'implicit' join
    // method described above.
    'relationship' => array(
      'base' => 'node', // The name of the table to join with.
      'base field' => 'nid', // The name of the field on the joined table.
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
    ),
  );

(similar to example from api page)

but there isn't above relation in Add relationships box. Could some one give me any hint?

I solved it by this way:

$data['stream']['table']['join'] = array(
  'node' => array(
    'left_field' => 'nid',
    'field' => 'nid',
    'handler' => 'views_join', // this is actually optional
    'left_table' => 'node'
  ),
);

$data['stream']['nid'] = array(
    'title' => t('Related node'),
    'help' => t('Node related to stream item.'),

    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),

    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
      'allow empty' => TRUE,
      'help' => 'Filter on a related node nid.',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric',
      'numeric' => TRUE,
      'validate type' => 'nid',
      'help' => 'Argument on related node nid.',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
      'help' => 'Sort on related node nid field.',
    ),
    'relationship' => array(
      'title' => t('Stream node'),
      'help' => t('Relation to node related to current stream item'),
      'label' => t('Stream node'),
      'base' => 'node',
      'base field' => 'nid',
    ),
  );


how can i change the "Create new Account" to Custom registration Is there any ways to add more fields in "Create new Account" ?

By defaults it provides only username and emailid.

So how can i add more fields like gender, date of birth.

Fields module should be enabled with Field UI and other.
http://YOURSITE/admin/config/people/accounts/fields - add field, mark "Display on user registration form." on field editing form.


RSS feed is downloading I just noticed today that my rss feed is not working properly. When I click it, it prompts me to download it.

My site is http://www.sourcecodester.com/

The rss feed url is: http://www.sourcecodester.com/feed

Can anybody tell me what's wrong?

I can see one empty line in beginning. This might be due to a empty line in any one of your modules. In PHP blank lines before <?php tag causes a lot of problems remove it and check again. have a look at other site XML (Source Code) for proper format.


Incorporating external jquery library I am trying to use with Javascript in Drupal 8. I took an example from official drupal website, which I got it from https://www.drupal.org/project/examples and modified the code of js_example to incorporate sDashboard library.

The js_example.libraries.yml includes:

# A simple script using jquery ui accordion.
js_example.accordion:
  js:
    js/js_example_accordion.js: {}
  # Build up our dependencies for this page as a library. Our accordion script
  # needs jquery.ui.accordion. You can find the core scripts under core/assets/.
  dependencies:
    - core/jquery.ui.accordion
    - core/jquery

js_example.sdashboard:
  js:
    js/jquery-sDashboard.js : {}
  css:
    component:
      css/sDashboard.css: {}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.datatables

The example module includes a Controller which I modified as:

public function getJsAccordionImplementation() {
    $title = t('Click sections to expand or collapse:');
    // Build using our theme. This gives us content, which is not a good
    // practice, but which allows us to demonstrate adding JavaScript here.
    $build['myelement'] = array(
      '#theme' => 'js_example_accordion',
      '#title' => $title,
    );
    // Add our script. It is tiny, but this demonstrates how to add it. We pass
    // our module name followed by the internal library name declared in
    // libraries yml file.
    $build['myelement']['#attached']['library'][] = 'js_example/js_example.accordion';
    $build['myelement']['#attached']['library'][] = 'js_example/js_example.sdashboard';
    // Return the renderable array.
    return $build;
  }

and there is an accordion.html.twig where I added the code for displaying the sdashboard widget. It is given as:

{{  title }}

  .... accordion here ...

Now when I am trying to run the example, I get the error:

ReferenceError: $ is not defined
$("#myDashboard").sDashboard({
accordion (line 299, col 3)
ReferenceError: Flotr is not defined
factory($, Flotr);

Isn't this the usual way of using any external library in drupal. How do I use other libraries that I may need like sDashboard, etc?

If you are trying to add a js library from an external cdn in drupal 8 then, in your theme/module mycustom.libraries.yml file add do like this:

NOTE: Make sure you indent each spaces with two spacebar press button and not a tab press.

NOTE: version is optional here. You may not need add in.

mycustom.flexslider:
  version: 2.6.3
  css:
    theme:
      //cdnjs.cloudflare.com/ajax/libs/flexslider/2.6.3/flexslider.css: {type: external}
  js:
    //cdnjs.cloudflare.com/ajax/libs/flexslider/2.6.3/flexslider.min.css: {type: external}
  dependencies:
    - core/jquery

If you are hosting it within your module or theme then:

NOTE: Here I placed flexslider within my theme or module vendor directory. So it would be inside mycustom/vendor/flexslider

mycustom.flexslider:
  version: 2.6.3
  css:
    theme:
      vendor/flexslider/flexslider.css: {}
  js:
    vendor/flexslider/jquery.flexslider-min.js: {}
  dependencies:
    - core/jquery

If you are just trying to host your custom js or css file then:

mycustom.myscript:
  js:
    js/script.js: {}

If its dependent on other library like core jquery or custom library then:

mycustom.myscript:
  js:
    js/script.js: {}
  dependencies:
   - core/jquery
   - mycustom.myscript2

Then like in example module If I had to add flexslider library:

public function getFlexSliderImplementation() {

    $build['myelement'] = array(
      '#theme' => 'js_flexslider',
    );
    // Add our script. It is tiny, but this demonstrates how to add it. We pass
    // our module name followed by the internal library name declared in
    // libraries yml file.
    $build['myelement']['#attached']['library'][] = 'mycustom/mycustom.flexslider';
    // Return the renderable array.
    return $build;
  }

Update:
Download and extract Flotr2 to your module or theme vendor directory. Modify libraries.yml file to include flotr2

js_example.flotr2:
 js:
   vendor/flotr2/flotr2.min.js : {}

js_example.sdashboard:
  css:
    component:
      vendor/sDashboard/sDashboard.css: {}
  js:
    vendor/sDashboard/jquery-sDashboard.js : {}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.datatables
    - js_example/js_example.flotr2


View block - show only field content from own page I am creating a view block to be displayed on every page of a specific content-type. Among other things, this view shows a field from that content type. How can I configure the view so that it will only display the field data from the page it is on? Right now it shows the data from every instance of that content-type field. Is there a way to reference the 'parent' page only?

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


Why book re-ordering is not being saved? I'm using Drupal 7.38. When I re-order book pages and then hit the Save button, the ordering stays the same. If I open individual nodes and change weight of each one then it works, but that will take a lot of time.

Any idea why the re-ordering is not being saved?

It's an old bug when you have too many pages, I've been struggling and finally still doing it through MySQL :

it's 'menu_links' table and Weight value in DB , and flush cache well

it's from my old question How to reorder Book module menu through Database?

Hello, who deleted My Answer?! - This IS ANSWER not Bug report, indeed! You can use my answer about MYSQL data tables! Why joke and delete?!


Set option value in a select field The array generated gets me the information that I need, but it's created a keyed array where the key is numeric (0..length-1).  How do I change it so that key is equal to the value, so that the option value is equal to what is displayed?

$page = $sql->execute();
$pages = array();

    // Populate page dropdown
    foreach($page as $p)
    {
      $pages[] = $p->title;
    }
// Display only unique values in the array
$paged = array_unique($pages);

// Sort the array in ASC Order
sort($paged);

$form['group_owner_filter']['select'] = array(
    '#type' => 'select',
    '#title' => t('Filter by Name'),
    '#default_value' => t('Make a selection...'),
    '#options' => $option
  );

This generates:

<select id="edit-pages" name="pages" class="form-select">
    <option value="0">About Davenport</option>
    <option value="1">Academic Support Center</option>
    <option value="2">Academics</option>
    <option value="3">Adjunct Insurance Scholar Opportunity</option>
    <option value="4">Admissions</option>

So here is the corrected code. I've changed some variable names to make it easier to understand.

$option and $pages became options
$page became $pages
$paged was retired

As @Sujith-Nara mentions you don't need array_unique as the keyed approach will make them unique by default. This does presume that the page titles are unique across the site (which is not enforced). You could replace the key with $p->nid or $p-name if the titles aren't unique.

Because the keys are now strings you can use ksort instead of sort to order them on the key.

$pages = $sql->execute();
$options = array();

// Populate page dropdown
foreach($pages as $p)
{
    $options[$p->title] = $p->title;
    // $options[$p->name] = $p->title;
    // $options[$p->nid] = $p->title;
}

// Sort the array alphabetically in ASC Order
ksort($paged);

$form['group_owner_filter']['select'] = array(
    '#type' => 'select',
    '#title' => t('Filter by Name'),
    '#default_value' => t('Make a selection...'),
    '#options' => $options
);