Feeds CSV import taxonomy and file I have an interesting use-case.

I have to import a lot of documents (+100) into a specific content type called "Resource".
This content type consists of few taxonomy fields (mapped to a vocabulary), some textfields and PDF file.

What should be the strategy when using Feeds module. Is it possible to have multiple taxonomy terms per field ?

For taxonomy terms :
It is possible, simply delimit your values with commas in your taxonomy field CSV column, and in the Feeds mapping, select "Search taxonomy terms by: Term name" and "Auto create"

Make sure your Drupal field allowed number of values is set to Unlimited (or > 1)

For files:

your file is external and given a URL, feeds will download it and store it
your file is already stored locally then the URI must be either

a stream wrapper (e.g.: public://import/myfile.pdf)
a relative path from your docroot
an absolute path on your system


Content type export broken in PHP 5.4 I am trying to upgrade my server from PHP 5.3 to 5.4. When accessing the Content Type export form in CCK with D6 the form does not display.

This issue is on first display of the form, not just on submit (as I have seen other questions online).

Here is the bad form.

Here is the correct form (on PHP 5.3).

I don't have any errors being thrown to the error_log or watchdog, and I am using Pressflow 6.26.

Line 623 of modules/cck/modules/content_copy/content_copy.module needs to be changed from:

function template_preprocess_content_copy_export_form($vars) {

to

function template_preprocess_content_copy_export_form(&$vars) {

https://drupal.org/node/2230081


how do I access raw URL from a File Field to render it in twig inside href? I have a "Our Staff" Content Type, that includes a field for uploading an individual's CV as a PDF:

field_cv_file

I have created a View for this Content Type, then added it to page via Blocks

The twig file I'm using to render/style this area is:

views-view-fields--our-staff-view--block-1.html

I'm having trouble with the URL for the File Field

I can render it as a PDF icon link like this:

{{ fields.field_cv_file.content }}

But I want to obtain the 'raw' URL to apply inside a href, something like this:

Download CV

This however is not working.

I've tried a few different ways of rewriting the code in href, but none are working.

how would I do this?

In my case as I was using a views twig, and required the field's file path to be usable inside a href, I had to write it like this:

Download CV


D7 - Rules System Page Redirect not working at all? I've been trying to add action Page Redirect to my rule (after a coupon code is applied to an order), and it doesn't work in any scenario? I did a bit of digging and it seems this is common - anyone know why it's happening/what the fix is?

First things first: a page redirect from "current page" to "current page" is what seems to be your very last Rules Action, is that what you actually want? If that's not your issue, then read on about a possible approach to find out what else might be wrong.

Basic debugging

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

Also, since you have 2 Rules Conditions in a single rule (both must be satisfied for your Rules Actions to execute), you should try to see what happens (if you get a "bingo") for each of the individual Rules Conditions. This by simply (temporary) removing 1 out of the 2 Rules Conditions you are using, and verify if they each result in the Rules Action you'd expect (also just a simple Bingo-message should be sufficient).

Advanced debugging

Something else that will help you find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your node:comments).

For way more details about these 2 variations, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


Why jquery menu collapse on all pages except front page I have a Drupal 8 site and them (upgraded from Drupal 7) and the main menu collapses to a button when the page is narrow enough (i.e. on a mobile device).  Or at least it is supposed to.  I did not design the theme.
SITUATION
Unfortunately when the menu is collapsed into a button, clicking on the button does NOT open the menu.
SITE SETUP
It seems that the old theme used jQuery to handle the collapse of the menu.
I have installed the jquery_ui module.
I added jquery to the .libraries.yml file
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.once

There are 4 template files which the only reason I can see is so that the main menu (which is hardcoded) can style the active menu item for the page.

page--node--2.html.twig
page--node--3.html.twig
page--node--6.html.twig
page.html.twig

Each of those pages has as the last line of the page a reference to the JavaScript file located in the site as
<script src="sites/all/themes/custom/mytheme/js/main.js"></script>
FIXED SOME OF IT
Adding jquery.main.js to the /js directory and adding the reference to it in the .library.yml file as
  js:
    js/main.js: {}
    js/jquery.main.js: {}

was enough to get all of the pages to collapse and open the menu EXCEPT THE FRONT PAGE.
JURY-RIG
I can get the front page menu to work if I add a reference to the bottom of the page to the jquery.main.js file I manually added to the local /js directory.
<script src="sites/all/themes/custom/mytheme/js/main.js"></script>
But then the other pages (not node 2, 3 or 6) which should use page.html.twig are run, it does NOT un-collapse the menu.
So for now I make a page--front.html.twig file which includes BOTH script referecnes to the JavaScript files, and all other pages have just the one (to main.js).
QUESTION
I have a couple:

What is the more standard way to situate this? I don't imagine that having a local jquery.main.js file is the best solution but it wasn't working with out it.
Why would the front page not operate like the other pages in accessing the JavaScript and jQuery?

Thank you for any insight.

Doing

<script src="sites/all/themes/custom/mytheme/js/main.js"></script>

is bad Drupal practice. As per the docs you should be doing
my_theme.libraries.yml
menu-collapse:
  version: 1.x
  js:
    js/main.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.once

page--node--2.html.twig
page--node--3.html.twig
page--node--6.html.twig
page.html.twig
{{ attach_library('theme_name/menu-collapse') }}

inside the template file(s).
Note: If this functionality is meant to be for every single page, rather then having to always add this to every variation of page.html.twig, add this in html.html.twig instead.

If after doing the above, the issue still persists

Why would the front page not operate like the other pages in accessing
the JavaScript and jQuery?

Possibly due to jQuery being loaded twice.
Go to /admin/config/development/performance and uncheck Aggregate JavaScript files (remember to turn back on after your're finished debugging)
Then on your front page, right mouse click, and select inspect
Go to network, and select JS, then refresh the page with the inspector open. You'll be able to see all the JS files that are loaded.

If there are no jQuery duplicates, in the inspector go to the "Console tab" and see if there is a JS error.


Can't find created block I'm trying to create a custom block programmatically in a Drupal 7 project.
I've implemented the two hooks hook_block_info() and hook_block_view($delta=''), I can't find the created block on my_site/admin/structure/block admin page.
Here is my code:

<?php

/**
 * @file
 * File for Header module block
 */

/**
 * Implements hook_block_info().
 */
function my_header_block_info() {
  return array(
    "headers" => array(
      "info" => "Header Block",
      "cache" => DRUPAL_NO_CACHE,
    ),
  );
}

/**
 * Implements hook_block_view().
 */
function my_header_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case "headers" :
      $block['subject'] = 'HEADER';
      $block['content'] = 'Hello world';
      break;
  }

  return $block;
}

What did I do wrong?

UPDATE
It's a basic project should I install a necessary contrib module for make it working?

Both of the below formats should work,

function my_header_block_info() {
  return array(
    "headers" = array( //I have Replaced => with = on your code
      "info" => "Header Block",
      "cache" => DRUPAL_NO_CACHE,
    ),
  );
}

-----OR-----

function my_header_block_info() {
    $blocks = array();
    $blocks['headers'] = array(
        'info' => 'Header Block',
        'cache' => DRUPAL_NO_CACHE
    );
    return $blocks;
}

Make sure to clear the cache after updated your code.


How do I remove the "Request New Password" link? When I visit www.example.com/user, there is a page that shows the login/password and as well as a "Request New Password" tab.

How do I remove this "Request New Password" tab from the user page?

The No Request New Password module is probably the easiest way to go, though you'll need to dig for the 6.x releases. This disables any request to user/password, so this path with neither be accessible directly nor display in menus/tabs/links.

Alternatively, you can put its main function into your own custom module:

 /**
  * Implementation of hook_menu_alter().
  */

 function MYMODULE_menu_alter(&$callback) {
     $callback['user/password'] = array('access arguments' => array(FALSE));
 }


Text Resize but with defined font sizes? I am using the Text Resize module to dynamically change the font size of my page content. However, instead of having two buttons which increases and decreases font size, I need, instead, to have three buttons so when the user clicks on one, the font size will be set to a preset value. This value should be able to be changed by the client themselves.

Is there a module which is similar to Text Resize but with defined font sizes?

You can use Text Size. It provides 3 buttons and also has settings for increment/decrement step.

step 1: go to admin/config
step 2: User interface -> Text Resize click
step 3: tick Add Reset Button then save


custom hash generated password and module wise added db password is different? function custom_submit_method(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $cusers = $form_state->getValue(array('name'));
  $cpass = $form_state->getValue(array('pass'));

  $gh = new \Drupal\Core\Password\PhpassHashedPassword();
  $hash_password = $gh->hash($cpass);
  $check_pass = $gh->check($cpass, $hash_password);

  //  \Drupal::logger(' customusersubmit')->notice('customusersubmit submit ') ;

 //  login_finalize($cusers, $cpass);

   drupal_set_message($hash_password .'------------'. $check_pass);
 }

Output : $S$5JdG.BjCPSTzc03AJ7aYPwMMH6HR.63IDUzqG3h2kkjG0NEcXtIo------------1 for admin

 Admin Password: $S$EnLPNV41YaHAPKhzwTGHVIir.OlOyK9ngYyEzVKdsd//WMnlaegV

When on comparing to db admin password the hash generated salt value is    different. It timely change for every runtime.

Kindly suggest me the Idea.

Yes, that is correct: The password is always salted with a different string.

If you want to verify a password, don't hash it, just check it against the value that was stored, that does work.

You're probably asking the wrong question. Explain what you're actually trying to do.


how to generate view data from sql query? i need to create a view that display last post for each user to make them into carousel, i do many search but no pure response. than i will try to generate my view from this sql query:

SELECT *
FROM `node`
WHERE `type` = 'post'
AND `nid`
IN (
SELECT MAX( `nid` )
FROM `node`
WHERE `type` = 'post'
GROUP BY `uid`
)
LIMIT 0 , 30

Any Idea?

It looks like you're selecting 30 nodes of type 'post' and grouping them by user.  This view would be pretty easily built using the views UI. Once you've created the view, you should be able to add an author uid as a grouping field.  This will group the post fields by author.

Let me know if you have questions.


How to send a message notification based on a flagged node being linked via entity reference? I'm trying to figure out how to make the following work: Sending notification based on flagged node being linked via entity reference.

I have a 'News' content type and a 'Band' content type, that has a flag called 'fan'. When somebody becomes a fan, I want them to receive a notification via the Message module whenever I link the band to the content type 'News' with the News article I just created.

The content-type setup is as follows:

Node type 'News' has field:
Entity reference to content type 'Band'
The Band content type has a flag called 'fan'
The Message type is called "user notification center" and has a field named field_mnc_recipients, which is an reference to a user(unlimited values)

How I want it to work:

when a user flags the 'band' and a new article is referenced to the band, I want to notify them with the Message module,
to make it work, I need to get the user from the flag for that band and insert it into the message field  field_mnc_recipients.

I created a Rules Component as follows:

{ "rules_message_tes3" : {
"LABEL" : "message tes3",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : {
  "referencing_node" : { "label" : "referencing_node", "type" : "node" },
  "referenced_node" : { "label" : "referenced_node", "type" : "message" }
},
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "referencing-node" ],
      "type" : { "value" : { "bands" : "bands" } }
    }
  },
  { "entity_is_of_type" : { "entity" : [ "referenced-node" ], "type" : "message" } },
  { "entity_has_field" : { "entity" : [ "referenced-node" ], "field" : "field_mnc_recipients" } }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "referencing-node:flag-fan-user" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "data_set" : {
            "data" : [ "referenced-node:field-mnc-recipients" ],
            "value" : [ "referencing-node:flag-fan-user" ]
          }
        },
        { "entity_create" : {
            "USING" : {
              "type" : "message",
              "param_type" : "user_notification_center",
              "param_user" : [ "site:current-user" ]
            },
            "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
          }
        }
      ]
    }
  }
]

}
}

And now I got stuck, I based the component on "Sending a message to users of a flagged node when it is referenced" which is close to what I want.

It works, after days and days it finaly works! I used this as a base line for my research: Sending a message to users of a flagged node when it is referenced

Instead of sending an e-mail within the loop, i create a new entity(action), in this case the message notification. After that i fill(set data) in the entity-created:field-mnc-recipients field with the flagging users. This is how it works :)


Features - branch 2.x results in large info files that exceed the 'info' column limit in the 'system' table Original thread on DO (will keep it up to date)

Hello. I am currently developing a mid-to-large project. As i've done before, but using the 1.x branch, I use Features to track all structural and functional components of my site in order to be able to transfer them from my local installation, to the staging server, to the production server etc, while also having svn capabilities and tracking.

The current project consists of 45 Content Types with an average of 15 fields each. There are also ~15 vocabularies, ~10 fieldgroups, and a couple of tons of views.

The problem occurs when trying to track all this stuff with Features. It produces a large (initially, just alpha versions of the Content Types) .info file ( > 100K) which results in the following error:

PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'info' at row 1: UPDATE {system} SET info=:db_update_placeholder_0 WHERE
// yada yada yada serialized array of the .info file

Which is totally natural seeing that the collumn is declared as a BLOB.

My question, is how should one go about to manage such a problem?
1) perform a ALTER TABLE system CHANGE info info LONGBLOB /* or MEDIUMBLOB */ NULL DEFAULT NULL? (Ouch)
2) Use branch 1.x instead which is less verbose in the .info file declarations?
3) Break down the project and track it in multiple features? (I'd avoid this cause it will make reverting those features a hellish job since one would depend on the other and vice versa)
4) ...?

I'd appreciate any input on the matter

The way I see it, you have options:

Features

Break your Features down into smaller Features.  Yes, this might make the dependencies a little more effort to manage, but a Feature containing that many content types, as well as other config does seem a little extreme.

If you do break them up, and are worried about dependencies, create a controller module to deal with them.  Every time you add/break down a Feature, add it as a dependency to this controller module, then make your new Feature depend on the controller module.

This means that all other dependencies will be inherited by the Feature, but you've only had to declare it in one place. When you then disable any part of your Feature, everything will get disabled - which is the same behaviour as having one monolithic Feature.

As an added bonus, if you perform updates to your Features that require hook_install or hook_update_N, they can go in the controller module.

Configuration Management

If the idea of breaking down your Features really sends shivers down your spine, then check out Configuration Management, which can do what you want (track EVERYTHING), and if pretty easily extensible if you are happy writing your own code. This is also the route Drupal 8 is taking/has taken with configuration management, so with this method you'll be future-proofing your own knowledge.

My personal preference is Features, but if you are looking for something that wouldn't involve you breaking down a huge Feature into smaller ones, then Configuration Management is a solid option.


Delete all nodes from database except from user1 and admin I have got thousands of junk entries in my Drupal 6 website. Is there a way I can Delete all nodes from database accept from user1 and admin.

I also want to delete all users accept user1 and admin.

Yes, you could do that with

views_bulk_operations

It will delete the nodes and users progressively using the Batch API.

Create a content / node based View
Add the bulk operations field
Configure bulk operations field to add "Delete item'
Add filters to View to exclude content from user1 / admin
Run the View, check to select all rows, and bulk delete the relevant nodes.

Repeat using a user-based View to delete users.

Note, prior to deleting users, check the account cancellation settings at Admin > Configuration > Account settings > Registration and cancellation


Print result of $body on D7 and I've made this:

function project() {
  global $user;
  $uid = $user->uid;
  $name = $user->name;

  $teaser = 0;
  $page = 1;
  $type = 'page';
  $status = 1;
  $format = 3;

  $body = " ".
                "

Projects from user ".$name."

";
}
?>

And I need to print the result on the main content of my theme, how can I do it?
If I do echo "$body";I view the result not in the main content but as a single page. Thanks a lot.


Adding custom block problems I've created my own module in drupal 8. I also created block in my module.
I tryied to add my custom block (which is type of custom form) to view. But when I am trying to add custom block in view, its not appearing in the list. Block is only appearing in block layout. What is wrong or is there other way of adding custom block from module to your view in drupal 8?

<?php
/**
 * @file
 * Contains \Drupal\reviewhelper\Plugin\Block\ReviewHelperBlock.
 */
namespace Drupal\reviewhelper\Plugin\Block;

use Drupal\reviewhelper\Form;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'ReviewHelper' Block
 *
 * @Block(
 *   id = "ReviewHelper",
 *   admin_label = @Translation("Review helper block"),
 *   category = @Translation("Custom Blocks"),
 * )
 */
class ReviewHelperBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\reviewhelper\Form\ReviewHelperPush');
    return $form;
  }
}

There are two different "block things". Actually, three.

First, there are block plugins. That's code, that's what you have. It's the thing you select on the block layout page. It's not something that you can list with views (Well, theoretically, it would be possible, but you would have to write a views query plugin that queries plugins.)
Then, there block config entities. That's a plugin + configuration, a block placement.
Last, there are custom blocks or content blocks. Those are content entities, similar to nodes with different types, fields and so on. Those are the user-created data. Each of them is exposed on the block layout page as a plugin derivate. There's one plugin class for them and then there are derivates for each content entity. Those are the things you can list with views. Only those.

Everything is connected, you can create custom/content blocks, which are exposes as a block plugin, which is then placed and becomes a block config entity. But they're all different things.


Field-images wont be migrated in a migrate-upgrade --- Not sure if it's a bug I try to Migrate-upgrade a D 7.44 site to D 8.1.3 and all seem to be migrated besides API images (i.e images uploaded in image fields).

Images uploaded in CKeditor with IMCE, on the other hand, appear just fine.

I am not sure if that's a bug because AFAIK, tens if not hundreds of sites were upgraded without that a problem.

Details that might help you conclude if this is a bug:

The D7 site files folder permissions is 755.
The D8 site files folder permissions is 777.
The node__field_image table in the D8 DB is empty (i.e zero rows).
The files path I gave in the Migrate UI module is /var/www/html/benia.biz/sites/default/files as in the first image here.
The second image describes a warning I saw while migrating and it might be associated to the problem. This warning deals with duplicated image paths, though I have no clue why it would appear.

Image1:

Image2:

You've included a critical piece of information here which was not included in https://www.drupal.org/node/2759309:

You specified your file path as /var/www/html/benia.biz/sites/default/files.

Actually it should be /var/www/html/benia.biz/.

The sites/default/files portion is automatically included in the file paths by the migration process.

In the correct path note you have an extra slash (one after the benia.biz so it's benia.biz/); Missing this slash as well could make the migration process miss the images.


One-One mapping between content types I have 2 content types named All Events and Event. Event as the name is self descriptive it represents an single event (programme). Whereas All Events contains additional data related to events, that is not part of any single event.

I need to have a relationship which says 'Featured Event'. And that relationship is going to be one-one. What would be the best way to select featured event among those events?

To organize this I can create a field collection field where each collection represents an event. And again selecting featured content would be question. Having a field in event to make it featured won't work, since 'one-one' wont be respected by the system and user need to take care of it.

It's not too clear to me what you are asking but if you want to relate a content-type to another content-type you can use the Node reference from the References module.

You can include a field on your Event content type called Featured Event and relate it back to the All Events content type. Then limit the amount of values to one. Then when you create a node from the Event CT, you can relate it to whatever node you want from the All Events CT. Vice-versa you can create a relationship through the All Events nodes if you wanted to as well.

Then if you wanted you could use the Corresponding node references module to sync up node to node. This module will warn you if you have overloading references (more than 1:1 for a node) basically helping keep the integrity of the 1:1 relationship.


Question about D7 Organic Groups, Memberships, and Views I have been using OG and Views on Drupal 7. I think it's great but am having one problem. Here's the situation: I am creating views of content, and am wanting to show which group each piece of content is a "member" of. To do this, I bring in a "group membership" relationship and then another group relationship, which then lets me show the GID, title, etc., from the Organic Group.

But here's the problem: as soon as I introduce the "OG membership" relationship into the mix, it begins to show each piece of content twice (or 3 or 4 times) if that content is posted into 2, 3, or 4 groups. I think this is because in the og_memberships table, each membership has its own ID.

What I'd like to do is show each piece of content once, but have a "multiple" type setting on the OG field area, the same way I can show multiple imagefields or Taxonomy terms that are all related to one node.

Anyone got experience with this?

That sounds more like an issue with the SQL query, called a Cartesian join.  It's where you join every row of one table to every row in another table, or to itself, resulting in lots of duplicated rows. Dump the SQL that the View is creating and run it by itself in the database client to see if that's the source of the problem.


Drupal 7, passing URL arguments page not found Good evening. Please help me.

I built my website on my home pc using Wamp as webserver.  On one page I pass arguments to backend.php via URL.

Like this

echo "<button >nbsp$row[1]</button>";

The code is working fine.

Now I uploaded the site to my godaddy hosting and can’t send the argument in the same manner.  I gives me 404.
The requested page "/backend.php?g=http://bc.luckyfaucets.com/" could not be found.

The code is exactly the same as on my home server,  .htaccess is the same and they both have clean URL enabled.
Can someone tell me the cause of this ?

This is the backend.php file.

<?php
define('DRUPAL_ROOT', getcwd());
require_once
DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
variable_set('ref', $_GET['g']);
$g = $_GET['g'];

$con=mysqli_connect($db_host,$db_user,$db_pwd,$database);

// Get infos siteid sitecyle from _sites_
$result = mysqli_query($con, "SELECT `siteid`, `sitecycle` FROM `_sites_` WHERE     `siteurl` = '$g'");

while($row = mysqli_fetch_row($result)) {
$siteid = $row[0];
$sitecycle = $row[1];
// Count time + sitecycle
$next = (time() + ($row[1]*60)+15);
}
// Update _counters_
$result = mysqli_query($con, "SELECT `siteid`, `uid` FROM _counters_ WHERE `uid` ='$user->uid' AND `siteid` ='$siteid'");
if( mysqli_num_rows($result) > 0) {
    mysqli_query($con, "UPDATE _counters_ SET `cycleend` = '$next' WHERE `uid` = '$user->uid' AND `siteid` = '$siteid'");
    }
else
{
    mysqli_query($con, "INSERT INTO _counters_ (uid, siteid, cycleend) VALUES ('$user->uid', '$siteid', '$next')");
 }
 drupal_goto('page');
?>

I would like to know what/why the same code does work with Wamp but not on my hosting. Is this maybe cause by some setting at godaddy?

Thanks for the help

Try editing your .htaccess file and uncomment the following line:

RewriteBase /


Managed File Field and file_usage_add() - what should I attach the file to? I'm creating a module which uses the Form API and integrates with the Mantis bugtracker system.  I have included a managed file field on the form and am at the stage of handling the form submission.  The Form API documentation mentions that you must make a call to file_usage_add:

Without the call to file_usage_add, file_managed_file_validate produces an error upon saving the form, saying that the uploaded file may not be referenced.

Here is the signature for file_usage_add():

file_usage_add(stdClass $file, $module, $type, $id, $count = 1)

And the explanation of the parameters:

$file: A file object.

$module: The name of the module using the file.

$type: The type of the object that contains the referenced file.

$id: The unique, numeric ID of the object containing the referenced file.

$count: (optional) The number of references to add to the object. Defaults to 1.

The problem I have is that my module doesn't create any nodes to attach the file to.  I just want to store the file in the filesystem and then send it off to Mantis.

Any suggestions on what I can enter for the $type and $id parameters?

I attached the file to user 1 and can't see any adverse effects as yet:

file_usage_add($file, 'mantis', 'user', 1);

I also OMITTED the following line from my submit function:

$file->status = FILE_STATUS_PERMANENT;

This means that the file will be deleted after 6 hours when cron runs.

If anyone has a better solution then I'll be happy to mark as answer.


Profile2 restrict main profile I really don't know how to fix this so whats why im posting this over here.

Im using Profile2 for my profiles The Main profile is for authenicated users, lets can this User A.

I have also another profile type, with a seperate registration form, lets call this user B.

When user B wants to edit his profile, he can also choose to edit his main profile (profile for user A), i figured out that because user B is authenticaded he can automaticly edit his main profile, and his own profile (specially for user B's). How can i prevent user B for edit his main profile?

One solution would be to create two roles, one for A and one for B - then you can restrict access to different profiles in permissions under admin/people/permissions .

You could use Rules to assign the appropriate role based on selections during registration, and use the 'After Saving a new user account' trigger.


Does memcache allow anonymous users to be served content when the database server is down? I'm exploring options around keeping my Drupal 7 sites working for anonymous visitors while a database server is being upgraded.  The site is already fronted by Cloudflare - but their always on tech is a little hit and miss.

I'd like to understand more about when the database is queried when using the memcache module.  My other choice is to use the AutoSlave module and setup a master - slave replication - but if I can get a performance boost from memcache and a little resilience added in - I'd maybe prefer that route.

I'm hoping that the page cache will remain relevant enough to perform the database upgrade.  What are the rules around the memcache content going stale?

As stated in the comments, memcache is probably not going to help you here.

Since you are using CF as a front end, you might be able to get by by creating a page rule to cache everything.  See this doc.  This assumes that your site is pretty static (e.g. not an e-commerce or has user logins.

I'd suggest creating a script to load all your pages prior to shutting down the sql server.  I.e., clear the CF cache then load all the pages into cache using the script.  A bunch of CURL statements should work.  Make sure to load ALL the content (e.g. images, css, scripts).

That said, I really would not depend on this.  Personally, I'd set up a temporary DB server, copy the DB to it, then change the settings.php to point to it when the main DB is being updated.  Then swap it back after the update.


How to filter a view based for the current user based the value of custom fields in his profile and fields in the list of items viewed I'd like to implement Views that conditionally show or hide item listings of content nodes to the current User based on:
(1) value(s) in the current User's profile and
(2) value(s) in the profile of the author of each item and
(3) value(s) in each content node itself.

A good example would be a classified ad system that enabled advertisers to specify that a given ad be shown only to users whose profiles meet a set of specific criteria.

For example:
A Drupal site with User Accounts with custom fields to capture each user's age, height, and hair, and a Content Type for advertisements with the same fields.

The challenge is how to construct a View that supports a use case like the following:
Users who will look at the View:
= David is a bald, 6.5 foot, 70 yr old.
= Edward is a blond, 5'5", 18 year old.
= Fred is a brown-haired, 5'11", 30 year old.
Ads that can be displayed in the View as follows:
= "Miracle Grow Hair Spray" posted by Abby to be shown only to bald people.
= "NuEar Hearing Aids" posted by Betty to be shown only to people over age 65.
= "Big and Tall Shop" posted by Carol only to be shown to people over 6 feet tall.

In summary, I'm trying to filter tablular View of nodes based on attributes of the content nodes, the authors of the node, and the current user who is looking at the View.
The standard Views filter UI supports filters based on attributes of each node in the table, but does not appear to permit any use of information about the current user other than his login state.

Any advice and references to doing the filtering at the granularity of each node would be greatly appreciated!

I'll take the assumption that your using a content view, that way we're only making relationships to the user or user of said content.

Essentially you could add an entity reference to a taxonomy term which would in turn be referencing the piece of content to filter. So;

We create a new vocabulary, add the entity reference field. Create a new term, we'll call this 'bald'. Bald will make an entity reference to the content item 'Miracle Grow Hair Spray'.

Next we'll add a taxonomy reference field to the user profile. This will reference the users 'properies' from our new vocabulary. E.G. if our user is bald we will reference this term.

Lastly on the view we should have enough data to make a bridge to the piece of content being referenced by the term associated with said user.

Although basic & very roughly explained this should hopefully help.


How can I print the file size and other file info in a Views field template? I have created a content type with a number of fields including file fields. In the node template for that CT (node--unit.html.twig) I am able to get the details with the following code:

{% if content.field_files.0 %}
   {% for key, value in content.field_files if key|first != '#' %}
      {{ content.field_files[key]['#description']}}
   {% endfor %}
{% endif %}

Now I'm trying to get those same details for the field inside a view that lists nodes of that CT but the above code doesn't work. In fact all I can get from the field is the 'content' using the following code inside the views-view-field template (views-view-fields--units-e-resource-sheets.html.twig):

{{ fields.field_e_resources.content}}

All I can find using kint and other tools is the target_id attribute. Do I have to use this to retrieve those other details in the view?

Well with some pointers from colleagues I have found out what I was doing wrong!

In the node you have all that info already there but views and their displays are more stripped back to keep them 'lean' so you have to be explicit that you need that info...

Step 1 - add a 'relationship' to the field

In the settings for the display of the view, I added a relationship to the file from the field under the 'advanced' settings using the 'add' button and it shows like this:

Step 2 - add fields for the stuff from the relationship

Under the fields for the view display I can now add fields for the relationship I just created. I added one for the URI and one for the filesize using the 'add' button and they show like this:

Step 3 - build the template

Now you can use those just like any regular field in the template. Here is the code I'm using to build a link with the file extension, filesize and a link to download the file:

<a href="{{ file_url(fields.uri.content|striptags|trim|convert_encoding('UTF-8', 'HTML-ENTITIES')) }}" target="_blank">Download
  (.{{ fields.field_e_resources.content|striptags|split('.')[1] }})({{ fields.filesize.content }})
</a>

Conclusion

I couldn't access the details for the uploaded file because they aren't included by default so by building the relationships as required you can add to the available fields and get the job done!


How can I create a table view of entities showing their related entities in the same row? I have multiple content types, which are in some ways related to each other. Lets say, the first one is "Author". Other ones are "Novel", "Drama" and "Short Story", which each reference "Author" (using the same field for each content type, so I can create relationships easier later in the view).
Now I want to create a view table like this:

Author
Novels
Dramas
Short Stories

King, S.
It, Insomnia, ...
...
Rush Call, ...

Martin, G. R. R.
ASOIF, ...
...
...

...
...
...
...

For each author there should be one(!) row in the table and for each text type they wrote there should be a column in the table showing the titles of that text type comma separated.
How can I achieve this output using views? I tried different ways of grouping and aggregation, but none of them quite worked. For example, when I try to group by "Novel", the tables split and it looks awful. I would have no problem styling the final results in a custom template, but what can I do using core views to get to my desired outcome a little bit easier?

I don't see a way of creating with vanilla Views, that without changing the templates.

Starting from the Author Views is the worse path to take. You can use reverse Relationships to show nodes that reference a particular Author, but they will be in separate rows, reverse Relationship doesn't support Multivalue options that you get when directly displaying an ER field.

The best path seems to be to create Content Views that lists all  "Novel", "Drama", and "Short Story" nodes. Add the Title Field, Author ER, and the CT (type).
(I don't know if there is some magical Agreggate trick that could work to your solution, the usual ones I've used aren't sufficient for something like this.)
Hide the Author field with Exclude from display and then under Format Settings select the Author field as the Grouping field.
This will still give you each book in its own row, but they will be grouped by their authors. With some template changes you can change the grouping to appear within the table so it appears more like you'd like, with the Author as a column that spreads multiple rows (their work) and all results can be displayed within one table where each author info is within separate tbody elements.
With some more templates adjusted I think you could get to construct exactly the table you want where work nodes of the same type are printed out in the same cell, and types come out as columns, but it wouldn't be trivial.

You might also try the Views Field View module. This is usually used to embed Views within Views (that are related through a field such as an ER field) but it can be very heavy on the performance!
I also haven't tried it under the reverse condition, assuming you start from the author and then get to the relating nodes through backwards Relationships. But OTTOMH it seems possible, you could list all work in the same table row as the Author, each work would still be in a separate row but you could group them by type though. The types wouldn't display horizontally like in your case, but vertically, still it would be close to what you want to achieve. And you could use templates to replace the output of the "embedded" Views (works) to match it closer to what you had in mind.


cannot enable module after DB migration, only in one environment I have 3 environments: live, stage & dev.

I've taken a database backup from live and imported into stage & dev.

I clear all caches on stage & dev and navigate to /admin/modules to turn on module_a but on stage it's disabled and i'm unable to enable it.

It seems strange that I am enable it locally but it's disabled on stage.

How do I go about debugging this?

The system module builds this form in the function system_modules(). It disables a module in the UI under 3 conditions:

The module is required by your Drupal distribution.
The module is missing a dependency.
The module (or one of its dependencies) has version incompatibility with Drupal core.

In any of these cases, you can click the Description fieldset which shows the dependencies required and highlights the ones that are missing.

Another direct method is to utilize the Drush command:

drush en module_a

Drush will attempt to enable the module and alert you if module_a doesn't exist or it has unmet dependencies (which should help you track down what is missing).


What is causing /user/*/taxonomy/term/* to redirect to /taxonomy/term/*? I got a view with contextual filters set up as the following:

Global: Null (Fixed value "user")
Content: Author uid (User ID from URL)
Global: Null (Fixed value "taxonomy")
Global: Null (Fixed value "term")
Content: Has taxonomy term ID (Taxonomy term ID from URL)

When I go to mysite.com/user/*/taxonomy/term/* I'm being redirected to mysite.com/taxonomy/term/*.

How can I prevent this?

I also got Pathauto to change the URLs to [user:name] for user/* and tags/[term:name]for taxonomy/term/*.

Edit: If I disable the URL alias for the taxonomy terms it still redirects to mysite.com/taxonomy/term/*.

The source of the redirect could be essentially any module you have, and several modules allow for configuration that will cause redirects as well. You will need find the source of the redirect on for your particular situation.
Suggestions:

Deactivate modules in a 50 / 50 manner. This allows you to quickly narrow down which module is providing the redirect, and hopefully that will help you to work it out. Using drush to disable/enable modules will make this much faster.

Install Devel. It has a settings called "Display redirection page", and implements devel_drupal_goto_alter halting the redirection.
The primary purpose of this is to gather up debug information that would otherwise go lost due to the redirect. In this particular case, I suggest you add a dpm(debug_backtrace()); into the hook so you can trace the call to the source of the redirect.

Everything else failing, fire up a full debugger, and trace the call, ideally with help from the information provided by the debug_backtrace() above.


How can I alter Entity Auto Complete Results? I want to alter entity auto complete results in hook_form_alter.
My functionality is

  1) I have a entity reference of taxonomy and bundle is tags which is
  Level 2 (Field Name: Product Child)

  2) In this I select one term from Level2

  3) I have another entity autocomplete which refers to taxonomy
  tags Level 1 (Field Name: Product Parent)

Now my question is if i select one Level 2 Term in Product Child Field , is there any option to show only parent terms of that Product child field in Product Parent Field
Like :

Cabbage (L1)
 -> Fruit (L2)
 -> Flower (L2)

Lemon(L1)
 -> Lemon Fruit(L2)
 -> Eatable (L2)

If I select Fruit in Product Child field I want to show only Lemon in Product Parent Field. Is there any way to do this.

I wrote a little module that shows how to alter entity autocomplete suggestions. You could try modify it to meet your needs.
https://github.com/minnur/Alter-Entity-Autocomplete


Block visibility using PHP to show Vocabulary and Terms not working In Drupal 6 I used PHP for Block visibility on selected vocabularies and terms.

The same PHP code does not work in Drupal 7 on a Centos 7 computer. Does PHP 4.4. not work on a PHP 4.5 server? I am using the same examples found here:
https://www.drupal.org/comment/reply/69076#comment-form

Modules written for Drupal 6 are not designed to work with Drupal 7. Some do, by fluke, but it's quite rare. Sounds like you have one of the more common ones, that doesn't.

I'm not sure what you mean by

  Does php4.4. not work on a php4.5 server?

I think you're confusing several things there, none of which would be related to Drupal.

If you want to know what versions of PHP Drupal supports, see the requirements. If you want to know what version your server supports, your hosting provider will be able to tell you.

Some modules have specific minimum PHP version requirements; you can find those in the module's .info file, and you'll also be informed in the UI if your system can't support it.


How to pass dynamic parameters through a local action button? I created a local action button with the following in my_module.links.action.yml:

my_module.content.action:
  route_name: node.add_page
  title: 'My action'
  deriver: 'Drupal\my_module\Plugin\Derivative\ContentByDomainLocalActions'
  appears_on:
    - view.affiliated_content.page_1

Then, the local action button appears in the page admin/content/domain-content/firstdomain_local

I'd like use the argument firstdomain_local from this URL path to pass it in my local action button.

So, I retrieve the param from \Drupal::routeMatch() in getDerivativeDefinitions, like in this tutorial:

class CustomLocalActions extends DeriverBase {
  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives['example.action_id'] = $base_plugin_definition;
    $this->derivatives['example.action_id']['title'] = "Add content";
    $domain = \Drupal::routeMatch()->getParameter('arg_0');
    $this->derivatives['example.action_id']['route_parameters'] = [
      'domain' => $domain
    ];
    return $this->derivatives;
  }
}

But the param of the local action button is only updated after I clear the cache. I have to clear the cache each time I use different parameter value in the URL.

What's the correct way to pass dynamically this argument?

Local actions and local tasks are quite similar, so looking at the Customising local task behavior I've managed to pass in dynamic route parameters to my local actions by specifying the class parameter (MyClassName) in my_module.links.action.yml and overriding the LocalActionDefault::getRouteParameters() method in that class. Only one initial cache rebuild was required.

use Drupal\Core\Menu\LocalActionDefault;
use Drupal\Core\Routing\RouteMatchInterface;

class MyClassName extends LocalActionDefault {

  public function getRouteParameters(RouteMatchInterface $route_match) {
    return array(
      'my_local_action_parameter' => $route_match->getParameter('existing_parameter_from_route')
    );
  }
}


I have a field which looks corrupted. How should I remove all traces of it? Problem

I have a taxonomy field that I was forced to re-create with different values after a number of errors. (I deleted the field and taxonomy and re-created them.)

It's used as an exposed filter in views and unfortunately appears to have become corrupted. Whenever I use it as a filter, in the drop down it only shows the previous values of the field (before it was re-created).

Clearing the cache, re-creating the field, clearing the search indexes, creating new views have all had no effect. Other identical field names with different machine names work fine so I'm presuming it's corrupted.

How should I go about cleaning this field from my database?

I'm considering just re-making it under a different name but I'm worried about the consequences of leaving some corruption in my database.

This is totally off the top of my head so use with much caution, and after taking lots of backups!

// Remove taxonomy index records. Do this BEFORE removing field data tables.
$indexed_tids = db_query("SELECT field_foo_tid FROM field_data_field_foo WHERE entity_type = 'node' AND bundle = 'bundle_field_is_attached_to'")->fetchCol();
db_delete('taxonomy_index')->condition('tid', $indexed_tids)->execute();

// Remove the field data tables completely
db_drop_table('field_data_field_foo');
db_drop_table('field_revision_field_foo');

// Remove the field config
db_delete('field_config')->condition('field_name', 'field_foo')->execute();
db_delete('field_config_instance')->condition('field_name', 'field_foo')->execute();

// Clear up
drupal_flush_all_caches();

That should get tid of a taxonomy field called field_foo, and all associated index data.

Note this is for a core install - if you have other modules installed that rely on that field or taxonomy data in some way, things might not be so easy.


How to limit access to content for which the Content Access module doesn't limit access? I run a small business, and have created a website in Drupal 8 (should have used 7, bit late now, oooops).

Part of the website is designed to be behind a subscription, which I've got working and works well. Only problem is, the content types I want to only be visible to people who have paid, are visible to everyone.

I installed the Content Access module and have set it up thus:

As you can see, "view any checklist content" is set as only "subscriber - bronze" which is currently the only role that'll need it.

When logged out, the page is visible; when logged in (as admin or a test account using that role) it's visible.

Rebuilding permissions is a pain (~20k nodes), but using Drupal Console I can do so and it runs successfully, but no change to the page's permissions.

I prefer to use Node view permissions for this. As long as all you are trying to do is control access to content types based to user type.


Display Suite Custom Template Issues I've been using Display Suite for Drupal 7 (with Bamboo theme,) and I'm trying to build a layout template that contains 5 rows, so I can place the appropriate fields into each row, making all content nice and tidy.

I've followed the instructions here, but I'm doing something wrong: https://www.drupal.org/node/1098068

I'm guessing it has to do with the PHP code, because I'm getting errors involving my wrappers. Here is the PHP code for the tpl.php file:

<?php

/**
 * @file
 * Display Suite Bamboo custom template.
 */
?>
<<?php print $layout_wrapper; print $layout_attributes; ?> class="ds-bamboo <?php print $classes;?> clearfix">

  <?php if (isset($title_suffix['contextual_links'])): ?>
  <?php print render($title_suffix['contextual_links']); ?>
  <?php endif; ?>

  <<?php print $first_wrapper ?> class="introduction<?php print $first_classes; ?>">
    <?php print $first; ?>
  </<?php print $first_wrapper ?>>

  <<?php print $second_wrapper ?> class="entry1-group<?php print $second_classes; ?>">
    <?php print $second; ?>
  </<?php print $second_wrapper ?>>

  <<?php print $third_wrapper ?> class="entry2-group<?php print $third_classes; ?>">
    <?php print $third; ?>
  </<?php print $third_wrapper ?>>

<<?php print $fourth_wrapper ?> class="entry3-group<?php print $third_classes; ?>">
    <?php print $fourth; ?>
  </<?php print $fourth_wrapper ?>>

  <<?php print $footer_wrapper ?> class="group-footer<?php print $footer_classes; ?>">
    <?php print $footer; ?>
  </<?php print $footer_wrapper ?>>

</<?php print $layout_wrapper ?>>

<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

I think it is very possible I am also writing my .inc file incorrectly. Here is that code as well:

<?php
function ds_ds_bamboo () {
  return array(
    'label' => t('Bamboo DS'),
    'regions' => array(

        'introduction' => t('Introduction'),
    'entry1-group' => t('Entry 1'),
    'entry2-group' => t('Entry 2'),
    'entry3-group' => t('Entry 3'),
    'group-footer' => t('Footer'),
          ),
    // Add this line if there is a default css file.
    'css' => TRUE,
      );
}

I would be very appreciative if someone can set me in the right direction. Thank you!

I have managed to solve this problem, and I'm posting my own answer here in hopes that it will help someone else struggling with this.

First, when creating a Display Suite Custom Layout, follow the directions here: [https://www.drupal.org/node/1098068][1]

Then, if you are defining custom regions like I am, the trick is to create custom regions in your Drupal theme. To do this, go to sites/all/themes and enter the folder containing your theme. Then find your theme's .info file.

This should be where the regions in your theme are stored and created. To set up the regions that will work with the php code listed above, enter:

your_region_name = [name_of_custom_region]

I created 7 regions this way. For example, my first region is named:

introduction = [introduction]

This may be slightly different given how your theme is set to define regions, but this is what worked for me. I entered my new regions after the pre-existing Content region defined in the theme. (I have no idea if that makes a difference, but that is what worked for me.)

After you have defined the regions, insert and alter the php code from the question above in your Display Suite tpl.php file. (The link in the first step shows you how to define this file.)

You will then change some of the php code to reflect your custom regions. For example, if you defined your first region as "introduction" the code should look like this:

    <<?php print $introduction_wrapper ?> class="introduction<?php print $introduction_classes; ?>">
    <?php print $introduction; ?>
  </<?php print $introduction_wrapper ?>>

You will then need to alter the code each time, entering the next region name that you defined in the .info file in order.

Lastly, you will need to update your Display Suite custom layout .inc file.
I did this by defining each newly created custom region that I wanted to show up on the custom layout within Drupal. As an example, my code looked like this in the end:

    <?php
function ds_ds_bamboo () {
  return array(
    'label' => t('Bamboo DS'),
    'regions' => array(

    'articletitle' => t('Article Title'),
        'titleimage' => t('Title Image'),
    'introduction' => t('Introduction'),
    'entry1' => t('Entry 1'),
    'entry2' => t('Entry 2'),
    'entry3' => t('Entry 3'),
    'author' => t('Author Bio'),
          ),
    // Add this line if there is a default css file.
    'css' => TRUE,
      );
}

Doing this will create row-like regions that will allow you to neatly group Drupal fields together, giving you a template for future content.

As an example, my "entry1" region contains an image field, text field, another optional image field and text field, as well as a video embed field. Due to the structure of the code and Display Suite's field management, all of the fields and their content are kept nice and tidy within the custom region.

I hope this helps if you're struggling with defining custom layouts in Display Suite!


What is taxonomy/term/tid/* I'm first time seeing a link indexed by Google : taxonomy/term/10007/*  as in here.

What could be causing it?

I've already GlobalRedirect enabled, also not using the View "Taxonomy term" which emulates Drupal core's handling of taxonomy/term.

Removing the "*" from the path does trigger the redirection to the right page.

It seems to me the "*" is just confusing global redirect (maybe some setting not configured correctly in the module?), because the redirection is definitely not happening, and that might be the reason why google is indexing that.

I'd suggest double-checking the globalredirect settings in place.


How to create a multi step form that can be saved/edited by multiple users? I need some tips on how to implement a form with these specifications:

Multi steps. for example the user completes section 1 then clicks next to go to section 2 and so on (can be tabs or anything similar).
It can be saved, so users can come back to continue also multiple users can edit
Some users can add a new form to the site (with a different title for a new set of users)
Users should have different permission levels to interact with these forms (creator, editor or view only).

I've been looking at webform. But it doesn't seem to offer what I need. Because it doesn't use native Drupal fields. I need a form that stores data in Drupal standard format. This allows me to expand my form's capabilities (For example using views).
Are there any combination of modules that can be helpful here?

The Multistep module adds multiple-step functionality to CCK forms. It does so by assigning a step number to each fieldgroup within the content type and hiding all the groups that do not belong to the current step. The user can then use different submitting buttons that will redirect to the previous, next, or current step.

For further reference look into this link.


How to return drupal's articles image upload I am new in drupal

when I click on content>add content
I don't have the browse button to uploading image for article, maybe I removed accidentally from structure>content type or other...

How can I see that browse button again?

Go to Structure » Content types » Article >> Manage fileds

Add new field. Here is the sample screenshot


Colorbox First Field Image Style Using colorbox in views.

Can someone explain what the functionality of the "Content Image Style for first image" is?

At first glance, I would assume that it allows me to choose an image style for all of my gallery images, and then choose a different image style for the first image, allowing the first image in the gallery to be bigger or smaller, which would be very cool.

However, when I change the image style for the first image and save, all of my images in the gallery are changed to that style.

Am i missing the point here?

Ah, I have just figured this out.

This only works when you show all multiple fields in the same row.

Changing the field to display all images in the same row, and displaying them in an unordered list sorted it right away.


How to check for Grouping field in Views submodule? I'm developing on the Views Datasource module to enable grouping by field (not field aggregation). I've now got the output format that I want, but I don't know what variable the Grouping Field setting is stored in. I want to check if a grouping field is selected, and then assign the field's name as an array key if it is.

views-views-json-style-simple.tpl.php:

// TODO Enclose everything in an if statement, conditional
//   on a grouping field being selected

$grouped = array();

foreach ($rows["nodes"] as $nodenum => $nodearray) {
  // TODO Replace "building" with variable representing user-
  //   selected field.
  // Variable names will obviously change too.
  $building = $nodearray["node"]["building"];
  foreach ($nodearray["node"] as $cprop => $cvalue) {
    // TODO Replace "building" with grouping field variable
    if ($cprop != "building") { // Ignore grouped field
      $grouped[$building][$cprop][$nodenum] = $cvalue;
    }
  }
}

$rows = $grouped; // Pass back to existing code

The above code takes the $rows output by views, and reformats the array right before it goes to _views_json_json_encode. The idea is to take the default output of Views Datasource:

{
  "nodes" : [
    {
      "node" : {
        "name" : "Energy Services Performance Contract (ESCO)",
        "geometry" : "48.7366, -122.486",
        "description" : "This project was initiated In order to advance Western’s sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
        "building" : "BH"
      }
    },
    {
      "node" : {
        "name" : "Energy Services Performance Contract (ESCO)",
        "geometry" : "48.7378, -122.486",
        "description" : "This project was initiated In order to advance Western’s sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
        "building" : "WL"
      }
    },
    {
      "node" : {
        "name" : "Wilson Becoming Skyscraper",
        "geometry" : "48.7378, -122.486",
        "description" : "Wilson will have 708 floors added to it, becoming the tallest building ever.",
        "building" : "WL"
      }
    }
  ]
}

and turn it into

{
  "BH" : {
    "name" : [
      "Energy Services Performance Contract (ESCO)"
    ],
    "geometry" : [
      "48.7366, -122.486"
    ],
    "description" : [
      "This project was initiated In order to advance Western’s sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus."
    ]
  },
  "WL" : {
    "name" : {
      "1" : "Energy Services Performance Contract (ESCO)",
      "2" : "Wilson Becoming Skyscraper"
    },
    "geometry" : {
      "1" : "48.7378, -122.486",
      "2" : "48.7378, -122.486"
    },
    "description" : {
      "1" : "This project was initiated In order to advance Western’s sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
      "2" : "Wilson will have 708 floors added to it, becoming the tallest building ever.\n"
    }
  }
}

My question assumed that Views Datasource includes parent view format options such as grouping fields, but it does not. Rather than call all of the parent fields from the Views defaults, I copied only the field definition from views_plugin_style.inc to views_plugin_style_json.inc, within the options_form function.

The second part of my question was how to get the value of that field back out. It exists in $options["grouping"][$i]["field"], where $i is the Grouping Field Number, -1.

So, the value entered into "Grouping Field Nr.1" is $options["grouping"][0]["field"].


How to enable drag and drop picture upload into CKEditor? I would like to include the functionality of drag & drop image uploading in CKEditor of my Drupal webpage.

I have been looking for information about that but I can't find anything useful, have you ever done it? I hope you can help me.

Most drag&drop upload solutions are meant for image / file upload fields, but there is one more that integrates with CKEditor: the media module. According to its project page:

  Features: […] Drag and drop upload (requires the Plupload module).

Choose the 7.x-2.x branch, it reportedly has better drag&drop image upload capabilities. Integration of media with CKEditor happens via the wysiwyg module, so if you deploy CKEditor instead via the ckeditor or editor modules, it may not work even if overriding dependencies, because these integrations have slightly differing APIs to talk to CKEditor.


How to make method entity_uri work when $entity_type is taxonomy_vocabulary? I have a table with entities of type content, taxonomy_vocabulary and terms. For content and terms, I can show a link to each detail page by using the method entity_uri.

But for entities with type taxonomy_vocabulary this does not work, entity_uri returns null.

What is the best way to get the url for a taxonomy_vocabulary entity?

I hope it is not the best answer, because it requires customized code. But anyway, it is a possible solution and I'll share it.

/**
 * Implements hook_entity_info().
 */
function mymodule_entity_info_alter(&$info) {
  if (isset($info['taxonomy_vocabulary'])) {
    $info['taxonomy_vocabulary']['uri callback'] = 'my_module_entity_info_uri_callback';
  }
}

/**
 * Return path for taxonomy_vocabulary entities
 */
function my_module_entity_info_uri_callback($taxonomy) {
  return array(
    'path' => 'admin/structure/taxonomy/' . $taxonomy->machine_name,
  );
}


Views, Views-Slideshow, and Paging in Drupal 7 The situation is as follows:  I have a content type Slide, and I want to display the three newest slides in a slideshow.  The slides need to cycle, and the slides also need to be controllable by a pager.  The pager should have three bullets/links/images to be able to jump to a particular slide in the slideshow.  The pager should also have left and right arrows for incrementing and decrementing the the slide in the slideshow.

This technique is used ubiquitously around the web, yet I can't seem to figure out how to set this up correctly using Views and Views Slideshow.  Any pointers from all of you experienced Drupalites out there are welcome.

Cheers, Les.

(1) Required Modules (Version: Drupal7.0)

Views
Views Slideshow
Chaos tool suite
Libraries
Link Field
Token

(2) Install the Modules

In Drupal7 you can install modules from the admin section, but I still feel this new feature doesn't have any meaning, because we have to search for the module link in the Druapl site and then copy paste into the admin module installation area, really crazy. It would have been so good if they would have made it something like wordpress a small search feasture. Anyway I just gonna download and istall it in the old way (I still recommend this old way).

Download all the modules from Drupal site and install in the directory yoursitename/sites/all/modules.
Go to http://www.yoursitename.com/node#overlay=admin/modules and enable these modules as below;

(1) Views (2) Views UI (3) Views Slideshow (4) Views Slideshow: Cycle (5) Chaos tools (6) Link (7) Libraries (8) Token (Optional)
(3) Create Image Cache

In Drupal7 imagecache is part of core module and is named as Image styles. So let's create two image cache from here, one for the full size slider image and other for the thumbnail image. In this tutorial I use 935x293 (pixels) dimension for the full size slider image and 210x100 (pixels) dimension for the thumbnail image. Note: These configurations csn be defered depends on your needs.

Fullsize Slider image settings

Go to http://www.yoursitename.com/node#overlay=admin/config/media/image-styles and click on the add new style link
  (1) Give an Image style name and click on create new style button
  (2) On the next configuration screen select new style you want and then click add button (In this tutorial I choose resize style)
  (3) On the next screen set the width and height and click on the add effect button. (The settings may vary depend on the style you choose). I set width as 935 and height as 293 pixels.

Do this same process for the thumbnail image too. (for the thumbnail image dimension, I set width as 210 and height as 100 pixels.)
(4) Create New Content Type

Let's create a new content type, From the dashboard menu bar cick on Structure and then content types then click on the add new content type link.

(1) Give a human-readable name, I named it as Featured Slider (machiine name will be auto generated based on the human readable name)
  (2) Give a brief and relevant description
  (3) Submission form settings, I leave as the default settings
  (4) Publishing options, I checked only published (all other settings unchecked)
  (5) Display settings, I have unchecked the authour and date info.
  (6) Comment settings,I set hidden (disabled)
  (7) Menu settings, I leave as default settings.
  (8) Click Save and add fields Button
(5) Create New Fields

Here in this example I create only two fileds, and they are image field and link field.
We will use image field for uploading our slider image and link field for creating a custom link where we want our slider to be linked.

Image Field Settings

(1) Label: Slider Image
(2) Field: slider_image
(3) Field type: image
(4) Widget (form element): image
(5) Click Save button, and on the field settings page leave default settings and click on Save field settings button.
(6) On the image field configuration settings page you can configure as you wish.

I set this field as required, I added a file director name called slider-image so that this images will be arranged sperately from other images.
You can set the maximum upload size and resolution here, I have anabled alt and title field and finally click Save settings button.

By using same method create the link field too.

Link Field Settings
    (1) Label: Slider Link
    (2) Field: slider_link
    (3) Field type: link
    (4) Widget (form element): link
    (5) Click Save button,
For the link field configurations leave evrything to default settings.
I have re arranged the field like shown below;
 Title field
 Image field
 Link field
 Body field (you can even remove this field if not necessary)
Manage Display
On the manage display tab you can conigure how the out put of the field to be diplayed.
I have set the link field as hidden and I have also set image label as hidden
Drupal7: manage fields
(6) Create Feature Slider Content

I have created four featured slider content for this tutorial.

(1) Click on add content link
  (2) Create Featured Slider content
  (3) Give a proper title name
  (4) Upload slider image
  (5) Give alt and title field names
  (6) Give a link title and url where you want the slider to be linked
  (7) Leave all othe settings as default except for the path field if yo want you can give an SEO friendly URL alias.
  (8) Save the content.

Same way create more Featured Slider contents (I have created four contents)
(7) Create a New View

Now it's time to create our new Slideshow view.
From the Dashboard menu click on the Structure and then click on the Views.

(1) Click add new view link
  (2) Give view name, I have named as Featured Slider (machiine name will be auto generated)
  (3) Give an apropriate view description
  (4) Choose Show Content of type Featured Slider (your content type name).
  (5) Uncheck Create a Pge and check Create a block
  (6) Type in Block title and choose display format as "Slideshow" of "fields" items per page 5 (you can enter the number of items you want to display)
  (7) Click the button "Continue & edit"
Views Field Settings
First let's add link field (link must be the first field in order to work everything properly) so click on the add icon and from the filter Groups select Content
Add Content: Link, Click "Add & configure button" in the next cofiguration window uncheck "Create a label". "Check" Exclude from display.
Click "Apply button"

Next let's add image field, so click on the add icon and from the filter Groups select content
Add Content: image field (Note: make sure you choose the image field which we crerated for this slider content type only.)
Click "Add & configure button" in the next cofiguration window uncheck "Create a label".

Formatter: Image (if you have installed Colorbox or lightbox you can choose them here!)
Image Style: Fullsize (Choose the imagecache you have created in the above step)
Link image to: Nothing
Style Settings: Leave default settings
No result behaviour: Leave default settings
Rewrite Results: Check Output this field as a link
Link path: [view_node] (Note:Scroll dow a bit and you can see replacement patterns created by Core Token module, (if we didn't set the link field as first we can't see link field option here) copy only [view_node] then scroll up and paste it in the link path field.)
Click "Apply button"

Finally we need one more field for the thumbnail, so let's click on the add icon and from the filter Groups select Content
Add Content: image field (Note: make sure you choose the image field which we crerated for this slider content type only.)
Click "Add & configure button" in the next cofiguration window uncheck "Create a label" and CHECK EXCLUDE FROM DISPLAY,
Formatter: Image (if you have installed Colorbox or lightbox you can choose them here!)
Image Style: Thumbnail (Choose the imagecache you have created in the above step)
Link image to: Nothing
Style Settings: Leave default settings
No result behaviour: Leave default settings
Rewrite Results: Check Output this field as a link
Link path: [view_node] (Note:Scroll dow a bit and you can see replacement patterns created by Core Token module, (if we didn't set the link field as first we can't see link field option here) copy only [view_node] then scroll up and paste it in the link path field.)
Click "Apply button"

Views Filters Settings

In views3 the filters are created in the beginning while we choose the content type and other settings! If you need any additional filetering you can create it here!

Views Style Settings

Click on the Format Slideshow | settigs and on the next configuratioin window set as below;
  (1) List type: Unordered list
  (2) Wrapper class: Leave default settings
  (3) Style> Skin: deafult
  (4) Slides> Slideshow type: cycle
  (5) Cycle options
You need to download jQuery cycle plugin and copy jquery.cycle.all.min.js to sites/all/libraries/jquery.cycle You can find the plugin at http://malsup.com/jquery/cycle.

IN SIMPLE ENGLISH
Create a folder named "libraries" in the site/all directory and then create an another folder named "jquery.cycle" in that directory and finally copy and paste only the "jquery.cycle.all.min.js" into this directory.

(6) Transittion: Fade
  (7) Action: pause on hover
  (8) Internet Explorer Tweaks: default
  (9) Widgets: You can choose either or both Top and Bottom (I choose bottom here, and the advance settings as below;)
  (10) Bottom Widgets>Pager>Pager type: Fields
  (11) Pager field: Content: Image (Note: last one we added for the thumb, don't mistake since both field will be named same.)
  (12) Activate Slide and Pause on Pager Hove: checked, controls and slider counter leave unchecked.
  (13) Click Apply button.

Format Show Field Settings

Inline fields: Choose the thumbnail field as inline.
Click Apply button. (Note: Well it actually doesn't change much in appearance but it does change in the code. Next step use the firebug and find the class and add some styles to display properly.)

(8) Create a Custom Region (optional step)

(1) On your thems folder open the your_theme_name.info file and add a new region like this shown below;
regions[featured_slider] = Featured Slider and save the .info file.
(2) Open your themes page.tpl.php file and add these code where you want your slide to be displayed as shown below;

You can even create custom front page template like page--front.tpl.php so that you do't need to make any changes to the default page.tpl.php template.
[9] Enable & configure the Block

Now this block will be visible in the blocks disabled area, so from the Dashboard menu go to Structure>Block and enable the block to a themes default region  or the custom region we created (featured_slider). (Regions varies depends on the theme you are using.)

Block Configuration Settings
After enabling the block you get a link to configure the block so click on the Configure link and on the settings section set as below;

(1) Block title (if you don't want blobk title to be displayed just type )
  (2) Again you get all enabled theme specific Region settings.
  On visibility setings
  (3) Pages>Show block on specific page: choose Only the listed pages and type  so that this block will be displayed only on the front page.
CSS TIPS TO DISPLAY THUMBNAILS INLINE

Add these CSS codes to your themes style sheet to display the thumbnails inline.
.views-slideshow-controls-bottom .views-slideshow-pager-field-item { float: left; margin: 20px 6px; } Make necessary adjustments.


Filter Node Reference options I'm trying to set up the content types for a site and ran into a bit of a problem.
Let's say I have a content type called Employee, and a list of taxonomy terms that holds function names.
Each employee is linked to a function so to say using a Term Reference to one of the available function. Like this each employee is either a mananger, a desk employee, or a janitor etc.

In a second content type, I wish to add a node reference to these Employee nodes, but I wish to have the option of only selecting the nodes linked to a certain term, such as manager. As such, when creating a new node of this second content type I should only be able to select managers in my overview.

Is there any way of filtering your available options like this? I saw some other questions mentioning the References module, but these questions didn't have an answer.

I hope someone can shed some light on this for me.

Using Entity Reference Module you can set up a view that pulls in a list of entities and then use that view to select the nodes. Steps:

Create a view of employees
Add a contextual filter to the view for has term reference
Save view.
Add entity reference filed and select use view to show results.

Hope that helps


Is there a module to hide URL path settings by content type? Eg. I'd like to let the client see the URL path settings fieldset for Page but not for Slide.

I'm happy to implement it myself, just wondered if someone else already had.

I don't believe there is anything out there at the moment (perhaps my search wasn't extensive enough either), but you can hide the URL path settings fieldset yourself easily with one line of code:

<?php $form['path']['#access'] = FALSE; ?>


Automate creation of taxonomy terms for use with migration module How do i script the creation of my taxonomy terms - do people normally do this with features?

depends when you want to create them, in a new site or importing them into an existing one?

If you're building an install profile you could write an install script to create the taxonomy and terms as you need.

If you're trying to export/import into existing sites then it might be a bit harder.

features can't export taxonomy terms by itself because they have sequential ID values and so don't have a UUID that can be safely ported across sites.

that said, there are other modules out there helping to fix that problem - http://drupal.org/project/uuid is somewhere to start your research. Fair warning, you might have test a few patches for existing modules to get the solution you're after..


How to change Drupal's default language programmatically? I am trying to change the Drupal's default language programmatically  but haven't found the codes/function. Any suggestions?

Here is a corrected and tested version of the code posted by @Clive in a comment to the OP:

$langs = language_list(); // Note: No argument
// debug($langs, '$langs');
$langcode = 'en';
variable_set('language_default', $langs[$langcode]);

The code snippet above assumes that the two-character code that you assign to $langcode is enabled.  Uncomment the call to debug to see the languages that are enabled on your site and what array indices they use.

Note that the setting will not take effect until the next page load.


How to get vocabularies for an entity reference to a taxonomy? So I'm having a bit of a difficult time finding out how to get the information I want.

I have an entity reference field - call it field_event_type. This is an entity reference to a taxonomy. I am trying to programmatically get the possible vocabularies associated with this entity reference and get the fields/properties associated with them. Basically walking each of the bundles to get their relevant information.

So far I can get the field definition on the parent node, which looks like this:

Array
(
    [uuid] => 32eeda5f-270f-477d-b24c-75ed15e69b2a
    [langcode] => en
    [status] => 1
    [dependencies] => Array
        (
            [module] => Array
                (
                    [0] => node
                    [1] => taxonomy
                )

        )

    [id] => node.field_event_type
    [field_name] => field_event_type
    [entity_type] => node
    [type] => entity_reference
    [settings] => Array
        (
            [target_type] => taxonomy_term
        )

    [module] => core
    [locked] =>
    [cardinality] => 1
    [translatable] => 1
    [indexes] => Array
        (
        )

    [persist_with_no_fields] =>
    [custom_storage] =>
)

By doing this:

\Drupal::config('field.storage.node.field_event_type')->get();

Based on this link:

field_info_field() deprecated, what's the equivalent?

But I'm not sure how to get the vocabularies or even if that's the right thing to do to get the information I want.

How would I go about getting the vocabularies? I should be able to just load by VID and get the correct fields at that point, correct?

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

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

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

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

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

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

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

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


Create node display custom tab I'm trying to create tab in node display that links to node delete form. I used hook_menu_local_tasks_alter in template.php

function mytheme_menu_local_tasks_alter(&$data, $router_item, $root_path) {
// Add a tab linking to node/add to all pages.
$data ['tabs'][0]['output'][] = array(
'#theme' => 'menu_local_task',
'#link' => array(
    'title' => t('Delete'),
    'tab_parent' => 'node/%',
    'tab_root' => 'node/%',
    'tab_root_href' => 'node/'.arg(1),
    'tab_parent_href' => 'node/'.arg(1),
    'href' => 'node/'.arg(1).'/delete',
    'access callback' => 'node_access',
    'access arguments' => array('delete', 1),
    'localized_options' => array(
    'attributes' => array(
     'title' => t('Delete'),
    ),
  ),
),

);

}

Tab is created but it is displayed for every user and on every page where tabs are enabled. How can I configure access arguments to display tab only on node display page and only for user with permissions [Content type]: delete own content?

This will be done by hook_menu, See the example below for creating tabs (MENU_LOCAL_TASK). This is how tabs will be created.

    // For the default local task, we need very little configuration, as the
  // callback and other conditions are handled by the parent callback.
  $items['examples/menu_example/tabs/default'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'Default primary tab',
    'weight' => 1,
  );
  // Now add the rest of the tab entries.
  foreach (array(
    t('second') => 2,
    t('third') => 3,
    t('fourth') => 4,
  ) as $tabname => $weight) {
    $items["examples/menu_example/tabs/$tabname"] = array(
      'type' => MENU_LOCAL_TASK,
      'title' => $tabname,
      'page callback' => '_menu_example_menu_page',
      'page arguments' => array(t('This is the tab "@tabname" in the "basic tabs" example', array('@tabname' => $tabname))),
      'access callback' => TRUE,

      // The weight property overrides the default alphabetic ordering of menu
      // entries, allowing us to get our tabs in the order we want.
      'weight' => $weight,
    );


How do I test the methods or hooks implemented in .module file using PHPUnit? PHPUnit testing in Drupal 8 works for functionality which are written in class files.

How do I test the methods or hooks implemented in a .module file using PHPUnit in Drupal 8?

No, PHPUnit is not for testing functionalities written in class files. Quite the opposite, PHPUnit in Drupal can be used to test hooks, functions, and classes implemented from modules.
Drupal core itself has tests for hooks, for example the InfoAlterTest class that tests hook_system_info_alter().

How to write tests is described in Automated tests. Without a specific use-case, I cannot give more details on testing hooks, except saying that functional tests that do not test web output, which is the case for most of the hook tests, the test class needs to extend \Drupal\KernelTests\KernelTestBase.

References

Types of tests in Drupal 8
An Overview of Testing in Drupal 8


'Edit' tab does not appear on user's account page? On my site when a user navigates to their account page there is no 'Edit' button for them to be able to edit their details. From the documentation online it seems this should appear automatically.

Is there any way this could have been disabled by accident or are there any modules that could have interfered with it?

A user is able to edit their profile if they add /edit to the link to their profile page, so it is not that they don't have the 'edit' permission - they definitely do and are able to edit their details successfully if they go to this link.

Oceanescence, some times people have disabled or moved the tabs block. If you are using a custom theme try switching to Bartik and see if it pops up.

If not try digging into the permissions. Just log in as Admin 1 and see if the tabs show up.


Abandoned webform log I'm building a huge form with Webform module and need advice for a way to save not fully submitted forms even without Showing "Save draft" button options is enabled and button is visible (which is another PITA).

You'll need to write a custom module that calls an AJAX function after each field of the Webform has been changed that fires the same function that the Save draft button does.

Shouldn't be too complicated, there is a starting point at Use AJAX to auto save a draft which should hopefully push you in the right direction, plus Webform Ajax might also help


Modal Dialog not Opening when not authenticated or in incognito mode Hi i am using Drupal 8 to render a modal popup on clicking a link. However when i am connected as admin the popup render well but as soon as i logout or choose to be incognito mode of the browser the popup does not appear and the page is redirected to link set in the href tag. Here is my link :

SOME TEXT IN MODAL

Can anyone explain to me why this is so? I can't figure out why when i am connected the modal render well but when not connected it redirect me to the node.

Ajay is correct, the javascript dependencies wont load by default for anonymous users. Here's what I added to my theme.libraries.yml to get it working:

dependencies:
  - core/jquery
  - core/drupal.dialog.ajax


Hiding a filter in a view with same filter in contextual filters I've a simple problem. In Views I've city filter(exposed) set that'll show jobs in a city. Now I've set the same City in contextual filters as well with the condition to show all values when no argument is supplied. So this view is "General Advanced Job Search"

Now I want to offer "Jobs in Citi1", "Jobs in Citi2". But I want to reuse the same View without duplicating it. I'd call it "Advanced Job Search given a city".

So I can pass the arguments as Citi1 etc and it'd show Jobs in Citi1 at the same time it'll show City filter as drop down in Filter Criteria. I want to hide this City in Filter criteria as it is of no use as cities are already being limited by the argument passed(Citi1).

I've tried searching here and there but nothing found.

In short if argument is passed to a view I want to hide an exposed field show in filter criteria.

The following code will help you to solve your issue.

/**
 * Implement hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'views_exposed_form') {
    if($form['#id'] == 'views-exposed-form-myview-page') {
       // argument 1 represent city1
      if(arg(1)) {
        // hide city field
        unset($form['#info']['filter-jobs_in_city']);
        hide($form['jobs_in_city']);
      }
    }
  }
}

Notes:

Replace form id views-exposed-form-myview-page with your own form id
Replace argument 1 with the right City1 argument index
Replace jobs_in_city field name with your own city field


How can I download files from public folder? I want to provide download link to the users to download the files which are present in the public folder. How can I achieve that, I tried below but not worked.

if ($handle = opendir(variable_get('file_public_path', conf_path(). '/files/') .'/xmluploads/Sainath')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $file = basename($_GET[$entry]);//$file consists caste certificate.pdf
            $file = variable_get('file_public_path', conf_path(). '/files/') .'/xmluploads/Sainath'.$file;
            if(!$file){ // file does not exist
                die('file not found');
            } else {
                header("Cache-Control: public");
                header("Content-Description: File Transfer");
                header("Content-Disposition: attachment; filename=$file");
                header("Content-Type: application/zip");
                header("Content-Transfer-Encoding: binary");

                // read the file from disk
                readfile($file);
            }
        }
    }
    closedir($handle);
}

This error I am getting:

Notice: Undefined index: caste certi.pdf in file_upload_download() (line 194 of C:\xampp\htdocs\academy\sites\all\modules\custom\file_upload\file_upload.module).
Warning: readfile(sites/default/files/xmluploads/Sainath): failed to open stream: Permission denied in file_upload_download() (line 206 of C:\xampp\htdocs\academy\sites\all\modules\custom\file_upload\file_upload.module).

Please help regarding this, Thanks in advance..

I think just giving a link to the file itself will download the file. In case of an image or PDF file, won't opening the file in new tab from where they can download suffice for you?

Regards,
Supriya Rajgopal


EntityFieldQuery for retrieve only 1 field I'm developing a new rules action that it is called by EntityForm when a Form is submitted.

In this action I want to retrieve 1 field from "noleggiatori" content type, so this is my function:

function zbl_rules_send_email_to_noleggiatori($entityForm) {

  $prov = $entityForm->field_provincia[LANGUAGE_NONE][0]['tid'];
  $reg = $entityForm->field_regione[LANGUAGE_NONE][0]['tid'];

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'noleggiatori')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_provincia', 'tid', $prov, '=')
        ->fieldCondition('field_regione', 'tid', $reg, '=')
        ->addMetaData('account', user_load(1)); // Run the query as user 1.

  $result = $query->execute();
  dd($result);

  $articles = $result['node'];
  $fields = field_info_instances('node', 'noleggiatori');
  $field_id = $fields['field_email_per_comunicazoini']['field_id'];
  field_attach_load('node', $articles, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
  dd("articles");
  dd($articles);

  /* Other lines .... */
}

But I have a problem: the code is correct (no error), but it does not work correctly because it set ALL content type's fields in $articles. I want only "field_email_per_comunicazioni". Is this possible? How?

The code looks correct. Note that according to the field_attach_load() documentation:

  The field ID that should be loaded, instead of loading all fields, for each entity. Note that returned entities may contain data for other fields, for example if they are read from a cache.

So having other fields than field_email_per_comunicazioni does not mean the code does not work properly.


using {{ twig variables }} inside external jquery Developing a D8 theme, I am loading an external .js file containing some jQuery code (so it is not inside the TWIG template).

Is it possible to access and modify TWIG variables like {{ myvariable }} inside the external jQuery?

It's not possible to access Twig variables in jQuery directly. Instead access the content of PHP variables inside of an external jQuery code by attaching them to drupalSettings. See the documentation:

  Attaching configurable JavaScript

  In some cases, you may want to add JavaScript to a page that depends
  on some computed PHP information.

  In this case, create a JavaScript file, define and attach a library
  just like before, but also attach JavaScript settings and have that
  JavaScript file read those settings, via drupalSettings (the successor
  to Drupal 7's Drupal.settings). However, to make drupalSettings
  available to our JavaScript file, we have to do the same work as we
  had to do to make jQuery available: we have to declare a dependency on
  it.

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

  and

$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

  Where 'bar' is some calculated value.

  Then cuddly-slider.js will be able to access

  drupalSettings.fluffiness.cuddlySlider.foo (and it will === 'bar').

https://www.drupal.org/developing/api/8/assets


Using CSS Sprites with Drupal I ran a Page Speed review of my website and got a suggestion that I should combine some images on my site into a single image using CSS sprites. I assume it is the mistake of the person who coded the theme, and I cannot recode it due to lack of knowledge. Is there any easier way of achieving this in Drupal? What I am looking for is solutions like this and this that would make the process easy for Drupal 7.

Drupal's primary role is a CMS. For development tooling, it's probably more effective and more efficient if you build sprites without the use of Drupal. Drupal itself already has a very large memory footprint.

How to produce CSS sprites (2013/2014 Edition)

With today's rapid growth in development tooling and technology, here are just some ways of which one can produce sprites for your theme today:

Manually Manually edit them in photoshop and place them accordingly in the same file and write css for it. If this isn't clear to you. There's a plethora of information on how to do this: here, here, here, and yes there's plenty of more articles out there. Just search for "css sprites" in your favorite search engine.
Use Compass Compass, a Ruby Gem, allows one to automatically generate sprites. It's very well used and integrated in some themes today. For example, Zurb Foundation.
Grunt Spritesmith If you're familiar with using Grunt and have node already setup on your local machine Spritesmith is a viable option. Spritesmith allows you to create sprites within a folder for use of your theme.
CSS Sprite Generator - I quickly googled 'css sprite generator' and found this particular tool. Not sure if it's helpful but it seems as to allow you to build sprites online via upload.

Again, IMHO i'm pretty skeptical and think that outdated Drupal 5 sprite module will improve your front performance when you have to load one more module.


Reorder the Basic page list in views .How? I have created views to display basic pages in blocks.I what to reorder the list according to me .How to do?Plz help......

In Drupal 7 you use VIEWS SORT CRITERIA

If you want to sort based of Content: Post date OR Content: Updated date just use these fields in VIEWS SORT CRITERIA.
If you want to sort based on your requirement then, just add one more extra field to basic page like weight.

Edit your VIEW and just add this field in the Views SORT CRITERIA and sort is as per
your requirement.


What's the best practice to show a node's fields in different regions? In D7 we used to create a view for nodes, with each field having an own display. Each display creates a block to place in any region of the site. But of course, Views are SQL-heavy.

Now, Drupal 8 is all fancy. What's the Drupal 8 way of showing a node's fields in different regions of the page?

Edit: my current attempt is to create a custom module which provides a block for each specified field.

Not exactly sure why you want to have every single field as a separate block? That's pretty inefficient, if nothing else.

To have one or two additional blocks, you can use an Entity view block provided by ctools module. It will take the current node and display it in a certain view mode. Of course that will be painful to maintain if every field is separate, but I don't really see why you would want to do that?


Create colorbox link programmatically Hello fellow druaplistas!

I have a situation where I need to output an image field using different image styles depending on some checkbox settings.

I'm doing this inside a node template. Basically this goes like this:

if ($layout == 1) {
  print $small_image;
}
if ($layout == 2 {
  print $medium_image;
}

To get the url to the correct sized image I can use image_style_url, but this way I have to build the links to the bigger version to open inside colorbox manually.
Is there some function available that I can pass two image styles and it uses them to generate an image tag wrapped with a link to the bigger sized image?

Update:
I took Clive's code (thanks again) and added a second parameter to be able to choose the preset that will be shown inside the colobox. Also Title and Alt is now included:
As your code was better than mine I took it and extended the stuff I needed, maybe it's of use for someone:

function _colorbox_link($image, $style_name, $style_name_link = 'colorbox_full') {
  $image_style = theme('image_style', array(
    'style_name' => $style_name,
    'path'       => $image['uri'],
    'alt'        => $image['alt'],
    'title'      => $image['title']
  ));

  $url = image_style_url($style_name_link, $image['uri']);

  $link = l($image_style, $url, array(
    'html' => TRUE,
    'attributes' => array(
      'rel' => array('colorbox-gallery'),
      'class' => array('colorbox')
    )
   ));
  return $link;
}

I don't think there is, weirdly enough I've just been looking for pretty much the same thing...I couldn't find one so I just wrote a helper function:

function _lightbox_link($image, $style_name) {
  $image_style = theme('image_style', array(
    'style_name' => $style_name,
    'path' => $image['uri'],
    'alt' => $image['alt']
  ));

  $url = image_style_url($style_name, $image['uri']);

  $link = l($image_style, $url, array(
    'html' => TRUE,
    'attributes' => array(
      'rel' => array('lightbox-gallery')
    )
  ));

  return $link;
}