Do I need to sanitize a user input textfield used in a mail body? I have a feature on my site where a user is allowed to edit a textfield is a Drupal form (built using the D7 Form API) and then send the contents of that textfield as (part of) the body of an email to another user.  I use drupal_mail to send the mail.

The textfield is saved in the database, and I rely on the Form API to protect against SQL injection.  The textfield is never rendered on the screen outside the textfield widget, so "dangerous" HTML tags and PHP/JavaScript injection is not a concern (I hope).

I use DefaultMailSystem as mail backend.

Given that the user can type anything in this textfield, is there any need to sanitize this user input before it is included in the email body and sent?

There are two reasons to use Drupal's text filtering system: security and proper formatting of the information for the context.

In reverse order:

For formatting: if you use something like the markdown filter or limit with html tags can be used for simple sanity (i.e. no h1) then you want to use a filter that removes that.
For security: you want to remove malicious code if it is being displayed in an environment where that matters. In the case of email, the relevant DOM is the email client which can sometimes be a domain. However, if it is a security weakness to that email user to get javascript...that is a problem with their client. Since anyone can send any email to any address with any (malformed) contents it is not a major consideration of e-mail processing to ensure the body is "safe" (without scripts). See this discussion on g.d.o/security about sanitizing text in email bodies

That said, you don't want your system to be useful for spam.

Consider using the flood_control system.
Consider adding an introduction and closure to your email message to make it less useful for a spammer. For example "This email was sent from example.com. Your friend said: _stuff_here_. If you have questions contact your friend and not example.com"

There is more to e-mail than the body, of course. E-mail headers can be a vector for attacks, since someone can use a newline as part of the "to" address and then append new headers to send as many mails as they want to whomever they want, pretending to be from whoever they want, hurting your domain's reputation in the process.

One other side-note:

  The textfield is saved in the database, and I rely on the Form API to
  protect against SQL injection.

SQL Injection protection should come from proper use of methods and arguments in your db_insert or db_query function. It does not come from the Form API.


How can add Thumbnail image in Drupal 7 site? I have set an image style as a thumbnail, but it doesn't render as my thumbnail style.  Instead, it is showing the original size of image.  How can I solve this problem.

You can edit the content type and configure in the manage display fields. Go to admin/structure/types/manage/article/display considering article is a content type.Replace 'article' with what every node type you have and change the image fields display options as shown in the screen shot.


hook_form_alter() exposed filter form item #weight I'm trying to insert a form element with hook_form_alter(), and then rearrange the form elements so that the new form item appears at a particular point amongst the existing exposed filters.

I've tried adding #weight of 0 to all existing items and then #weight of -1 to the new element, just to see if I can have any influence on the form item order at all, however I don't seem to be able to affect it.

EDIT: In addition I'm getting kinda weird behaviour regarding the container of the Form element. I'm adding my form element as a new array element at the root of $form, however it is be rendered inside the element <div class="views-exposed-widget views-submit-button"> rather than getting it's own container, which seems like either a bug or I really am doing something wrong!

Take a look at comments #3, #7 and #9  in http://drupal.org/node/893392

#3 (dereine):

  The problem is that there is some theming on exposed form. You would have to override it, sadly.

#7 (manatwo):

  Yes, all of it is handled in views-exposed-form.tpl.php, which you can override in your theme to print out your fields manually. IIRC, the extra fields are gonna be in the $button variable in that template, so you might want to do some preprocessing in template.php

#9 (PadreHomer):

  I was able to alter the order without overriding the template. I am using Views 3, but I think this will work in Views 2 as well.

  Alter the order of the filters in $form['#info'] in your form_alter and this should alter the order the widgets print out in the template without having to do any custom templating.


How to create a custom menu in Drupal 7? I need to create custom menu in Drupal 7. I don't need to add links on Main menu, but instead I need to create new menu with new menu links.

How can I do so?

Step 1: Create the menu

Navigate to admin/structure/menu/add in your site and add the menu you want. Add at least the "Title" of the menu (like Custom menu), save it, and it will show up in admin/structure/menu also. From there you can start to add menu items (which will be the "new links" you are looking for).

Step 2: Make the menu visible

Head over to admin/structure/block to indicate in which region of your theme you want that newly added menu (Custom menu) to be shown.

Step 3: Clear the cache

And don't forget to clear the cache (since you're changing things that are cache sensitive ...). I think "menu" cache should be sufficient, but to be sure I usually just clear all caches ...


Custom #ajax "Add another" button only adds 1 This form consists of 1 textfield, and 1 ajax button.

I'm trying to make it add another text field with each click.

It works for the first one, to get a total of 2 text fields. I cannot get more than 2 to appear though.

I suspect the dom is being updated, but not the form. So the subsequent callbacks add an element based on the original form build.

I'm not sure how to approach this in Drupal 8. Any insight would be appreciated.

Here is my form control

<?php
...
class MyModuleForm extends FormBase {
  ...
  public function buildForm(array $form, array &$form_state) {
    $form['foo'] = array(
      '#type' => 'container',
      '#tree' => TRUE,
      '#prefix' => '
',
      '#suffix' => '
'
    );
    $form['foo'][0] = array(
      '#type' => 'textfield'
    );
    $form['add'] = array(
      '#type' => 'submit',
      '#name' => 'add',
      '#value' => t('Add'),
      '#ajax' => array(
        'callback' => array($this, 'addMore'),
        'wrapper' => 'foo-replace',
        'effect' => 'fade',
      ),
    );
    return $form;
  }

  public function addMore(array $form, array &$form_state) {
    $form['foo'][] = array(
      '#type' => 'textfield'
    );
    return $form['foo'];
  }
}

You made a common mistake. In Form API, ['#ajax']['callback'] has only 2 purposes:

Make one-time changes to form, that are not meant to persist form reload, submit or second Ajax request. Good example is adding some classes to freshly modified element.
Return proper part of the form.

To have persistent changes, you need to keep the number of elements you want somewhere, for example in $form_state, and add them in form builder function, buildForm in your case.

My approach would be to check $form_state['triggering_element'] to see if it was your Ajax button to invoke form building, and if so, increase counter. Then simply for($i = 0; $i < $element_counter; ++$i) to add required number of elements.


Why is this block found but not installed? I have a custom block that is found by "Place Block" but does not actually get placed. The spinny just spins for second and then nothing happens; the screen just stays at the list of available blocks.

Is there any method within Drupal 8 to see what the error is?
What incompatibilities might be causing this?

Setup Notes

Drupal 8.1
Lots of cache refreshing attempts
Lots of uninstall/reinstall attempts
Same behavior on a fresh D8 install
The module does install and the controller works at its prescribed URL
The base directory of the module is nrs_raceroftheday

This is the content of ROTDBlock.php.

/**
 * @file
 * Contains \Drupal\nrs_raceroftheday\Plugin\Block\ROTDBlock.
 */

namespace Drupal\nrs_raceroftheday\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Racer Of the Day' Block
 *
 * @Block(
 *   id = "rotd_block",
 *   admin_label = @Translation("RacerOTD v4 block"),
 *   )
 */
class ROTDBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build()
    {
    $pageContent='asdf';
    return array('#markup' => $this->t($pageContent),  );
  }
}

Here's the routing file nrs_raceroftheday.routing.yml.

nrs_raceroftheday.controller:
  path: '/racer-of-the-day'
  defaults:
    _controller: 'Drupal\nrs_raceroftheday\Controller\NrsRacerOfTheDayController::content'
    _title: 'Racer of the Day'
  requirements:
    _permission: 'access content'

In general, that can have many possible causes. But it's very likely some sort of syntax or other error that leads to an exception or a fatal error.

Open the Place block link in a new tab to see the response, check the network tab and/or check your apache or drupal logs.

That should give you a hint about the problem. In this specific example, it was a trailing space after the closing PHP tag, as suggested by @kiamlaluno, that's why Drupal coding standard says that they should be left out.


How can the author choose when to publish an article, whether the article gets a teaser or not? Is there a possibility for the author/editor to decide - when publishing - whether the article (the content type) gets a teaser or not?
This is important for the look of the article on the front page.

I thought so far that would have to be defined before in the content Type.

If I understand your question, then this can be done by checking the Promoted to Frontpage box on the article.

You can then change your view to filter out nodes that have Promoted to Frontpage checked.


Disable plugin ckeditor per content type I am using the ckeditor module.
I have 2 content types.
Both content types use the same ckeditor profile on their body field.

Is it possible, without creating another profile, to disable a certain plugin (e.g. image plugin) on that ckeditor profile for only one content type?

You need create different "body field" in one of your content type.
I.e. For first content type use the same "body field" and use first ckeditor profile.
For next content type create a new "body field" - like a "content_type_name_body" and use last ckeditor profile.


Easiest way to make body of text wrap around image I would like to have a body text wrap around the the image below. Here is an example:

http://www.fareham.ac.uk/events/2011/06/creative-arts-summer-exhibition

And here's an excerpt of the code:

        Fri 24 Jun 2011

    Don't miss your chance to see the incredible artwork produced by this year's Creative Arts students at Fareham College.

    The exhibition will be held on the College campus, featuring work from our Art, Graphic Design, Photography, Fashion and Media students.

    This event runs on weekdays from 10am–4pm on 24th June–1th July 2011 in both the A-Block and the Function Room at Fareham College.

    We look forward to seeing you.

How can I get the  with the text in to wrap around the  with image in?

Thank you.

Put the field before the text and apply a float class to the field.

.field-field-event-image {
float: left;
}


'invalid render array key' error when using an associated array for a twig variable I have a list of images, and I want access to both the direct path to the image, and the path with an image style applied to it available to a twig template.
I'm grabbing the images in my .theme file like so.

$images = $node->get('field_image');

foreach($images as $image){
    $image_style =Drupal\image\Entity\ImageStyle::load('photos')->buildUrl($image->entity->getFileuri()),
    $image_path = file_create_url($image->entity->getFileuri()),
}

I want to be able to access these attributes for each image by storing them in the $variables array.

I attempted to do so by using

foreach($images as $image){
    $image_style =Drupal\image\Entity\ImageStyle::load('photos')->buildUrl($image->entity->getFileuri()),
    $image_path = file_create_url($image->entity->getFileuri()),
    $variables['photos'][]['image_style'] = $image_style;
    $variables['photos'][]['image_path'] = $image_path;
}

However that didn't work and I received errors. After that I figured that maybe I needed to supply a more explicit associative array so I tried

    $variables['photos'] = array();
    $photo_paths = array();
    foreach($images as $image){
        $photo_paths += [
            $i => [
                'image_style' => Drupal\image\Entity\ImageStyle::load('photos')->buildUrl($image->entity->getFileuri()),
                'image_path' => file_create_url($image->entity->getFileuri()),
            ],
        ];

        $i += 1;
    }
    $variables['photos']= $photo_paths;

But then I receive the error

  User error: "image_style" is an invalid render array key in
  Drupal\Core\Render\Element::children() (line 97 of
  core/lib/Drupal/Core/Render/Element.php).

and

  User error: "image_path" is an invalid render array key in
  Drupal\Core\Render\Element::children() (line 97 of
  core/lib/Drupal/Core/Render/Element.php).

These errors continue for each image. I'm guessing that $variables can't handle nested associative arrays? Is there a way I can use an associative array inside a twig variable? Or is there another way to accomplish the same task or storing the path and image style for each individual image to be displayed in a for loop in twig?

Twig doesn't understand what you put in the keys image_style and image_path. Twig can handle only arrays when the children are renderable. And this means, they have to contain a '#type' or '#theme' key with a valid render element or theme name. For image styles use the theme image_style:

$variables['photos'] = [];
foreach ($images as $image) {
  $variables['photos'][] = [
    '#theme' => 'image_style',
    '#style_name' => 'photos',
    '#uri' => $image->entity->getFileUri(),
  ];
}

Then Twig can render the images like their are supposed to be rendered without the need for custom php code.


How do I get a new database connection with a new setting? I want to set the GLOBAL variable innodb_flush_log_at_trx_commit, and then run a migration after getting a new connection since changes to a global variable does not affect the current session.

So the raw mysql would go like this...

-- set the variable that speeds my migrate up by 40x
SET GLOBAL innodb_flush_log_at_trx_commit=0;
-- reconnect (starts a new mysql db session)
connect;

-- Do the import

-- at the end of the import
SET GLOBAL innodb_flush_log_at_trx_commit=1;
connect;

I've not tried anything yet, but I'm interested to see if anyone else has looked at this, and the issues encountered, and the end solution.

I like your gutsy move in this regard.
I wrote about changing innodb_flush_log_at_trx_commit in the DBA StackExchange

Feb 10, 2012 : Is it safe to use innodb_flush_log_at_trx_commit = 2
Mar 08, 2012 : What are some key configuration settings for using an InnoDb table for session storage?
Dec 07, 2012 : Dynamic change to innodb_flush_log_at_trx_commit

I also wrote about tuning InnoDB for better INSERT performance

Jul 04, 2012 : Capabilities of InnoDB INSERT Performance

EPILOGUE
You have the right idea. You should experiment with this on a Staging DB Server (load data, test drive the setting, kick the tires)
Note the difference between setting innodb_flush_log_at_trx_commit to 0 and 2

Setting to 0 : any mysqld process crash can erase the last second of transactions. The log buffer is written out to the log file once per second and the flush to disk operation is performed on the log file, but no writes are done at a transaction commit.
Setting to 2 : only an operating system crash or a power outage can erase the last second of transactions. The log buffer is written out to the file at each commit, but the flush to disk operation is not performed on it. Before MySQL 5.6.6, the flushing on the log file takes place once per second. Note that the once-per-second flushing is not 100% guaranteed to happen every second, due to process scheduling issues. As of MySQL 5.6.6, flushing frequency is is controlled by innodb_flush_log_at_timeout instead.

Based on this difference, you have to decide who do you trust flushing data, the Operating System or the mysqld process. Using 0 leans in favor of mysqld. Using 2 seems to be OS oriented.


Why isn't there a "node" table? After installing Drupal 7, the site seems to run fine, however looking in phpMyAdmin I don't see a "node" table. According to this image, used from the documentation on Drupal.org, it should have that table.

When I try to run various SQL queries that mention the "node" table they fail. However the Views module shows Drupal apparently internally able to query against the "node" table.
Also, using a raw SQL module I am able to write SQL against node.title, for example. However, it fails from phpMyAdmin.

I notice that Drupal 8 installations on the same server seem to have a node table. If it's relevant, these were all installed with Softaculous on Arvixe.

What is going on here?

Yes, drupal 7 does have a node table. The reason why your database does not might be either because you are looking at the wrong database or perhaps because your configuration are using a database prefix. Look in your sites/default/settings.php file and check if you are using a prefix. For example:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'host' => 'localhost',
  'database' => 'example',
  'username' => 'user',
  'password' => 'password',
  'prefix' => 'd7_',
);

or

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'host' => 'localhost',
  'database' => 'example',
  'username' => 'user',
  'password' => 'password',
  'prefix' => array(
    'node' => 'd7_',
  )
);

The first example would prefix all tables in the database with d7_, while the second would only change the name of the node table.


How to import multiple terms from XML into a node? I am trying to import all the Destinations as taxonomy terms using following XML. In my situation, the list is not a comma separated list. It is as follows:

<product>
    <category>Ship</category>
    <id>000032</id>
    <Description>The description comes here</Description>
    <list>
        <Destination>
            <DestinationName>Dest 1</DestinationName>
            <DestinationCountryISOAlpha3>US</DestinationCountryISOAlpha3>
        </Destination>
        <Destination>
            <DestinationName>Dest 2</DestinationName>
            <DestinationCountryISOAlpha3/>
        </Destination>
    <list>
</product>

I have a taxonomy called destinations and the list is already imported. Now how can I import Destinations list of a product as a term reference for the product node. I am using feed module, Feeds XPath Parser, and Feeds Tamper modules?

I finally found a way to achieve this goal at least for my use case. Publish my solution here for anyone to use if required.

My Settings for XPath XML parser :

Context -> //product/list/Destination
Product id -> ../../id
List of ports -> DestinationName # This is a term reference field which well have multiple terms per product

Then mapped all required fields as normal.

I created a small module with hook_feeds_after_parse() hook (I will use "My module").

My module has one .info file and the .module file.

function my_module_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
    $current_id = -1;
    $cuurent_destination_list_final = '';
    foreach($result->items as $key => $row) {
        if($current_id !== $row['xpathparser:0']){
            $cuurent_destination_list_final = '';
            $current_id = $row['xpathparser:0'];
        }
        if($cuurent_destination_list_final === ''){
            $cuurent_destination_list_final = $row['xpathparser:1'];
        }else{
            $cuurent_destination_list_final = $cuurent_destination_list_final . ',' . $row['xpathparser:1'];
        }
        $result->items[$key]['destination_list_final'] = $cuurent_destination_list_final;
    }
}

What this module does is it creates a comma separated list of destinations.
Once we set $result->items[$key]['destination_list_final'] (This builds a comma separated list of terms) using this module, we can refer destination_list_final from Feeds Tamper (Refer this).

Install and enable Feeds Tamper PHP.
Add 3 pluggings to xpathparser:1 -> List of Destinations

Execute php code (This come from above installed module) -> return     $item['destination_list_final'];
Find replace - Use to remove double quotes (")
Explode - Use to explode the comma separated list we created from the custom module.

That's it. It worked for me.


How to create reviews for user comments? I want use user review for my content. For example they can send their comment in my content and review in comment ( with fivestar field ).

Five star and other module not work in drupal 8.

The scenario is not very encouraging for Drupal 8 in voting modules at this time, but you can check some modules that can help you:

Votingapi Widgets

  A flexible field based Voting System based on
  https://www.drupal.org/project/votingapi .

Like Button

  Add a Like button to Drupal content and comments! Get instant
  statistics and insights! Sort content by likes!

Star Rating

  Star Rating is a simple module that provides star rating field and
  display formatter using Drupal 7's Field Type API.


How do I programmatically install a module? For Drupal 7, I found How do I programmatically install and enable a module?

What is the equivalent code for Drupal 8?

UPD: here Configuration Manager or hook_update() to enable modules I found the case when you can use the code during deployments, specially when your module has updates in own dependencies.

Use "module_installer" service.

$installer = \Drupal::service('module_installer');
// Or from the container.
$installer = $container->get('module_installer');

// Install single module.
$installer->install(['module_name']);
// Install multiple modules.
$installer->install(['module_name_1','module_name_2']);

Also for uninstallation of the module use the next example:

$installer->uninstall(['module_name']);


Alternative to field_attach_update In Drupal 7 we were able to use field_attach_update($entity_type, $entity) to update fields without having the need to update the whole node. $node->save() is very heavy and calls many hooks in between.

With the coming of Drupal 8, field_attach_update was deprecated. Is there an alternative to it, and what is it if yes?

In my case I'm updating two image fields programatically and don't want to call $node->save in order to not trigger all the other hooks.

There is no alternative, saving an entity is the only supported API.

Saving will only update the configurable field tables if it detects a change, and we plan to implement similar logic for the base tables as well.

But the hooks are still called and there is no supported way to prevent that.


How to disallow commerce checkout if no payment method is available? With Drupal Commerce and Commerce Payment, when no payment method is available on the checkout, it displays this message: Payment is not required to complete your order. and the customer is still able to finish the checkout.

It's probably trivial, but I can't find a solution that doesn't involve calling a hook in a custom module.

The best solution would to actually display a webform when no payment method is available.

The core payment module offers this option in the checkout pane's settings form.


Multilingual search problem I have a site which is setup with 2 languages. Primary language is English.
If I do a search in English then I can find all content and get search results. When searching in the second language I only get results if the search term is present in content in both languages.

So if Node23 has the word "plant" in both English and the translation in the 2nd language too then I will have a search result in the 2nd language. Result shown is in the 2nd language.

If node23 contains the word "plant" only in the 2nd language then I get no results.
What can I do to fix this issue? Looks like indexing only takes place on the primary language and when found it is displayed in the second language.

I tried built in search, Display suite search and Search configuration module.
Very strange behavior if you can build a multilingual site but can not search.

I do not as yet have significant experience with internationalisation in drupal.

Having said that, if you would like greater control over your search indexes I would definitely look at using search api instead of the default drupal search.

As well as allowing you to pick which fields are indexed, it also abstracts your search index so that you can take advantage of Apache solr etc. In your case, at least to start, I would suggest you stick to the simple database backend for search api.

The more flexible approach of search api brings additional functionality via other modules. For your use case I would look at Search API Entity Translation, which

  generates separate search index items for all/selected available
  languages for each translatable entity

It looks like this relies on entity translation rather than internationalisation, so make sure you survey any potential implications for translation of your content first.


How do I run multiple cron jobs? I want to run 4 cron jobs inside Drupal, in four different times.

How can I achieve that? Is there any module for that?

Try out the Ultimate Cron module.

  Runs cron jobs individually in parallel using configurable rules, pool management and load balancing. Multiple rules per cron job. Configuration per job (enable/disable, rules, etc.)

There is also the Elysia Cron module.

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.


Use an exposed filter in Views to list all nodes with same title I want to use an exposed filter in my view to allow users to list all nodes with the same title.

I have tried the link below but I have to manually pass the argument via the URL to get it to work.

Views related nodes with same Title

It is possible that your other two nodes have spaces at the end of the title. Check that, and if it is not the issue - try changing your exposed filter operator to Contains instead of Is equal to and see if you get 3 nodes as the result.


Views: filter content by two taxonomy terms I have vocabulary with these terms:

Sport

Soccer
Hockey
...

term

subterm
...

And I have content where is chosen one of those subterms.

Then there is a second vocabulary (countries):

France
GB
...

I need to create view that will show content by path.

For example: /sport/soccer - this will show content with soccer term. (This is done by default)

But I need also this: /sport/soccer/france - content with terms soccer and france.

I know that I have to user Views with contextual filters. I am using Drupal 7 with Views 3.

Thanks for your help.

Create three contextual filters: 1) global null (it's at the bottom), this will ignore the first argument 2) normal contextual filter for the first vocabulary, 3) normal contextual filter for the second vocabulary.

By normal I mean that you first select Term ID then Specify validation criteria, Taxonomy term, pick your vocab, Term name converted to term ID. It's a good idea to give these filters an Administrative title found under the More section, so that you can keep track which is which, as they need to be in the right order.

To reduce duplicates, in the view details "Advanced" > "OTHER" > "Query settings", check the box "Distinct" (thanks user2171413).


Drupal admin links broken for site when using WAMP (e.g. localhost/test2/admin/content) I decided to try out the newly launched Drupal 8. After resolving some issues I finally got the installer up and running (using WAMP), and arrived onto clean homepage of my test site.

the problem here is that clicking on any Admin menu links at the top of the page takes me to a Page Not Found... Anyone know if this has been reported among other users and if there is a fix for this?

Thank you to @kenorb for supplying the answer that resolved the issue involving WAMP, Drupal 8.0.0 and having the admin menu links break when clicking on them.

The solution is to uncomment RewriteBase line in .htaccess file and setting it to /test2 which is used as my base URL.


How to disallow users to edit their content after it was submitted for review? I'm looking for a solution that does not allow a user to edit content after being submitted for review.

I'm working with two roles: Content Creator and Reviewer.

If the Reviewer rejects the content, then it will be enabled for the Content Creator to apply changes again.

I've tried using the Workbench module, it is very practical, but when the Content Creator submits a new content for review, the user still has access to edit this content, even if it is with status "Under review".

You can look to the workflow module to implement a suitable workflow and permissions.


How to migrate files together with additional fields In my Drupal 8.4 installation I use the module File Entity. In the module are defined a few additional fields: 'author', 'title', 'alt',... My migration works. The files are imported, but the additional fields are after the import empty.

The complete YML (modules\my_migration_module\config\install\migrate_plus.migration.files.yml) looks like:

langcode: en
status: true
id: files
migration_group: import_xml
label: 'Import the test XML file'
source:
  plugin: url
  data_fetcher_plugin: file
  urls: 'http://example.org/test.xml'
  data_parser_plugin: xml
  item_selector: /imports/files
  fields:
    -
      name: id
      label: ID
      selector: ./@id
    -
      name: title
      label: Title
      selector: ./@title
    -
      name: alt
      label: Alt
      selector: ./@alt
    -
      name: author
      label: Author
      selector: ./@author
    -
      name: filename
      label: Filename
      selector: ./@filename
    -
      name: uri
      label: URI
      selector: ./@uri
    -
      name: target
      label: Target
      selector: ./@target
  keys:
    - id
  ids:
    id:
      type: string
process:
  field_alt: alt
  field_title: title
  field_author: author
  filename: filename
  uri:
    plugin: download
    source:
      - uri
      - target
destination:
  plugin: 'entity:file'
  source_path_property: uri
  destination_path_property: target
template: null

E.g. for the field title I have tried:

field_title: title
title: title
field_title/field_title_value: title
field_title/field_title_value: title
field_title/field_title: title
file__field_titel/field_title_value: title
file__field_titel/field_title: title

I have found a solution for a similar problem in Drupal 7: How to migrate fields attached to files? I'm not sure, how can I implement this in Drupal 8.

The YML code is correct. But there is an issue in Drupal core: https://www.drupal.org/project/drupal/issues/2822545

There is also a patch. I have tested the patch and it works:
https://www.drupal.org/files/issues/2822545-cannot_update_file_properties-6.patch

The patch can be installed with Composer:

{
    ...
    "require": {
        "cweagans/composer-patches": "~1.0",
        "drupal/core": "8.4.6",
        ...
    },
    ...
    "extra": {
        "patches": {
           "drupal/core": {
             "Solve the issue when migrating files with additional fields": "https://www.drupal.org/files/issues/2822545-cannot_update_file_properties-6.patch"
            }
        }
    }
}


How to get instance of Module / Plugin / Widget of Vote Object in THEME_preprocess_node? My drupal site is using the Fivestar Module or from the Vote Up Down Module.
Multiple of my content types are using various implementations of these as fields (specifically comments and my primary articles. Users can up/downvote comments and articles, and also give them ratings).
In my theme, I want to be able to access things like the vote count, and if the current user has voted, and ideally even the vote and reset links for custom display and front end functionality.
The default way how things are displayed doesn't work for my purposes, and creating specific views/blocks for each little snippet on my page, or manually overriding each template seems too cumbersome, and not flexible enough.
I'd much rather get all the vote info that I need in an array and pass it to my template, to be then displayed for full nodes, teasers, and comments.
How can I make use of the pre-formatted data that the modules are fetching and compiling from the database?
I see for example that abstract class VoteUpDownWidgetBase extends PluginBase implements VoteUpDownWidgetInterface has a method public function build($entity) which does exactly what I need to do. It gets all of the data about the vote field, and formats it for display in a template.
I don't see this equivalent from the Fivestar Module yet, but I'm sure I'll find something useful...
Either way: How can I access this method? What class do I have to get an instance of?

Turns out, everything I need is in $variables['content'] as long as the widgets/plugins that I'm trying to display are set to display as part of the view mode.
So in my specific case I can for example access $variables['content']['field_upvotes']['#up_points'] and that contains the number of upvotes!
Easy enough! :-)


How do I switch a node's view mode for AJAX calls? I've programmatically created a new view mode called ajax.  Is there any way to force a node page to use that view mode if I'm making an AJAX call?  I know how to switch page and node templates when it's an AJAX call in template.php, but it's not quite the same thing.

If you have a custom handler for your ajax request, I suggest you to manually render the node using node_view api function. It has a view_mode parameter which you should set to 'ajax'.


Views - Add a wrapper around fields or rows Example:

I have a view with fields:

[field_name]    == Field collection item: Name
[field_title]   == Field collection item: Title
[field_text]    == Field collection item: Text

I can wrap these fields by excluding from display first two of them, and rewriting the output of the third field with tokens, for example:

[field_text]

[field_name] // [field_title]

It seems a bit tricky, so here is my first question:

Is there any module or just another way to wrap fields in views?

I know Semantic Views module which solve the problem, but there is no recommended releases for Drupal 7.

Question #2

All my fields are wrapped in their div like in above mentioned example, but this is only the one row, and I have several rows. I need wrap all of them in another div.

Do I have to create a view template file only for that? which contain for example:

<?php if($rows): ?>

        <?php print $rows; ?>

<?php endif; ?>

I have a feeling like I miss something when I have to create a special template file only for one wrapper.

I think it's pretty safe to say that most people tackle both of your questions using the Cascading features of CSS.

For example, a typical view's HTML looks somewhat like this:

So, to your 1st question, Views already creates a div that wraps each row, that's the
 one.  You can style it per view by doing something like this:

.view-NAME .views-row {
  /* styles for the rows div goes here */
}

And to your 2nd question, Views also already creates a
 that wraps all the rows, that's the
 one.  To style it for a particular view you can do something like this:

.view-NAME .view-content {
  /* styles for the div wrapping your rows goes here */
}

Now, somewhat obviously, this is all dependent upon your theme.  I am aware that some out there dislike all the markup Drupal by default creates and has overridden a lot of the standard templates to create leaner markup.

If that's the case in your instance, you should still be to instruct Views to add a class to each row if you want.  This is accessed via the overall Style Settings (where you can also look at each Views template that is used for the particular view).

You could also instruct Views to add a class to each field wrapper.  This is accessed from the config widget by each field.

ADDITION based upon commentary:

The Views template that creates the output of the view-content div is views-view.tpl.php and the code in question is:

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

so without changing this up, you're right, Views doesn't allow quick and easy preprocessing of the View to insert any other variables into that div's classes.

You could however use Views' preprocessing hooks to create an additional variable so you don't need to create lots of additional templates but rather just one more.

For example, copy views-view.tpl.php to your theme (easiest) or module (requires special Views theme incantations :) and modify it along these lines:

<?php if ($rows): ?>
  <div class="view-content <?php print $my_special_content_class; ?>">
    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

and then create a views preprocess hook along these lines:

function YOURTHEMEORMODULE_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='VIEWYOUWANT' && $display_id=='DISPLAYYOUWANT') {
    $vars['my_special_content_class']='FOO';
  } else {
    $vars['my_special_content_class']=''; // so we don't have to isset() or !empty() it in our template :)
  }

}

Save everything and clear your theme cache and now you should be on your way.

SECOND ADDITION:

Upon further thought, and a 'doh!' moment, you can do this without a template at all in preprocess like this:

function YOURTHEME_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='VIEWYOUWANT' && $display_id=='DISPLAYYOUWANT') {
    $vars['rows']='
' . $vars['rows'] . '
';
  }

}

if you don't mind another wrapped div in there.  And, I think you will need to/should do this in your theme instead of a module so you make sure this happens in the right order, eg, you want this to happen after Views is all said and done with things, and the theme hooks always run after the module hooks.


How to get a conditional dependency to work? I have 2 fields in my content type 'test':

'Photos Gallery' -field type is image
'Enable' checkbox to Enable gallery (field type boolean)

Required output: When 'Enable'-field is checked, the node should not allow us to save with empty photos in the 'Photos Gallery' field and we should be able to save if 'Enable' is unchecked.

I tried the Conditional Fields module and given condition like 'Gallery Photos is required when Enable is checked.', where 'Gallery photos' is dependent and 'Enable' is dependee field.

Current output: In the node edit page , when 'Enable' is checked, asterisk (*) can be seen near 'Gallery Photos' , but without adding photos if i save, it is allowing me to save, without any error.

What additional settings I need to do, apart from dependency settings?

Note: I'm also interested in possible alternative solutions to get this to work (instead of using Conditional Fields).

As an alternative solution to using the conditional fields module (cfr your comment in your question), you can use the Rules module for this. Here are some details (the pseudo code) about how to do so:

Rules Event: Before saving content.
Rules Conditions:

Check for "entity has field" (for field = Enable)
Check for "entity has field" (for field = Photos Gallery)
Compare the value of the "Enable" field, for both the original value (before editing the field) and the (new) updated value, to verify if they enabled (checked) this field.
Check if field "Photos Gallery" is empty.

Rules Action: display an error message to explain that your validation failed. For an example of how to display an error message using rules, refer to my answer to "How to make the permissions of a module more granular?" (which actually includes 2 actions, you only want the drupal_message part of it (probably not the redirect to somewhere else).

To understand the need for those Rules Conditions "1." and "2.", have a look at my answer to "How to check in a rules condition if an image field has value?"

Should be straight forward to "develop" such rule, no (PHP) coding at all involved (only site building using admin UI).

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.


Ajax Submit Forgot Password Form Loaded in Front Page Firstly, I altered the Forgot Password Form in my template.php and added the #ajax property:

// Ajaxifying the form

    $form['actions']['submit']['#ajax'] = array(
      'callback' => 'themename_user_pass_form_ajax_callback',
      'wrapper' => 'user-pass',
      'method' => 'replace',
      'effect' => 'fade',
    );

Then I created the ajax callback function:

function themename_user_pass_form_ajax_callback($form, &$form_state){

  module_load_include('inc', 'user', 'user.pages');
  return $form;

}

The form works fine in /user/password page and the ajax works too.

I want the form to appear in the front page, So in my page--front.tpl.php I added the following:

<?php
      module_load_include('inc', 'user', 'user.pages');
      $user_pass = drupal_get_form('user_pass');
      print drupal_render($user_pass);
 ?>

The form appears and when submitting returns with js alert

  An AJAX HTTP error occurred.
  HTTP Result Code: 500
  Debugging information follows.
  Path: /system/ajax
  StatusText: Internal Server Error
  ResponseText:  Memory used at: devel_boot()=3.43 MB, devel_shutdown()=32.2 MB, PHP peak=32.25 MB.

Note: The ResponseText is from devel.

In my php_error log file I found this:

  PHP Fatal error:  Call to undefined function user_pass_validate() in
  /www/drupal/includes/form.inc on line 1464

The user_pass_validate() is not declared maybe module_load_include('inc', 'user', 'user.pages'); is not working with the ajax call?

module_load_include() works slightly differently from your example. The first argument is the file extension, the second is the module name, and the third is the file name minus the extension.

This should work:

module_load_include('inc', 'user', 'user.pages');


the difference between the drupal login "block" and mysite/user/login I trying to understand the difference between the default Drupal 7 login block and the login provided at mysite/user/login.

From my own understanding, it would appear that the default login block provided by Drupal 7 only logs you into the web interface and the login provided at mysite/user/login is a page provided for you to login through your website.

I have come to this conclusion because if I log out of the web interface and try to login at user/login, nothing happens (I enter my credentials, but nothing happens).

This is my understanding.

If my understanding is wrong, I would appreciate it if someone could please correct me. If I am correct, could someone please provide a good tutorial that teaches one how to use the login page to validate a user and "transfer" the user to a validated state?

Thank you.

There is no such difference. Both forms provide the same input fields and use the same validation and submit handlers. The one is generated by user_login(), the other is generated by user_login_block().


Show block on /user profile page only I want to show a block when a user visits his/her own profile page at /user.
The public user profiles have paths of "/member/[username]".

When I limit the block to "user" it won't show up. When I limit it to "member/*" it will show up both on the own profile and on the public profiles.

Is the "user" url something special?

What @clive has mentioned is great if you want to use /user for this, but from a number of angles, I really don't like using it at all for this kind of thing.  I would like to say mostly from a style perspective, but actually more from a linking perspective, eg, an email or post that includes check out my cool profile on mototribe:  www.mototribe.com/user bollixing things up.

So, when I've done stuff like this, I include php logic in my block view along the lines of:

$global $user;
$block=array();
$node=menu_get_object();

if ($node->type==THENODETYPEWEARELOOKINGFOR && $node->uid==$user->uid) {
  // generate the block here
} else {
  // don't generate anything (or put something else in it's place)
}

return $block;

so the block is only generated when the currently logged in user looks at a certain node type that s/he owns.  Obviously I've not fleshed out all the isset()s or empty()s needed in prime time for the above but I am sure you get the jist.

Of course, I could also be talking total smack here if D7 user profiles aren't nodes, but this works great in D6 with content profiles :)


How to change the "vid" in a field content_taxonomy I would change the vid in this code, I tried to replace it but not to change how do you make it?

 $fields[] = array(
    'field_name' => 'field_galerie_type',
    'type_name' => 'rf_galerie',
    'display_settings' => array(
      'weight' => '2',
      'parent' => 'group_galerie_donnees',
      'label' => array(
        'format' => 'above',
      ),
      'teaser' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
      'full' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
      '4' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
      'token' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
    ),
    'widget_active' => '1',
    'type' => 'content_taxonomy',
    'required' => '0',
    'multiple' => '0',
    'module' => 'content_taxonomy',
    'active' => '1',
    'save_term_node' => 1,
    'vid' => '60',
    'parent' => '0',
    'parent_php_code' => '',
    'depth' => '',
    'widget' => array(
      'group_parent' => '0',
      'show_depth' => 1,
      'default_value' => array(
        '0' => array(
          'value' => '',
        ),
      ),
      'default_value_php' => NULL,
      'label' => 'Type',
      'weight' => '2',
      'description' => '',
      'type' => 'content_taxonomy_select',
      'module' => 'content_taxonomy_options',
    ),
  );

In fact, it is quite simple.

First, change in the type of content vocabulary.

Then you need is to add features and the fields in the .info module configuration managing content type.

Then just make a pretty:

drush fu my_feature

and then we have a taxonomy fields changed continuously integration.


How can you remove another modules events? So, I have an event subscriber for Drupal commerce that listens for "commerce_order.place.post_transition" and will send a bespoke order email (due to not being able to change some of the things like subject title in the commerce module).

Commerce also has an event subscriber listening to "commerce_order.place.post_transition" which will send an order receipt email. I need to unsubscribe this event to prevent sending duplicate emails but searching through google and comments sections of articles has lead me to a dead end.

Any ideas?

Remove the event subcriber service from the container:

my_module/src/MyModuleServiceProvider.php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Remove the foo event subscriber.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $container->removeDefinition('foo_event_subscriber');
  }

}

You find the service name in the MODULE.services.yml file of the other module.

More info https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services


Redirect users on first time login to a particular page In my drupal 7 website when a user registers, an email is sent to them. And when they click on the verification link in the email they are redirected to "SITENAME/user" page. I wanna change that. I want the user to be redirected to another page say "SITENAME/upload" page. I have used the user registration password module. The email sent to the user is

[user:name],

Thank you for registering at [site:name]. You may now log in and verify your account by clicking this link or copying and pasting it to your browser:

[user:registrationpassword-url]

This link can only be used once. You will be able to log in at [site:login-url] in the future using:

username: [user:name]
password: Your password

--  [site:name] team

I think I have to change the  [user:registrationpassword-url] part. But Im not sure what to change that to.

Thanks

This is actually very simple in D7 using the Rules module. All you have to do is see if the value of the user's Last Access field is empty. When an account is created, the initial value of the Last Access is empty.

The value of this field is not set until sometime AFTER the rules have been run. So, all you have to do is setup a conditions in rules that check:

Data value is empty
site:current-user:last-access

Here is an export of my rule and it has been working fine. If anyone finds any issues, please let me know. You should be able to import this rule into your site.

{ "rules_first_time_login" : {
"LABEL" : "first time login",
"PLUGIN" : "reaction rule",
"WEIGHT" : "1",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "user_login" : [] },
"IF" : [
{ "data_is_empty" : { "data" : [ "site:current-user:last-access" ] } },
{ "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "16" : "16" } } } }
],
"DO" : [
{ "drupal_message" : { "message" : "Welcome to Drupal Camp Florida. Please submit your session proposal below." } },
{ "redirect" : { "url" : "node/add/sess?destination=/admin/dashboard" } }
]
}
}

The role with a value of "16" is a role of "Speaker".


How do I Bulk Edit Fields or Taxonomy of Nodes? I'm working on a site that needs bulk tagging on nodes. The D8 core View Bulk Operations Port is "simple" (https://www.drupal.org/node/1823572) and it doesn't have "modify entity values" which I used for this user-case in D7. There isn't a D8 tagged version of contrib VBO I can find.

My specific use-case is I need to bulk tag groups of blog posts with single terms. I have bulk imported around 2000 nodes from wordpress and need to apply new tags to them. Once the backlog id tagged I don't really need bulk editing any more. (But I'm sure many folks have similar use cases, like bulk editing fields or tags that aren't one-off tasks)

Actions is part of Core so it might be possible to write custom actions for my use case (Tag node with taxonomy term X, Y or Z). This documentation seems the most promising. https://www.drupal.org/node/2020549

Can any confirm this is best way to bulk-edit nodes or is there a different approach that I should consider?

Drupal core doesn't provide this functionality, so yes, you need to implement it yourself.

Yes, you can implement your own action plugin to do this. You can also have a form to select which tag you want to apply. Have a look at the node delete action plugin, which uses a confirmation form, but you can implement whatever functionality you want in that form.

Keep in mind that Drupal core is missing another important feature for your use case. The ability to apply a bulk action to more than one page. The best you can do until there is a port of the contrib module to provide this to increase the amount of rows per page, so that you need to repeat it fewer times.


Single site with multiple user interfaces based on path and role I'm currently working on a Drupal project that requires 3 separate interfaces.

Administrative users login to the site and all of the pages associated with their specific role start with a particular base path. Lets say it is /path_A/*. I'd like these users to login to the site using www.example.com/path_A/login and all subsequent requests to any given page would be accessed via www.example.com/path_A/.

The end users would access the site in the same way except the login page and all subsequent requests would begin with www.example.com/path_B. Users of path B should not be able to access any of the administrative functions tied to path_A/ but administrators should be able to navigate to any path_B/ URL and access the site in the same way as the end users.

On top of all of this, there is a public facing set of pages that should be accessed using the domain itself, it is basically a blog and information directory living at the webserver root directory (www.example.com).

Additionally none of the pages belonging to any of these specific URL paths should be available through the others, so a page /path_A/page/3 should not be accessible via /path_B/page/3 or /page/3. Multi site setup for this is not really an option since the a large piece of the database is shared by all three subsections of the site.

My initial idea is that I could use .htaccess rewrites to direct all requests to each of the paths to the drupal index file, register 2 aliases for each of the login pages using the paths module and then use context to change the interface based on the path/role. I am a bit new to drupal and this is my first major project working with it so I'm not sure if this is the best approach to this problem. And yes I realize that this might seem like a waste of time but the client really stressed this functionality.

Role Theme Switcher does what you're asking for roles.  For access to pages you could write your own custom module that implements hook_node_access or you could use Views permissions (which I've found to be quite easy and works well) or you could use another module that manages permissions on a per-page basis like Content Access or Nodeaccess.

Lots of options for what you want.  I personally recommend trying to combine Role Theme Switcher with Views permissions.  Otherwise I would go for making a custom module with hook_node_access.  I don't recommend Content Access or Nodeaccess, they've never worked exactly right for what my needs are, but they are there for reference.

EDIT: You may also find Rules to be helpful re-directing users of certain roles to certain pages based on their role when they login.

EDIT 2: As I mentioned in the comment below, logintoboggan is another module that will allow re-directs upon user login.


How do I contribute a version of the same module for the latest core version? I have contributed a module for Drupal 7; now I am interested in contributing the Drupal 8 version of the same module.

When I started creating the Drupal 7 version; I had all the instructions (under VERSION CONTROL of the project); now I need instructions in order to start with the Drupal 8 of the module.

So, I am looking for GIT instructions.

Drupal.org apparently doesn't give information for Drupal 8, in the Version control tab of projects. I checked for a project with a Drupal 8 version (the Token module), but even selecting a Drupal 8 branch, the information given is for Drupal 7.

That said, there isn't much difference, with Drupal 8. What I report here are the adapted instructions for Drupal 8.

  Creating Releases

  See the naming conventions for a complete description of how to name branches and tags so you can create releases.

  Branch for a dev release

  This creates and checks out a new branch in one command, then pushes it to Drupal.org.

git checkout -b 8.x-1.x
git push -u origin 8.x-1.x

  Tag for a stable release

git checkout  8.x-1.x
git tag 8.x-1.0
git push origin tag 8.x-1.0


Create a node Automatically when a commerce order is completed In my site, I am using drupal commerce in order to run  a shop.

In my plan, a new node must be created when an order is completed. (paid)

Also in new node creation I want to use the order's field values. (for example order id, or username (and uid ) who ordered , entity values & etc )

Please help me. How can I setup this solution?
can I do this process via "Rules" or I have to create a module and use hook functions?

Thanks a lot for your guidance.

Yes, its time to create a module, and use these nice hooks Commerce API is offering to interfere to the regular execution of things in your Drupal site.

After getting the big picture, creating a node will be as easy as this first script.
So in a hook which is invoked whenever an order is complete, you would add the node creation code.


How to make the node author's email show up as a replacement token in a Rules Action? I have set up a rule that is as follows:

Rules Event: After saving new content of type Article.
Rules Conditions: User has role(s), with role = Authenticated user.
Rules Actions: Send mail to all users of a role, with role = Administrator.

When anyone adds an article to the site, all the admins are notified and I have used token replacements for the email fields like so:

Mail Subject: [node:author] has just created a piece of content entitled "[node:title]"
Message Body:

[node:author] has just created a piece of content entitled "[node:title]"

You can see the article here and proof read: [node:edit-url]

The article is here: [node:url]

This all works perfectly, however I want to also add the author of the node into this email so that any of the admins can email this person if they need to. I cannot work out how to get the author's email into the email body as it doesn't seem to show up in replacement patterns.

Anyone any idea how I can achieve this?

It is not listed among the replacement tokens, but you can use the [node:author:mail] token.


Multiple Views filters criteria : query with LEFTJOIN instead of INNERJOIN? I created a view with 2 FILTER CRITERIA (Content: Has taxonomy term) exposed to visitors.

For testing purpose, I have 2 vocabularies with 2 terms inside :

Vocabulary 1

T1
T2

Vocabulary 2

T3
T4

I have 2 articles. Article 1 is only PART of T1.

If I select T1 and Any, I have no results but I should have result because I use OR operator(see screen shot).

Is the view filter criteria correct ?

If this article is T1 and T3 and i select T1 and T3, it works. If I select any and any, it works and i see my 2 articles.

See 2 cases :

1)

2)

How can I have a query with LEFTJOIN instead of INNERJOIN ?

Checking the "reduce duplicates" fixed the issue for me.

In "Views setting" (admin/structure/views/settings), check "Show the SQL query"

Then, we can see the SQL query built with views.

With reduce duplicates, INNER JOIN are converted to LEFT JOIN, which is exactly what I need I think.

When it was unchecked, the SQL query was :

SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
INNER JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
LEFT JOIN {taxonomy_index} taxonomy_index2 ON node_field_data.nid = taxonomy_index2.nid AND taxonomy_index2.tid != '2'
WHERE ((taxonomy_index.tid = '2')) AND ((taxonomy_index2.tid = '10'))
ORDER BY node_field_data_created DESC
LIMIT 11 OFFSET 0

When it is checked :

SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {taxonomy_index} taxonomy_index_value_0 ON node_field_data.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '2'
LEFT JOIN {taxonomy_index} taxonomy_index_value_1 ON node_field_data.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '10'
WHERE (taxonomy_index_value_0.tid = '2') OR (taxonomy_index_value_1.tid = '10')
ORDER BY node_field_data_created DESC
LIMIT 11 OFFSET 0


Module Block destroys head I'm struggling with blocks and a custom module. What I've got so far is a module which generates a block with that code:

function commerce_bulk_invoice_block_info() {
    $blocks = array();
    $blocks['showinvoiceoptions'] = array(
        'info' => t('Define Invoice Options'),
    );
    return $blocks;
}
function commerce_bulk_invoice_block_view($block_name = '') {
    if ($block_name == 'showinvoiceoptions') {
        echo '
';
        if(!isset($_SESSION['selected_entities'])) {
            echo 'select a product first';
        } else {
            echo '
SESSION Variables:
';
            echo '
';
            print_r($_SESSION['selected_entities']);
            echo '
';
        }
        echo '
';
    }
}

My problem is, the content generated by hook_block_view is not shown in the selected region but directly after the opening body tag. And it pulls the whole head-content into the body. Anyone knows a solution for that?

By the documentation, you should return content you want in block, not echo it.

$block['subject'] = t('Subject'); // String here
$block['content'] = t('Content'); // Array or string here
return $block;


Using tokens in block titles Plugging tokens into a block's title only shows the input text instead of what the token's supposed to output.

Is there a way to enable/use tokens in block titles, or maybe an alternative method of getting the results I want?

I've tried using Token Filter module, but it doesn't change the functionality.

I am trying to insert the [user:profile-realname] token into a block title (specifically the User Menu block title). The token is in my list of tokens available to use via HELP in the backend.

AFAIK, this cannot be achieved using the block title field, however using the Token Filter module, you can just drop the token in the body area of the block and wrap it in an H2 tag and it will appear as if it was the block title. (Just set the block title to <none>)


Qiuck tabs shifts the Openlayers map background layer Im displaying the list of locations (address and map Openlayers + Geofield) using views. There is no problems when displaying view in ordinary way, but when the view is displayed inside quicktabs the background shifts about 100px in particular(top-left) direction from the place it should be.

Normal map display

Same location with shifted map background

Also, I noticed that after opening Developer tools in Chrome the grey zone without map disappears(fills up with map) and if you click on the map region the red point mark shifts back to the place where it should be.

Any ideas about how to fix this issue ?

This is the css/jquery issue .inside a quick tab the map doesn't get load because it is display none initially .when you click on the locations tab it tries to get load but dos not get loaded . you need to play with jquery a little.


Create picture module responsive styles programmatically I could not find any documentation anywhere on how to programmatically create a new picture module responsive style set so am adding what I've discovered here.

First step is to create the image styles:

// 1. Create image styles
$multipliers = array(
  '1x' => 1,
  '1_5x' => 1.5,
  '2x' => 2,
);
foreach($multipliers as $label => $multiplier) {
  $style = image_style_save(array('name' => 'tile_image_' . $label));
  $effect = array(
    'name' => 'image_scale_and_crop',
    'data' => array(
      'width' => 390 * $multiplier,
      'height' => 194 * $multiplier,
      'upscale' => TRUE,
    ),
    'isid' => $style['isid'],
  );
  image_effect_save($effect);
}

Then create a group for the image styles:

// 2. Create image group
$new_group = breakpoints_breakpoint_group_empty_object();
$new_group->machine_name = 'tile_image';
$new_group->name = 'Tile image group';
$new_group->type = BREAKPOINTS_SOURCE_TYPE_CUSTOM;
$new_group->breakpoints = array('breakpoints.theme.armi_embl_theme.desktop', 'breakpoints.theme.armi_embl_theme.mobile');
breakpoints_breakpoint_group_save($new_group);
menu_rebuild();

And then finally define the mapping between the image styles and your set of breakpoints:

// 3. Add picture mapping
$mapping = picture_mapping_create(TRUE);
$mapping->table = 'picture_mapping';
$mapping->type = 'Normal';
$mapping->export_type = 1;

$mapping->label = 'Tile image mapping';
$mapping->machine_name = 'tile_image_mapping';
$mapping->breakpoint_group = 'tile_image';
$mapping->mapping = array(
  'breakpoints.theme.armi_embl_theme.desktop' => array(
    '1x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1x',
    ),
  ),
  'breakpoints.theme.armi_embl_theme.mobile' => array(
    '1x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1x',
    ),
    '1.5x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1_5x',
    ),
    '2x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_2x',
    ),
  ),
);

picture_mapping_save($mapping);


Error adding one content type. Bundle missing in term references I've got a problem on a Drupal 7.14 site when trying to add a new node to only one content type.

I get the following error message in the log:

EntityMalformedException: Missing bundle property on entity of type taxonomy_term. in entity_extract_ids() (line 7389 of /homepages/33/d169792374/htdocs/sites/yourfutureinautomotive.com/includes/common.inc).

I've tried the fixes outlined here as well as removing modules one by one and I'm not getting anywhere.

I've even reverted back to 7.8 to make sure I was on the same version as other people who were having the issue.

I'm open to any ideas or troubleshooting hints.

Ta

EDIT

As per @mojzis suggestion below I used the Devel dpm function. The following was output:

EDIT 2

vid: 14 is the problem. There is no vocab with vid of 14. Trying to hunt down a reference to it anywhere but not having much luck.

Your issue is most likely related to the Media module, and specifically this issue: 'Missing bundle property on entity of type file error'. In your troubleshooting efforts, did you run across this info? A quick check to confirm if this is the culprit is to follow the step(s) outlined in comment #5.


How do I get the number of rows affected from an update query? I'm having trouble figuring out how to get the number of affected rows from an update query in Drupal.
I have a form where users can update their profile details. Now, not every user is going to update everything from their profile. They may just update one field or two.
How do I account if there was a change or not and check for the affected rows?
This is the code I am running.
$update_query = $db->update('TABLE NAME')
  ->fields([
    'uid' => $uid,
    'name_of_user' => $name,
    'url' => $url,
    'website' => $website,
    'industry' => $industry,
    'company_size' => $companySize,
    'company_type' => $companyType,
    'headquarters' => $headquarters,
    'founded' => $founded,
    'page_picture' => $upload_picture,
    'tagline' => $tagline,
    'updated_at' => $time,
  ])
  ->condition('uid', $uid);

  $affectedRows = $update_query->execute()->rowCount();
  return new AjaxResponse($affectedRows);

The code doesn't return anything. I even checked the network tab and there's nothing displayed in the response tab. I should be getting back either 0 or 1. Am I missing something?

$update_query->execute()->rowCount() would cause a Call to a member function rowCount() on a non-object (or Call to a member function rowCount() on int, on PHP 7.4) since $update_query->execute() returns the number of rows  matched by the update query, including the ones that actually didn't have to be updated.
rowCount() can be called only when execute() returns an object implementing StatementInterface, which is the case for Select::execute(), Truncate::execute(), Upsert::execute(), and Query::execute().
Unfortunately, the only way to get the number of rows changed from an update query is to fetch the rows matching the update condition (in your case, the rows for which uid is equal to $uid), and count which rows have, for the desired fields (in your case, name_of_user, url, website, industry, company_size, company_type, headquarters, founded, page_picture, tagline, and updated_at), a value different from the value set by the update query.


Related Content with References in Drupal 7 I have made this website using Drupal 7 a year ago, where the References module plays a key role.

Say I have two content types movie and actor, and the content type movie has a references field which references actor nodes. Now, how do I have a block which lists other movies which the actors in this movie are referenced?

Something seems to be here: http://drupal.org/node/370227 but that doesn't seem to work for Drupal 7.

Also, as I have more than 1000 nodes in content type movie, I prefer not to move from References field also, my all my urls are like example.com/content-example

Thanks!

I am sure you could do all of this in one view using a contextual filter and using that as a relationship to point to the movies in question, but, if you don't mind some php coding, you can do all of this pretty easily yourself and one simpler view.

1.  create a view that has a contextual filter using the actor reference field, eg,
it returns just the movies that contain that actor, and in fields, just nid of the
movie node should be sufficient.  Make sure that this will reference any actor in the
movie, eg, all of the values of this field, not just the first one.

Then in your block hook, put in something along the lines of:

$node=menu_get_object();

$movies=array();
foreach ($node->NAME_OF_ACTOR_REFERENCE_FIELD as $actor) {
   $view=views_get_view('NAME_OF_VIEW_ABOVE');
   $view->set_arguments(array($actor['nid']));
   $view->execute();
   foreach ($view->result as $result) {
      $movies[$result->nid]=$result->nid;
   }
}

Assuming this is displayed on a page that is displaying a movie of course, what this does is grab the actors referenced in that node and then loops through them, grabbing each movie that has referenced them as well, and then stores that in an array.  Since we key this array to the movie's nid, we also create a unique list of movies.

So, now we have a list of movie nids so we can do something like:

foreach ($movies as $nid) {
  $node=node_load($nid);
  $content.='<div class="movie-title-link">' . l($node->title, $node->path) . ' </div>';
}

and return $content as the content of the block and style it however you want with css.

Caveat:  I am just learning D7 and a lot of times D6isms creep into play, and most of the above is just typed in from memory, so there may be subtle things you'll need to adjust (drupal_set_message() and print_r() are your friends) but this hopefully will help out.


Users aren't redirected to the front page after account cancellation I have a problem with account cancellation. The proccess itself executes fine, but after the batch proccess runs, the user isn't redirected to the front page as mentioned in the UserController::confirmCancel method:

user_cancel($edit, $user->id(), $account_data['cancel_method']);
// Since user_cancel() is not invoked via Form API, batch processing
// needs to be invoked manually and should redirect to the front page
// after completion.
return batch_process('');

This results in 403 error, as anonymous users don't have access to en/user/2/cancel/confirm/... path. I tested in in 2 different sites, using Drupal 8.2 and 8.3

How can I redirect user properly in this situation?

I solved it using custom service. Will post it here shortly.


Advanced search: USASearch compared to Apache Solr Search implemented by Acquia I have been asked by a US government agency to compare 2 different methods for
advanced search:

USASearch
Apache Solr Search implemented by Acquia

This agency already has a contract with Acquia to host their Drupal site and this subscription includes (for free) Apache Solr Search which is implemented by Acquia so cost is not an issue when comparing the 2 options since USASearch is free to any government agency.
What are the advantages and disadvantages of these 2 search methods, and which one would you recommend?

I didn't go too deep into USASearch, but it seems to me as a tool similar to Google Custom Search Engine.

So, let's classify them first. We'll call all such services as Search Providers. On the other hand, we'll call ApacheSOLR instances (whether through Acquia or otherwise), regular search index in Drupal or other such index hosting services as Indexes.

The general difference between Search Providers and Indexes is mostly in the level of control.

Search Providers

Quicker to setup for static websites as it is just HTML/JS code.
Ideal for simple static content with limited customization.
You don't have to worry about the index at all. That is your provider's job.

Indexes

For Drupal, it is just a matter of installing a module.
You get complete control over results, templating, filtering, facet search, etc...
You have to take care of indexing content, permissions, and search configuration.

Generally speaking, go for Indexes, or in your case, Acquia Search. The configuration and indexing is one time (and sometimes not even that) and the added benefits are huge. There are very few scenarios where I would pick a search provider instead.


Cannot get rules component to fire on Commerce Completing the checkout process I have a baffling situation. I created a nice little rules component that retrieves a list, using VBO, of published Drupal Commerce Product Display nodes with referenced product stock of zero or less. And then loops through that list unpublishing each node. This is how I built it - https://drupal.org/node/1345216#comment-8306801

This component works as expected when executing it by itself or when placing it in a rule with the "After updating an existing commerce product" and/or "After updating existing content" events. I cannot get it to run when attaching it to a "Completing the checkout process" event.

Any ideas? Is it a permissions issue, as in customer cannot run the component or access the VBO list?

Is there another event related to a customer completing an order that might work better?

It's possible the user doesn't have access to execute the rules component. You can check the permission in admin user permissions or on the rule component edit page.

Keep in mind the rules component will need to be attached to a reaction rule to fire on the checkout complete event.

Other than that, if the component can process the passed $commerce_order parameter (passed to checkout complete), then it should be ok.


Is it possible to run functional tests without creating test tables? My goal is to  speed up functional tests without tweaking the database. Is it possible to avoid the creation of Simpletests setup tables and use existing tables instead? I read this article where the author states :

Maybe the answer is Simpletest 2 which allows you to run on a "dirty" environment.

So is this "dirty" environement is the answer? If so, how to use it as setup ?

I have found the answer there. But don't do that !

It's better to move the database on a tmpfs folder (it's > 5x faster), because not only a "dirty" environment does not work, but it will broke your website with a serious error (just happened to me).
Hints to tweak the database on this question.

It's there but don't do it :

  // for our functional testing, we want to test the pages and code that
  // we've been generating in the real database. to do this, we need to
  // ignore SimpleTest's normal fake database creation and fake data
  // deletion by overriding it with our own setUp and tearDown. NOTE that
  // if we make our own fake data, we're responsible for cleaning it up!
  function setUp() {
    // support existing database prefixes. if we didn't,
    // the prefix would be set as '', causing failures.
    $this->setup = TRUE; // Drupal 7 way
  }
  function tearDown() { }


Drupal 7 Views table style with exposed filters I want to place my exposed views filters in a tabular format, something like below

How to achieve this?

The only way to do this is in the theme layer.

One way would be to implement a theme override - probably with a hook_preprocess function, maybe also hook_form_alter. Embedding the form in a table will be particularly tricky, since the exposed filter and results table are rendered in distinct processes.

If you are comfortable with jQuery, it might be easier to do this with javascript.


Why hook_preprocess_html() isn't working? Why hook_preprocess_html() isn't firing in my module file? Is it only works in theme_hook?

EDIT:

function my_module_preprocess_html(&$variables) {
  if (current_path() == 'user') {
    $variables['head_title'] = implode(' | ', array(drupal_get_title(),  variable_get('site_name')));
  }
}

Try the general preprocess hook, like:

/**
 * Implements hook_preprocess().
 */
function my_module_preprocess(&$variables, $hook) {
  if ($hook == 'html') {}
}


How to check if a View was cached? Is there a simple way to check (example: see from UI or browser developer tools) if a rendered View was retrieved from cache or just generated on the page load?

This would need to work for every view display, like a View Content pane embedded in a Panels page.

Would this need custom code or is there a module or any-other-simple-way for this?

Thanks

Caching only works for anonymous users (people who are not logged in).

So, a simple test would be to add new content to your view or make a change to your view. Ex: change your view title.

On another browser have your page open, but as anonymous. If your view doesn't change, it means the cache worked.

The View will NOT change to anonymous users until you clear the cache.


Add site branding to external site Maybe I'm asking the wrong questions on google, but I can't seem to find a solution to what I'm trying to accomplish.

We've created a Drupal 8 site and we need to add the existing header and footer to an external site so that it includes our site branding.

What is the best solution to accomplish this?

I have some initial thoughts, but feel like I'm way off base:

Pull the <header> and <footer> out of the page.html.twig template and put them into a separate header.html.twig and footer.html.twig template. (My base theme is bootstrap barrio)
Create a custom API that exposes the html from the header and footer twig templates. (I'm not sure if this even possible)
Using the custom API, expose any paths to custom CSS/JS required for theming.

Then the external website would just call the API, grab the html/css/js and put all the gathered resources on their pages.

Is the above on the right track or am I completely wrong? If I am on the right track, how would I accomplish #2?

I think creating a service REST API to be consumed by the client sites is the cleanest solution.

This has been implemented in Drupal 7 with sharedblocks but there no Drupal 8 port at this time.

Studying this module would give you a solid foundation on how to accomplish your task in Drupal 8.

Based on the same concept there is also distributed_blocks module but again does not seem to have a Drupal 8 port.


A way to share content structure across several panel pages I develop a site which presents content along with multiple blocks of information on side bars. They're context related by nature, so I decided to use panels instead of block module.

That approach worked great for some time and was flexible enough. I created multiple view panes and passed the arguments through panel contexts.

But soon I realized there is a problem. I have a bunch of pages on a site which usually implemented using views pages. But they must more or less share the same side bars. So they must be panel pages too.

But there is a dozen or so of panes on a panel, so copying panel content (say, by using export and import) creates an awful mess and redundancy which greatly hampers maintenance and subsequent changes.

I'm thinking about creating all the pages in code by customizing one rough part created through gui. But I'm hesitating whether it's a good way. Any ideas?

Why not use mini panels, one of the sub-modules of Panels.  Mini-panels are just like panel pages except that instead of taking a path and acting like a page they act like blocks.  They are specifically designed to be embedded in other panels/pages.

So you can make a mini panel called sidebar and then if you ever have to make a change just update it in one place.


How to put multiple conditions on a field, using Views 3? I am trying to make multiple conditions on a field in Views.

I found Views Conditional that allows only one condition.

I also found Views Custom Conditions, which I still don't really find how to use (very few documentation and the one left is very confusing to me).

So I'd like to find out How to put multiple conditions on one field, using Views 3.

Consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

A few issues on Drupal.org that may be of some help:

Using OR in filters breaks contextual filters.
Views AND/OR Contextual filters two ways.

There is also this comment in the support forum.


Debugging your code under SimpleTest when the behavior is different I'm dealing with a weird problem where a few of my tests are dying from exceptions when run inside of SimpleTest, but I'm unable to reproduce the problem outside of the SimpleTest environment. In particular, it appears that exceptions that I'm catching in my module code get intercepted by SimpleTest before they even leave my try block.

I'm able to debug my test script using xdebug, but for whatever reason, I can't get SimpleTest to pass on the debugger info to my code when it's running under SimpleTest.  So when SimpleTest calls $test->run() on one of my tests, the test starts up in its own, SimpleTest-unaware process.  And my debugger sits on its hands (they have hands, right?) and runs as if everything is copacetic.

Is there some option in SimpleTest that will allow me to get the XDEBUG_CONFIG environment variable passed on to the subprocesses that SimpleTest spawns?

I have a provisional answer to this, although I'm hoping someone will supply a better one than this one.

First of all, setting XDEBUG_CONFIG as an exported environment variable will let you stop your test script, but not your actual Drupal code.  The reason is sort of ugly.  SimpleTest interacts with your code using its own mini-browser.  So your SimpleTest test runner is as completely isolated from your Drupal application as your browser at home is isolated from the web server you get your page from.  There's no connection at all.

So how do we use xdebug via a browser?  One way is to set a get parameter, and add the XDEBUG_SESSION_START variable to your URL, like this:

  http://my-site-i-want-to-test/node/42?XDEBUG_SESSION_START=my-key

When your test web server sees XDEBUG_SESSION_START, and you have your server set up to connect with your IDE, your server connects up with your IDE, and away you go.

So, here's my not-really-very-good solution to the problem: I get drupalGet and its twins to add XDEBUG_SESSION_START to the string SimpleTest uses to communicate with your server.

SimpleTest is actually using PHP's curl extension to create its mini-browser. If you look at the implementation of drupalGet in WebTestBase.php, you'll see something like this:

  protected function drupalGet($path, array $options = array(), array $headers = array()) {
    // We re-using a CURL connection here. If that connection still has certain
    // options set, it might change the GET into a POST. Make sure we clear out
    // previous options.
    $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));

    // lots of stuff omitted here...

    return $out;
  }

The $options argument gets passed to $this->buildUrl(), which takes the regular format for URL options.  We need to add something to the query string, so we need to pass

$options = [
  'query' => [
    'XDEBUG_SESSION_START' => 'my-key',
  ],
];

This unfortunately requires you to edit your test and pass $options whenever you want to get control of your application via your debugger.

A slightly better solution is to override drupalGet() in your test class, since AFAICT, all the other drupal*() methods ultimately call drupalGet().  In your overrided version, you just append the 'query' info above to the $option array that is passed to it, and then call the original method.  You can even watch for a environmental variable in your SimpleTest test script, and only add the 'query' string when you see it.


Adding JavaScript to Slideshow? I asked a question a few days ago about getting the height of images to adjust in Slideshow along with the width. Unfortunately, I received no responses.

So, I went about writing some JavaScript that adjusts images in a page the way I would like the images in Slideshow to be adjusted. The code works fine on regular Drupal pages, but does not work for the images in Slideshow.

Does anyone know how to get the JavaScript to work for the images in the Slideshow? I should state that I am brand new to coding and JavaScript, so there may be some issues with the code below, but it does work.

Here is the JavaScript code:

function myFunction() {
  var x = document.getElementsByClassName("slide");

  for (i = 0; i < x.length; i++) {
    var viewHeight = window.innerHeight;
    var viewWidth = window.innerWidth;
    var viewAspect = viewWidth / viewHeight;

    var imageHeight = x[i].height;
    var imageWidth = x[i].width;
    var imageAspect = imageWidth / imageHeight;

    if (imageAspect < viewAspect) {
        x[i].style.height = viewHeight + "px";
    }
    else {
        x[i].style.width = viewWidth + "px";
    }
  }
}

window.onload = function() {
  myFunction();
};

window.onresize = function() {
  myFunction();
};

I ended up creating a regular view, not a slideshow. Then I used a variation on the code above to reshape the images. And I used CSS on the mini pager to turn it into the buttons that one would find in a typical slideshow. It turned out exactly how I wanted it. Although it took a lot of time and aggravation, I learned a bit more about about Drupal, JavaScript, and CSS. Plus, I can reuse the code again.

If anyone is interested, my final JavaScript code is below; there were a few minor problems with the code above that caused it to act wonky in certain resizing situations.

    function myFunction() {
      var x = document.getElementsByClassName("slide");

      for (i = 0; i < x.length; i++) {
        var viewHeight = window.innerHeight;
        var viewWidth = window.innerWidth;
        var viewAspect = viewWidth / viewHeight;

        var imageHeight = x[i].height;
        var imageWidth = x[i].width;
        var imageAspect = imageWidth / imageHeight;

        if (imageAspect < viewAspect) {
          x[i].style.height = viewHeight + "px";
          x[i].style.width = "auto";
          x[i].style.marginTop = - viewHeight/ 2 + "px";
          x[i].style.marginLeft = - x[i].width / 2 + "px";
        }
        else {
          x[i].style.width = viewWidth + "px";
          x[i].style.height = "auto";
          x[i].style.marginTop = - x[i].height / 2 + "px";
          x[i].style.marginLeft = - viewWidth / 2 + "px";
        }
      }
    }

    window.onload = function() {
      myFunction();
    };

    window.onresize = function() {
        myFunction();
    };


My pager code doesn't work I'm using the following code just to see if the paging works in Drupal 7, but I'm having trouble to set it to work.

$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5);

$headers = array(t('node'), t('Title'));
$rows = array();
$result = $query->execute();

foreach ($result as $record) {
  $rows[] .= array($record->nid, $record->title);
}

$output = theme('table', $headers, $rows);
return $output . theme('pager');

I'm not so good with PHP, so can someone please tell me what am I doing wrong?

Your code is using the string concatenation operator with an array; you need the assignment operator.

$rows[] = array($record->nid, $record->title);

$headers = array(t('node'), t('Title'));
$rows = array();

$nodes = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5)
  ->execute();

foreach ($nodes as $node) {
  $rows[] = array($node->nid, $node->title);
}

return theme('table', $headers, $rows) . theme('pager');

Depending from which function contains that code, it could also be re-written as follows:

$page = array();
$rows = array();

$nodes = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5)
  ->execute();

foreach ($nodes as $node) {
  $rows[] = array($node->nid, $node->title);
}

$page['table'] = array(
  '#rows' => $rows,
  '#header' => array(t('Node'), t('Title')),
  '#theme' => 'table',
  '#empty' => t('No content available.'),
);

$page['pager'] = array(
  '#theme' => 'pager',
);

return $page;


Grant permission for publishing options without full 'administer content' permission As the question says. I'm working on a news site, and authors should be able to create a full piece and be able to chose whether to publish or not. How can you do this?

You can use the Save Draft module. It adds a 'Save as Draft' Button to the node_form for content types, allowing the user to click the 'Save as Draft' button to save the node as a draft. It has it own separate permissions aside from the 'administer content' core permission.


Facet API and Entity Reference Autocomplete I have two content types, with Drupal 7 :

City
Job Offer, with an Entity Reference CCK field named "City" that accept Node Entities of Type City.

I am also using the apachesolr module, with Facet API, and I would like my users to be able to filter the offers by city. However, as I have thousands of cities in the database, the "Links" widget is unusable.

How could I easily integrate the Entity Reference module's autocomplete widget (or  https://drupal.org/project/entityreference_autocomplete, or any other one...) with the Facet API ?

If you are using the Search API Solr with the Facet API, you can create a search index view and use the Facetapi Multiselect along with Chosen to allow your users to select the city via a user friendly drop down box (chosen not only supports typing the search term, but it also allows fuzzy matching). Even if the content type city is not indexed in Apache solr, you can create a relationship in your search view and make the city available to FacetAPI system. You can even expose the city as a filter (if you do not want to mess with facets at all) to your users with a views' relationship.


Drupal 7 commons AJAX bulk operations active queue error Drupal 7 commons site with private trusted contacts enabled. When the accept trusted contact or break contact button is clicked this error appears.
An error has occurred.
Please continue to the error page

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /en/batch?id=6305&op=do StatusText: Service unavailable (with message) ResponseText:
ERROR PAGE - An error occurred while processing views_bulk_operations_active_queue_process with arguments: views_bulk_operations_active_queue_process
I have tried searching and this error seems quite wide with no results.
How do I resolve this?

For me, this error was due to the PHP version being used (5.3). Using PHP 5.4+ resolved it. You may also want to look at https://www.drupal.org/node/1871702 if the PHP version isn't your issue.


filter by taxonomy term = taxonomy term of referencing nodes I have a node type 'hotels'. These nodes have a reference to a vocabulary 'regions' and a field 'hotel_images'.

And I have a node type 'region_page' with also the reference to the vocabulary 'regions'. In these nodes I integrate a view with images of the field 'hotel_images'.

This view should be filtered by the 'regions'.

In case the node (type: region_page) is set to term 'xy' of the vocabulary 'regions' - only images of hotels for which the term 'xy' is also set should be displayed.

How can I do this?

If there is no specific requirement to use taxonomy terms to create the relationship between 'hotels' nodes and 'region_page' nodes, I recommend to use the Entity reference module instead.

In your use case, you likely want to attach an Entity reference field to the 'hotels' content type, that allows the content editor to point to a node of the content type 'region_page'.

If I understand it correctly, you already have a View attached to your 'region_page' content types' display. Assuming you're using the EVA: Entity Views Attachment module, you should add Content: Nid as your contextual filter in the particular View, create a relationship using Entity Reference: Referencing entity and then use this relationship for outputting the field 'hotel_images'.

In this way, when viewing a 'region_page' node, the View will show all images that are stored on 'hotels' nodes that have a reference to the particular 'region_page' node.


I am unable to create a variable in template.php that I later want to use in node--content-type.tpl.php In template.php I have created the following function.

function mytheme_preprocess_node__post_esl_material(&$variables){
  $variables['linking'] = 'yes baby';
}

In node--post-esl-material.tpl.php I am trying to print $linking, but it is not working. The reason I am trying this is because I heard from an expert in Drupal saying:

  Template files are usually used to change the CSS. You do not want to put too much PHP logic here. The PHP logic is typically included in your template.php file.

Therefore the objective, after getting the above code to work, would be to:

Create a $article variable in template.php.
Swap the following code from node--post-esl-material.tpl.php into template.php.

if (empty($content['field_article'])) {
  echo '';
}
else {
  echo '
';
  echo '
ARTICLE
';
  echo '
';
  print render($content['field_article']);
  echo '
';
  echo '
';
}

Print $article in node--post-esl-material.tpl.php and hence, have the PHP logic within template.php.

I am using Drupal 7 with the Stark theme.

These are the steps I would take to resolve (re-trying after each step)

Clear theme registry cache - /admin/config/development/performance - Clear Cache
Use the more general function mytheme_preprocess_node($variables), clear cache, try again

If the more general function works, your issue is likely that you have incorrectly named the template, try:kpr($vars['theme_hook_suggestions']) if you have the Devel Module installed.  If not, you should. Otherwise you can print_r($vars['theme_hook_suggestions']).  Is your template included in there?