How Do i implement an alternative for the Privatemsg Bulkmail module? I'm using the modules Private Message, Invite and Organic Groups in Drupal Commons.

I get listed with trusted content using Views and need to set private Message button for bulk operation just like the Privatemsg Bulkmail module from D6 (for which there is no D7 version yet).

How can I get the Private Message module to work with the VBO module, or any other module, in Drupal 7?

I created an Email system with bulk operation via external mail system.

  "User can invite friends and send email using VBO module "

But I want to send mail/message internal system like the Private Message system for bulk trusted contacts. How can I achieve this?

Looks like there are currently no plans for a D7 version of the Privatemsg Bulkmail module you are referring to. However, I'd use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the VBO module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

Introducing Views Bulk Operations.
More details about VBO settings.
Using Rules componens with more than one parameter.
Using VBO to load list of objects into Rules.

In this specific case;

use Views bulk operations to create the list of your users to be targeted.
use Rules action "Send a message" (provided by Privatemsg module).

PS: yet another great usage of the Rules module, in this case in combination with the Privatemsg module. So I wouldn't worry too much about the Privatemsg Bulkmail module not being available for D7.


internal server error after deleting thumbnails image-style I have an internal server error on my drupal site only when I log in, when logged out everything is fine.

I was having problems with the default image-styles, they would not work (no thumbnail preview) so I created a new style (thumbnail2), deleted the default thumbnail style and replaced it with thumbnail2 style.

Any ideas how I recover from this?

So 2 problems:
1. get access to admin again
2. get default images styles to work

Server log:
Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "view.media.media_page_list" does not exist."

After some googling I saw a similar error on Drupal.org

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

Check the last few comments. It might be related to Media Entity


PHP code contextual filter (arguments) I try to display a list of content with exposed filter in Drupal 7 and Views 3, I create a page and it works, but I also want to display a map with the filter, so I create a block for the gmap and for get the information about the filter I add a contextual filter with php code like this (where province is the name of the field)

return $_GET["province"];

In Drupal 6 it works this method, but in Drupal 7 I receive this error

  Notice: Undefined index: province in eval() (line 1 of /pathtomodule/views/plugins/views_plugin_argument_default_php.inc(49) : eval()'d code).

So where is the error, I return only one argument (I know that I need some control if the code is null, but in this case I )

Notice: Undefined index: province in eval() (line 1 of /pathtomodule/views/plugins/views_plugin_argument_default_php.inc(49) : eval()'d code).

This error occurs when the array key province does not exist. The PHP documentation goes into greater detail - http://www.php.net/manual/en/language.variables.basics.php

  Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name... E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Instead of

return $_GET["province"];

Use isset() logic. Also, you shouldn't be directly accessing $_GET, $_POST or $_REQUEST; best practice is to use drupal_get_query_parameters()

$param = drupal_get_query_parameters();
if (isset($param['province'])) {
  return $param['province'];
}
return NULL;

To address the problem in your comment:

  But i receive: Notice: Undefined offset: 1 in location_handler_argument_location_proximity->query()

This is (for all intrinsic purposes) the same as the undefined index; location_handler_argument_location_proximity->query() is expecting an array with at least two elements (offset 0 and 1), and that method expected, but did not receive an array with two elements. It might not even be getting an array.


Custom view sorting plugin / handler I am trying to create a custom sorting option for view that will sort result on the basis of percentage of 2 fields.

field 1 = node__field_funding_amount
field 2 = node__field_funding_goal

and i am trying to do something like below

$percentage = "round(( $this->tableAlias.$this->realField/node__field_funding_goal.field_funding_goal_value * 100 ),2)";
    $this->query->addOrderBy(NULL,
      $percentage
    );

Full code is here
1:- code in views.inc

function crowdfundingproject_views_data_alter(array &$data) {
  $data['node__field_funding_amount']['views_cfp_almost_full'] = array(
    'title' => t('CFP Almost Full'),
    'group' => t('Content'),
    'help' => t('Project almost full'),
    'field' => [
      'id' => 'almost_full',
      'click sortable' => TRUE,
    ],
    'sort' => [
      'field' => 'field_funding_amount_value',
      'id' => 'funding-percent',
    ],
  );
}

2:- Code in sorting class

use Drupal\views\Plugin\views\sort\SortPluginBase;

/**
 * Basic sort handler for Events.
 *
 * @ViewsSort("funding-percent")
 */
class FundingPercent extends SortPluginBase {

  /**
   * Called to add the sort to a query.
   */
  public function query() {
    $this->ensureMyTable();
    $percentage = "round(( $this->tableAlias.$this->realField/node__field_funding_goal.field_funding_goal_value * 100 ),2)";
    $this->query->addOrderBy(NULL,
      $percentage
    );
  }

}

But it's showing me column not found error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'node__field_funding_goal.field_funding_goal_value' in 'field list': SELECT node_field_data.created AS node_field_data_created, node_counter.totalcount AS node_counter_totalcount, node__field_funding_end.field_funding_end_value AS node__field_funding_end_field_funding_end_value, node_field_data.nid AS nid, ABS(round(( node__field_funding_amount.field_funding_amount_value/node__field_funding_goal.field_funding_goal_value * 100 ),2)) AS absroundnode__field_funding_amountfield_funding_amount_ FROM {node_field_data} node_field_data LEFT JOIN {node_counter} node_counter ON node_field_data.nid = node_counter.nid LEFT JOIN {node__field_funding_end} node__field_funding_end ON node_field_data.nid = node__field_funding_end.entity_id AND node__field_funding_end.deleted = :views_join_condition_0 LEFT JOIN {node__field_funding_amount} node__field_funding_amount ON node_field_data.nid = node__field_funding_amount.entity_id AND node__field_funding_amount.deleted = :views_join_condition_1 WHERE (node_field_data.status = :db_condition_placeholder_2) AND (node_field_data.type IN (:db_condition_placeholder_3)) ORDER BY node_field_data_created DESC, node_counter_totalcount DESC, absroundnode__field_funding_amount.field_funding_amount_ ASC LIMIT 6 OFFSET 0; Array ( [:db_condition_placeholder_2] => 1 [:db_condition_placeholder_3] => crowdfunding_project [:views_join_condition_0] => 0 [:views_join_condition_1] => 0 )

There is an error in your SQL so you're getting the column not found error.  If you break up your query, you should be able to get it.
Since this question has 1k views and no answers, and I just had to do this myself, here are some helpful resources for anyone looking to build their own Views custom sort plugin in Drupal 8/9.
First, this blog post on Medium by Oleksandr Trotsenko has a detailed tutorial on writing custom sorts and filters for Views.  The example is to take a product weight and weight unit fields to sort all products by weight, regardless of whether that weight is recorded in lb or kg. There are code examples for hook_views_data() and the views sort plugin.
There's another tutorial by Clare Ming on how to extend a datefield to add a sort that shows dates in the future first, and then dates in the past in reverse chronological order. It also has code examples.


How do I do a file upload with other form data in Drupal 6? I have this in my form function:

$form['#attributes'] = array('enctype' => 'multipart/form-data');
... other form fields
$form['form']['form_file'] =  array (
    '#type' => 'file',
    '#name' => 'form_file',
    '#attributes' => array ('class' => 'textarea_crmform'),
 );

and when I call file_save_upload in my submit function, I am doing this:

if ($file = file_save_upload('form_file'))

But it never gets into the above if statement.

My guess is that there's an error. Have you looked at your watchdog log? Is the temporary directory setup and writable by the web server?


Where are the "Replacement Patterns" (Tokens) in "Set Data Value" in Rules? Most of the actions in Rules allow you to use tokens, but seemingly the most obvious place where this would be useful, "Set a data value," does not seem to support it. Am I missing something? It seems like it would be pretty trivial to add support for this, but I can't find in the code why, for example, the "title" field in "create a new entity" supports tokens, but "Set a data value" does not. Thanks!

It depends on the type of the selected target data whether tokens can be used for the value or not.

For example if the target is a simple text field (e.g. node:title) then the value can be specified with tokens. On the other hand, if the selected target is for example an entity (e.g. node:field-tags:0), then token input is not possible.

When working with formatted text, it is necessary to drill down to the value column of the field. E.g. for the node body, specify node:body:value.


How to completely hide a table header in views? In views when you use the table layout and don't select labels it still creates an empty header, for example:

I can hide it with CSS. What would I have to do to access the render array and unset the element before the HTML is generated?

Is there any other way to remove the  tag?

Implement hook_preprocess_views_view_table(&$vars) in theme or custom module and set $vars['header'] to empty array. Template completely ignores thead when header variable is empty. For example:

function MY_THEME_preprocess_views_view_table(&$vars) {
  if ($vars['view']->name == "my_view") {
    $vars['header'] = array();
  }
}


Prepare Drupal to be multilingual in the future I am building a Drupal website with only one language (Italian first) but there might be more languages in the future. This website will use also DrupalGap to create an app.
Editors don't need backend Italian interface.

So these are the scenarios I thought about:

Case one:

Install Drupal with English as default.
I will NOT enable Locale module.
All machine names (Content types, vocabularies, views etc..) will be in English.
Labels will in Italian.
Content and term will be created in Italian.
Views page title and views block title will be in Italian.

After few months the website may be translated in English so, the steps will be:

Enable locale.
Install Italian language.
Install Entity translation i18n etc...
Make entities translatable.
Bulk update all nodes and terms to be Italian as original language.
Revert all Italian labels into English and use string translation to translate it in Italian.

Case two:

Install Drupal with Italian as default
All machine names (Content types, vocabularies, views etc..) will be in English.
Labels will in Italian.
Content and term will be created in Italian.
Views page title and views block title will be in Italian.

After few months the website may be translated in English so, the steps will be:

Install Entity translation i18n etc...
Make entities translatable.
Bulk update all nodes and terms to be Italian as original language.
Translate strings from Italian to English.

In terms of extendability and usability, which approach should I use at the beginning?

Let me know if you have any question.

Thanks in advance.

I think the best approach is something similar to your first one.

Install Drupal in English as defaults
Configure your environment for multilingual at the beginning.
Enable Italian Language
Set Italian to default language
When you create entities(Users, Content types, Etc..), configure everything at the beginning. Otherwise you might forget things later.
Enable multilingual support only for other pages excepting admin pages @ admin/config/regional/i18n/select (Under "ENABLE FOR SPECIFIC PAGES" set all pages except "admin/*")
Then do everything in Italian for Italian until you need English language stuffs.

Good luck.


Feeds importing unique nodes over and over I'm trying to import events to a calendar from an external ics..
I installed the Calendar module with the Feeds module. Unfortunately it creates the whole time new nodes. Even if the UID is unique (mapped to field field_gimme_uid) in the node. Update nodes is setted 'on'. I have checked everything but everything seems alright. The unique field is correctly imported (and the same for multiple nodes)..

I have a contenttype "Evenement" with the following fields:

Evenement (title)
Datum (field_event_date) Date
Gimme-UID (field_gimme_uid) Text

I have a feed that maps the ics import to the nodes

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'ics_importer';
$feeds_importer->config = array(
  'name' => 'Gimme Agenda',
  'description' => 'Gimme agenda importeren van het account website',
  'fetcher' => array(
    'plugin_key' => 'FeedsHTTPFetcher',
    'config' => array(
      'auto_detect_feeds' => 0,
      'use_pubsubhubbub' => 0,
      'designated_hub' => '',
      'request_timeout' => '',
      'auto_scheme' => '',
      'accept_invalid_cert' => 0,
      'cache_http_result' => 1,
    ),
  ),
  'parser' => array(
    'plugin_key' => 'DateiCalFeedsParser',
    'config' => array(
      'indefinite_count' => '52',
      'indefinite_message_display' => TRUE,
      'until_not_utc' => FALSE,
      'skip_days' => NULL,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => '1',
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'SUMMARY',
          'target' => 'title',
          'unique' => 0,
          'language' => 'und',
        ),
        1 => array(
          'source' => 'DTSTART',
          'target' => 'field_event_date:start',
          'unique' => FALSE,
          'language' => 'und',
        ),
        2 => array(
          'source' => 'DTEND',
          'target' => 'field_event_date:end',
          'unique' => FALSE,
          'language' => 'und',
        ),
        3 => array(
          'source' => 'UID',
          'target' => 'field_gimme_uid',
          'unique' => TRUE,
          'language' => 'und',
        ),
      ),
      'insert_new' => '1',
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
      'bundle' => 'evenement',
      'language' => 'und',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '900',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 1,
);

My modules:

Drupal 7.56
Calendar module 7.x-3.5
Date 7.x-2.10
Date iCal 7.x-3.9
Feeds 7.x-2.0-beta4

My ICS that I use to import can you find here

Why is it importing the whole time the same nodes?

My bad! The "Unique" option in the feeds module isn't working without the module "Field Validation". I added an unique rule to the contenttype "evenement" and now it works like a charm!


How to override/enhance file_save_upload() function of file.inc? For a specific requirement, wherein whenever an image is uploaded to a particular field of a node, a watermark should be added to it, I made changes in file_save_upload() function of file.inc

if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) {
    form_set_error($source, t('File upload error. Could not move uploaded file.'));
    watchdog('file', 'Upload error. Could not move uploaded file %file to destination    %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
   return FALSE;
}
else{
    process_image(drupal_realpath($file->uri));
}

But these changes will be lost whenever Drupal core will be upgraded. So what is the best way to override/enhance file_save_upload() function of file.inc or any function in the core drupal?

Drupal runs on a Never hack core policy.

The Drupal way to add a watermark to image is to use hook_form_alter to modify the form submit and do your things with $form_state['values']['YOUR_FIELD']

Eg:

function mymodule_form_alter(&$form, $form_state, $form_id)  {
  switch ($form_id)  {
   case 'YOURFORMID':
     $form['#submit'][] = 'yourModule_yourform_submit';
     break;
   }
 }

function yourModule_yourform_submit($form, &$form_state) {
    // do what you want to do
    // use $form_state['values']
}

Or Try ImageCache Actions module.

  Watermarking - a much requested addition that enables you to place any
  image anywhere over a source picture, with alpha transparency


How to nest a field collection? How to nest Field Collections in Drupal 8?

I have Field Collection installed and working fine. What I want to achieve is that for example, I'll have a box on the front end which may contain 6 tabs of content, or two boxes each containing 3 tabs.

First part is working: I have a 'tabs' Field Collection with which I can 'add another item' (tab).

For the second option I need a 'box' Field Collection that contains nothing but the 'tabs' Field Collection.

Using the Field collection module in Drupal 8 seems to NOT be a good idea anymore. It currently only has an alfa1 release from April 2016). Instead you may want to try to use Paragraphs instead, as suggested also on the Field collection project page, i.e.:

  Paragraphs is likely to replace field collection for Drupal 8. Field collection is on its way to being deprecated. It is recommended to use paragraphs instead of field collection for Drupal 8 projects.


How can I share cache with multiple users and roles? In my custom module, I define a custom block that performs an expensive operation:

/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data();
  $agent_number = get_agent_number_from_context();
  return [
    '#theme' => 'my_custom_module',
    '#cache' => [
      'keys' => ['my_block', 'full_version', $agent_number],
      'tags' => ['my_custom_module'],
      'max-age' => 86400,
    ],
  ];
}

The caching works except when another user views the block or a user with a different role view the page; it creates a new cache item. Is it possible to have cache only one time for multiple users/roles?

Edit

I tried the following (ended up using route context just to not add another variable to my problem):

/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data();
  return [
    '#theme' => 'my_custom_module',
    '#data' => $data,
    '#cache' => [
      'contexts' => ['route'],
      'tags' => ['my_module'],
      'max-age' => 86400,
    ],
  ];
}

Noticed when I had the block using Layout Builder via Page Manager, no item got added to the cache_render table (that might be a separate issue).  When I added the block on default Drupal Block Layout I noticed that it still created a new cache record for every user.  For example:

User 1 navigated to: /my-account/A123 and the following record got added to the cache_render table:

cid

entity_view:block:mycustomblock:[languages:language_interface]=en:[route]=entity.node.canonical7ccb4f15749b8c9e759f0016bfc863bd5e6bef88ea0a9dfe7b1cbe2687d30b32:[theme]=my_theme:[url.site]=http://mysite.test:[user]=1

tags

block_view config:block.block.mycustomblock config:user.role.administrator config:user.role.authenticated my_module rendered user:1

User 72 navigated to: /my-account/A123 and the following record got added to the cache_render table:

cid

entity_view:block:mycustomblock:[languages:language_interface]=en:[route]=entity.node.canonical7ccb4f15749b8c9e759f0016bfc863bd5e6bef88ea0a9dfe7b1cbe2687d30b32:[theme]=my_theme:[url.site]=http://mysite.test:[user]=79

tags

block_view config:block.block.mycustomblock config:user.role.agent config:user.role.authenticated my_module rendered user:79

With using contexts, I am still seeing it create a new record for every user.

Edit 3

I think my test form Edit 2 is invalid because I was trying to make the block work outside of page manager but I needed the context from page manager so it was using the logged-in users. Long story short, I need to figure out why context caching isn't working (although key caching is working) when using Page Manager or Layout Manager.

Caching is shared with multiple users or roles by default, unless you add a cache context like user or user.roles.

Otherwise it's hard to tell what the code in the question wants to achieve.

If it wants to set block cache keys, then you can't do it from here
and you don't need to. They're set automatically.
get_agent_number_from_context() should probably be a custom
cache_context.agent_number which you then could add to the block
build array to vary the cached block by this variable:

/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data();
  return [
    '#theme' => 'my_custom_module',
    '#data' => $data,
    '#cache' => [
      'contexts' => ['agent_number'],
      'max-age' => 86400,
    ],
  ];
}

How to create a custom cache context:
https://www.drupal.org/docs/8/api/cache-api/cache-contexts#recognize-discover-create
If it wants to cache the expensive data on its own (which
makes sense if you want to reuse the rendered result in other places
not necessarily blocks), then you need to execute
get_expensive_data() in a #pre_render callback to avoid that it
gets executed in case of a cache hit. See
https://dev.acquia.com/blog/drupal-8-performance-render-caching

Edit 1:
The cids you have added to the question contain a cache context for the user. I can't tell by the code shown so far how it ends up in your block. But there is also a cache tag of the user, so there has to be some code retrieving and rendering the current user.

Edit 2:
Assuming the theme is the same there is also a default user.permissions cache context for all render caching which probably kicks in now that user is removed. See https://www.drupal.org/project/drupal/issues/2493033


Insert images with Media I am using Media and Wysiwyg with CKEditor to insert images in the post editing field, and for some reasons I keep getting this code instead of my images.

Does anyone know how to fix it?

[[
  {
   "type" : "media",
    "view_mode" : "media_large",
    "fid" : "412",
    "attributes" : {
      "alt" : "",
      "class" : "media-image",
      "typeof" : "foaf:Image"
    }
  }
]]

[[
  {
    "type" : "media",
    "view_mode" : "media_large",
    "fid" : "395",
    "attributes" : {
      "alt" : "",
      "class" : "media-image",
      "typeof" : "foaf:Image"
    }
  }
]]

I fixed it; you have to go into Administration » Configuration » Content authoring » Text formats and check the box Converts Media tags to Markup.


Drupal 7 in subfolder behind reverse proxy, login not working I'm trying to run a Drupal 7.12 site behind an nginx reverse proxy, so that it shows up in a sub-folder to the primary domain (company.com).

Nginx is handling all incoming traffic to http://company.com, and Drupal is installed on another server with Apache. We want the content from Drupal to show up under http://company.com/drupal/.

For nginx, there is a proxy_pass specified like this:

  location /drupal/ {
    proxy_pass http://drupal.company.com/;
  }

For Drupal, I have set

$base_url = http://company.com/drupal;

This works fine to browse the content, Drupal is generating correct links, etc.

But when I try to login /drupal/user, I get the login form, but the action parameter for the form is set to "/user" - it seems that Drupal is forgetting to apply the base_url here.

Any ideas how to solve this issue? Help appreciated...

As I understood, the #action on the page /user is generated by request_uri, the default action of each form, except for few form that are block (check if the user_login block has the same problem).

I can advise you, to check your PHP config in Report -> Status report and then click on the PHP version an try to find the REQUEST_URI information, this can be different from what you are expecting (I guess /drupal/user).

To fixe it, I see only two solutions, submit an issue (or check if that issue already exists) or the second its to use the hook_form_alter and replace the #action by something like that.

$form['#action'] = url(current_path(), array('external' => FALSE));


Get the alt for the image on views twig I've got an image field, in which I'm showing the image using url by setting the relationship for that field on 'Advanced' tab to get the url of the field.

I'm getting the url of the field as

{% set image = file_url(fields.uri.content|striptags|trim) %}

I would like to know how to get the alt of the image on views-view-fields-view-machine-name.html.twig.

A simple solution is to add image again as a field and Rewrite Results:

Now in your template:

... alt="{{ fields.field_image_1.content|striptags }}" ...


views_pre_render add class item to a row When pre-rendering a view row is there a way to add an HTML class into a single row of the markup, allowing me to add a new background colour to the event item highlighting its importance? This is for the calendar module monthly view

For example,

Below the is the what I have so far.

function pnc_views_overrides_views_pre_render(\Drupal\views\ViewExecutable $view)
{
      if ((int)\Drupal::currentUser()->id() === 1) {
        foreach ($view->result as $key => $value) {
          try {
            $field_result_value = $value->_entity->field_display->getValue();
            if (isset($field_result_value[0]) && (int)$field_result_value[0]['value'] === 1) {
              // add a class to the change the background color to hi-light its importance
            }
          } catch (Exception $e) {
            \Drupal::logger('viewoveride_pnc_cal_views_overrides')->error($e->getMessage());
          }
        }
      }
}

Because you do not want to alter some data, you should use a preprocess function for this. Check this out:

function MYMODULE_preprocess_views_view_unformatted(&$variables) {
  $view = $variables["view"];
  $viewId = $view->id();
  if($viewId == 'my_view_id'){
    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {
      $important = $row['content']['#row']->_entity->get('field_result_value')->getString();
      $custom_row_class = 'views-row-' . $important;
      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }
  }
}


Should Text Format: "Full HTML" create a safe value? When I am rendering fields I noticed that if the user selects "full html" as the WSYWIG text format on a "long text" field, a safe value is not created.
For example the array would be:

value (String, 14 characters )
test

format (String, 9 characters ) full_html

But if "Filtered HTML" input selected it would be:

value (String, 14 characters )
test

format (String, 9 characters ) full_html
safe_value (String, 4 characters ) test

Settings to Full HTML seem to have no effect.

What controls whether a safe value is created?

The core text module does. This logic is driven by the text module's text_field_load(), an invocation of hook_field_load(). When the module loads text fields it looks up the filters used for the text format and sees if it's cacheable (i.e. if it saves to safe_value).

In your case, the logic is being triggered by toggling the filtered_html / full_html formats. Because raw HTML is potentially unsafe, it's not stored in the save_value cache.
`


Conditional clauses with Entity field Query I have a syntax issue on using conditional clauses with EFQ, but the documentation on drupal.org is a bit unclear for me. I have google the whole Internet for this with no results at all. My hook implementation is based on another drupal.stackexchange question

The code works for a single ->fieldCondition but when I try to implement the hook below,

    $query = new EntityFieldQuery();
    $entityFormSubmissionIds = $query->entityCondition('entity_type', 'entityform')
      ->addTag('or')
      ->execute();

  /**
  Implements hook_query_TAG_alter

  @param QueryAlterableInterface $query
  */

function mymodule_query_or_alter(QueryAlterableInterface $query) {
 $or = db_or()->condition('field_a',$term->tid)
       ->condition('field_B', $term->tid);
    ->condition($or)
    ->execute();

Fatal error: Call to undefined method DatabaseCondition::execute()

In the alter hook, you should not be calling execute(). You don't want to run the query at this point, just change it.

function mymodule_query_or_alter(QueryAlterableInterface $query) {
 $or = db_or()->condition('field_a',$term->tid)
       ->condition('field_B', $term->tid);
 $query->condition($or)
}


Form states expanded or collapsed not working I cannot get this to work. Visible/Invisible works for me but this doesn't. Have I misunderstood anything?

    $form['items']['delivery_address'] = array(
    '#type' => 'fieldset',
    '#title' => '',
    '#collapsed' => true,
    '#collapsible' => true,
    '#states' => array(
        'expanded' => array(
            ':input[name="add_address"]' => array('checked' => false),
            ':input[name="delivery_type_radios"]' => array('value' => 0),
        ),
    ),
);

This makes it work:

   '#title' => 'bleh',

It kinda makes sense...


Slideshow on the pages I am looking for a method to put différents slideshows on different pages. I mean every pages must have his own slideshow. Is it possible?

Assuming you're using the Views Slideshow module, for each slideshow you create, you also get a corresponding block that you need to position in an appropriate region.

So say you have 3 slideshows, ie ShowA, ShowB and ShowC, and you want to show them like so:

Show A on page with node id = X.
Show B on page with node id = Y.
Show C on page with node id = Z.

In this case, all you need to do is to adapt the "Visibility settings" (pages) for each block like so:

For the block related to ShowA, only show this block on page node/X.
For the block related to ShowB, only show this block on page node/Y.
For the block related to ShowC, only show this block on page node/Z.

Possible enhancements

Even though the above should be sufficient to answer your question, there are all sorts of enhancements to the above approach you may want to consider:

Use a content type (eg "Slide"), to create slides that you want to be shown in a slideshow. And optionally also add an extra field to that content type to identify in which slideshow (ShowA, ShowB, etc) you want an extra slide to be shown. And/or add another field to indicate some type of sequence (like slide nr) of those slides to be shown.
Use the Rules block visibility module to make the visibility of the blocks more dynamic, by using some Rules logic to yes/no show a specific slideshow-block. Refer to "How to stop a Views block from displaying to admins, such as user/1?" for way more details about how to use Rules block visibility.


List of parent nodes with a sublist of child referring nodes on a single content type I have a content type Article with an Entity Reference to himself.

Demo content:

Article 1 -> No ref
Article 2 -> No ref
Article 3 -> Ref to 1
Article 4 -> Ref to 1
Article 5 -> Ref to 2
Article 6 -> Ref to 1, Ref to 2

Step 1: I want a View list to display every node that doesn't referring to anybody. So: Filter criteria: RefField = Is empty works nice and the results:

View list results:

Article 1
Article 2

Step 2: Display the title of every node that is referring to the ‘parent’

View list results:

Article 1
   Article 3
   Article 4
   Article 6
Article 2
   Article 5
   Article 6

I'll break my head! The same architecture works fine if I have 2 content types, but I can't figure out with a single content type.

Edit: When I create a relationship: Entity Reference: Content referencing Content from field_Article_Ref and then add a Field and use the above relationship: (Content referencing Content from field_Article_Ref) Content: Title (Title). It displays the childs but the results are not grouped (even I use query settings->Distinct) and looks like:

Article 1
   Article 3
Article 1
   Article 4
Article 1
   Article 6
Article 2
   Article 5
Article 2
   Article 6

How I can group the results?

After that point go to Format->Settings->Grouping field Nr.1 and group by the desired field.

Recapitulation

Relationships->Add->Entity Reference: Referencing entity of the Field that reference to himself. Also check Require this relationship.
Fields->Add->Content: Title.
Fields->Add->Content: Title and use the relationship.
Format->HTML list (makes a wrapper element).
Format->Settings->Grouping field Nr.1->Content: Title.
Fields->Edit Content: Title->Exclude from display (it will be displayed by the grouping).

PS Also check the Views Field View module mentioned by @tenken here


How to export Group module entities with the Features module? I'm trying to find a way in D7 to export groups created with the Group module using the Features module. I have managed to export Group Types and Group Roles, but haven't found a way of doing the same with Groups.

I need to do this to create an initial set of groups when the feature is enabled.

Any help greatly appreciated!

Have a look at the UUID Features Integration module, which provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. It depends on the UUID and Features module. Some more info aboout this module(from its Community documentation):

  Drupal's core entities are supported by default within the UUID module, but if you want to export content contained within custom entities, you will have to implement UUID support using their API.

The challenge with the UUID Features Integration module is that its documentation is not complete (yet). So for adding UUID Features support for custom content entities (such as Groups), refer to the module's includes/ folder and use one of the existing implementations as an example.

2 more documentation issues that may be of some help also:

Issue # 2310115.
Issue # 2236497.


How do I unset a block? I just started creating a Drupal 8 theme.

For example in Drupal 7 if I want to remove the breadcrumb, I just need to remove this line of code <?php if ($breadcrumb) print $breadcrumb; ?> from the page.tpl.php.

In Drupal 8 I removed {{ page.breadcrumb }} from the page.html.twig and I still seeing the breadcrumb. So not sure how to remove or unset these kind of blocks in Drupal 8.

Yes, what you are seeing is the render cache. If you are developing a theme, you likely want to disable render caching and enable twig debug. See sites/example.settings.local.php for instructions on how to do that.

That said, breadcrumbs, like almost everything else, is a block now. Blocks are configuration. If you don't want a block, just remove that block in the UI. If you just remove it in the template, Drupal still needs to load and prepare that block for rendering as it cannot know the template doesn't print it.

And if you don't display the region (you always display regions with 0-N blocks, not directly blocks in page template), you should also not define it as an available region so that the user/site admin knows that he can't place blocks there.


How do I tweak an image field markup? I have an image field that is set to link to content. Drupal makes this markup:

Now I need to tweak the markup and add some styling, for example:

I want to add the inline CSS in this way because the page is for emailing.

What would be the best way to do this? I have tried:

Putting the markup into field--myfield.tpl.php and inserting variables, but the $items array doesn't give me clean image file or target URLs.
Using the Custom Formatters module, but it gives me AJAX errors for some reason and not sure it would do the job anyway.
I could use a preprocess function in template.php, but I am hot sure how.

For link, it's easy to provide in field--myfield.tpl.php:

$items[0]['#path']['options']['attributes'] = array('style'=>'border-style: none !important;');

But image doesn't have this, so you can miss upper code and rewrite formatter in template.php (add attributes there).

/**
 * Returns HTML for an image field formatter.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: An array of image data.
 *   - image_style: An optional image style.
 *   - path: An array containing the link 'path' and link 'options'.
 *
 * @ingroup themeable
 */
function YOURTHEMENAME_image_formatter($variables) {
  $item = $variables['item'];
  $image = array(
    'path' => $item['uri'],
    'alt' => $item['alt'],
  );
  // Do not output an empty 'title' attribute.
  if (drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image); // Here you should add attribute, check that it's your field.
  }
  else {
    $output = theme('image', $image);
  }

  if (!empty($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = $variables['path']['options'];
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);  // Here you should add attribute, check that it's your field. Or just take upper code.
  }

  return $output;
}


How do you create a view in which users can assign tasks to themselves? What I want to do.

A user clicks on his profile page.
A view displays that shows a list of completed tasks.
A task consists of a list of check-boxes (a checklist) and a "pending
and finished" dropdown.
The user should also be able to create a task for himself, selected
from a list of checklists.

This is my solution so far

Create a content type "checklists"
create a role reference field
create the checkbox field
create a view with CONTEXTUAL FILTERS to show the tasks assigned to
the user

Ive also tried a few modules

checklist
QA Checklist
SEO Checklist

But they dont seem to have the features i want.

Am i going in the right direction?

  Flags also looks promising - It looks like you can create a flag(button:create task) and then use actions or rules to create the node and reference the user automatically

Please go through the following modules,

To do list for Drupal 6 only

  Offers a content-type for a simple To do list. It can be used for anything that needs to be done: getting milk at the store, reminding yourself to update a profile, telling your users to vote on a poll by a certain date...

and myTinyTodo - Available for D6 & D7

  A simple way to manage your todo list. This module is based on myTinyTodo.

Otherwise you can do the same system with your current approach


commerce feeds product import not showing up I imported a file with 5 fields UPC-> SKU(Unique), Product Description -> Title, Unit Price -> Price Amount and 2 custom fields for wood type and knife number the import process says it created 21 products and I can find these products through phpmyadmin in various places including commerce_product, commerce_product_revision.

There are also a number of entries of type commerce_product in the field_revision_field_product_category table where as the types of my already created content are node in the same table. They all have a price of 0  but are not showing up in the product listing.

I'm using commerce kickstart 2.0, commerce feeds 1.3, feeds 2.0 alpha 7 and have feeds tamper 1.0 beta 4.
I have run cron and flushed all caches.

I tried this in a fresh install of Commerce Kickstart but the products are still not showing up in the view products screen.

I also created a barebones Drupal 7 install with commerce and feeds/commerce feeds and other required modules and the products seem to be created just fine.

Yesterday on #drupal-commerce in IRC, someone had a similar question. It appears that the "title" module may be interfering with commerce_feeds. Try disabling the "title" module and see if that helps your import woes.


Saving a line-item object Can anybody explain me why the right way for programmatically saving a line item object with Drupal Commerce is the following one?

commerce_line_item_save($item);
entity_get_controller('commerce_line_item')->resetCache(array($item->line_item_id));

I wish to be smarter after knowing that.

That isn't the right way to save a line item. All that second line does is remove the item from the entity controller's static cache.

As CommerceLineItemEntityController::save() already manipulates the static cache directly to ensure the updated entity is in it, the second line is redundant. All it does is force unnecessary database usage if/when the same line item is loaded again in the same request.

This is all you need to create or update a line item:

commerce_line_item_save($item);

Remember that $item is an object, so doesn't need to be passed by reference as you mentioned in the comments.


Should the maintenance template be used when the database API raises an exception? I have created a maintenance-page.html.twig template for my site.

The settings.php file says:

  This applies when the site is explicitly set to maintenance mode through the administration page or when the database is inactive due to an error.

However, on my site, this only works if I explicitly turn on maintenance mode. If I intentionally break access to my database by changing the password I get a page with a PDO error, not my maintenance page.

Is this a bug, or am I missing something?

This looks to be the case of where the documentation is out-of-date. That comment has been around verbatim since D7. D8 doesn't produce a themed maintenance page like D7.

When looking at _drupal_log_error(), you can see that unless Drupal is going through the install process, a fatal error will output a bare error message with a 500 status then exit:

if ($fatal) {
  // We fallback to a maintenance page at this point, because the page generation
  // itself can generate errors.
  // Should not translate the string to avoid errors producing more errors.
  $message = 'The website encountered an unexpected error. Please try again later.' . '<br />' . $message;

  if ($is_installer) {
    // install_display_output() prints the output and ends script execution.
    $output = array(
      '#title' => 'Error',
      '#markup' => $message,
    );
    install_display_output($output, $GLOBALS['install_state'], $response->headers->all());
    exit;
  }

  $response->setContent($message);
  $response->setStatusCode(500, '500 Service unavailable (with message)');

  $response->send();
  // An exception must halt script execution.
  exit;
}

Whereas in D7, _drupal_log_error() passes through a themed maintenance page:

if ($fatal) {
  drupal_set_title(t('Error'));
  // We fallback to a maintenance page at this point, because the page generation
  // itself can generate errors.
  print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));
  exit;
}


How to compare date from table with variable using db_query? I am trying to retrieve all records from a specific date, given the variable $date. I am using db_select and ->condition (due to a lot of joins).

I like to do something like:

->condition("`tableName`.`field_date_value` )", $date)

That doesn't return anything. Perhaps due to different time because field_date_value has a time set and $date hasn't. I looked into using a SQL functions like DATEDIFF, but it doesn't work for me.

How do I do this?

You are going to need to insure that the format of your $date variable is formatted exactly the same as the format of the date value in your database (field_date_value). For example, if your database is storing its date values in unixtime, then your $date variable needs to be unixtime. If your field_date_value field is storing mm:dd:yy hh:mm:ss, then your $date variable needs to reflect this same format accordingly. Refer to date() to formate your $date variable the appropriate way.

Once you've formatted your $date variable to the same formate of your sql data, you can run a condition method like this:

->condition("tablename.field_date_value", $date, ">=")

This will query for everything equal to or greater than the specified $date value.


Add taxonomy field to a bundle programmatically I'm currently developing a module which provides a content type called "Structural machinery" . This type should also provide a taxonomy term based on different manufacturers providing the machine (eg CAT or Komatsu) , I know how to create a taxonomy vocabulary programmatically but the question is how to attach a taxonomy field to my bundle.

this is the code used to implement the taxonomy term :

$term = new stdClass();
$term -> name = $t('Manufacture');
$term -> machine_name = 'manufacture';
$term -> description = $t('Description');
$term -> hierarchy = 2;
$term -> module = 'construction_machinery';
$term -> weight = 1;
taxonomy_vocabulary_save($term);

First create your field

$field_name = 'field_manufacture';

$field = field_info_field($field_name);
if(!$field){
  $field = array(
    'settings' => array(
      'allowed_values' => array(
        0 => array(
          'vocabulary' => 'manufacture',
          'parent' => '0',
        ),
      ),
    ),
    'field_name' => $field_name,
    'type' => 'taxonomy_term_reference',
    'module' => 'taxonomy',
    'active' => '1',
    'cardinality' => '1',
  );
  field_create_field($field);
}

Then create your instance(s)

$node_types = array('page','whatever');
foreach($node_types as $type){

  $instance = field_info_instance('node',$field_name,$type);
  if(!$instance){
    $instance = array(
      'label' => 'Manufacture',
      'widget' =>
      array(
        'weight' => 3,
        'type' => 'options_select',
        'module' => 'options',
        'active' => 1,
      ),
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => $type,
    );

    field_create_instance($instance);
  }

}

if you do var_export the return from field_info_field and field_info_instance of an existing field, you can see how the field arrays are structured & use this structure when creating new ones.


Can't visit site after switching on Language Detection 'Session' in combination with Ip to locale My site is in a kind of a loop? I can't login anymore and visit the site? http://landberg.at/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/nl/en/user

What do i have to do. Its a combination with IP to local and Language Detection 'Session'

How do i disable Language Detection 'Session' from mySql database manually?
i already disabled IP to local module from database...

I really need my site back as soon as possible.

Thanks!

Update:

I solved it by entering ?language=en behind my URL. After this i was able to login again.

I solved it by entering ?language=en behind my URL. After this i was able to login and visit my site again.


How to make uploaded file permanent to node without node submit My module automatically save new empty node when user create new node and redirect to edit this node. Now, is it possible to make uploaded file on _node_edit form without submitting form?

edit:
When user visit "node/add/article" for example, my module save new node type article and redirect user to "node/NID/edit" to edit this node. In node have fields type "image" and "file". User upload image and file.
Now, how to alter their (ajaxified) upload process to make this files permanent to node without click on "Save" button on node edit form?

You could try the autosave module, which allows automatic saving of the node form via ajax while the user is editing the form.

If it doesn't do exactly what you are after it would be a great place to look for ideas on how to code it yourself.

Probably if it doesn't do exactly what you want the easiest path might be to make a patch for that module to add what you need, instead of writing something from scratch.


Can a batch process be stopped Is there a way to force a batch process to stop if some kind of error occurs?  In particular, I have a batch that starts with saving a record to a database. Each subsequent batch operation depends on the database insert working correctly.  I'd like to force the batch to stop if the first batch fails.

The batch is called like this

$batch = array(
    'operations' => $operations,
    'finished' => 'mymodule_batch_finished',
    'title' => t('Merging records'),
    'init_message' => t('Starting processing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Processing has encountered an error'),
    'file' => drupal_get_path('module', 'mymodule') . '/forms/mymodule.inc'
);

where $operations is the array of functions to call.

Each function uses PDO to update the database.  I'm trying to figure out how to stop the subsequent $operations from being called if the query in the current operation fails.

try {
  $sth = $dbh->prepare($sql);
  $sth->bindParam(':newid',$new_id,PDO::PARAM_INT);
  $sth->bindParam(':id',$id,PDO::PARAM_INT);
  if($sth->execute()) {
    $context['results']['[] = $sth->rowCount();
  }
  else {
    // TODO: stop processing due to an error
  }
}
catch(PDOException $e) {
  // TODO: stop processing due to an error
}

If an error occurs, I want to bypass the remaining operations and go straight to mymodule_batch_finished

Inside your batch callback, where you do the batch work, you should be able to set $context['finished'] to 1, and that will signal to Drupal that the batch is complete.

So, in your case:

$error = FALSE;
try {
  $sth = $dbh->prepare($sql);
  $sth->bindParam(':newid',$new_id,PDO::PARAM_INT);
  $sth->bindParam(':id',$id,PDO::PARAM_INT);
  if($sth->execute()) {
    $context['results'][] = $sth->rowCount();
  }
  else {
    $error = TRUE;
  }
}
catch (PDOException $e) {
  $error = TRUE;
}
// If there was an error, immediately complete the batch process.
if ($error) {
  $context['finished'] = 1;
}

And, even better, you can pass in an error message in the $context as well, which you can check for in your finished callback, then display to the end user in case of failure.

If you want to immediately stop processing anything in other callbacks in the $operations list, you might also need to check for a static variable at the beginning of each callback, and skip the callback if it's in an error condition. You could try using variable_get/variable_set, or some other mechanism that persists between page requests. This would definitely be a hackish/last-resort solution, though!

See also:

How does the batch API work internally?
Batch operations API documentation


Storing Drupal form values when using tablesort or paging I have a custom form where I use a tableselect, and a couple of textboxes and checkboxes. The query for the tableselect is extended using TableSort and PagerDefault.

I noticed that when the user sorts a column, or goes to another page (using the pager), Drupal does a simple redirect which wipes all values in the textboxes and checkboxes.

This even occurs when looking at the inbuilt /admin/content screen.

I can't really expect the user to sort and page the table, and then enter textbox values. And sorting and paging is pretty standard functionality. Is there anyway around this?

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

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


Drupal 6 - create second contact form with redirect after submitting I was asked to add to existing Drupal 6 page second contact form.
What I mean by second:
On the site there is site wide contact form that's available at www.site.com/contact but what I need to add is a second contact form but with some custom fields.

I only need 2 fields: name and suggestion.
Also I would like to have custom message after form submit.

So the user navigates to page www.site.com/contact/question. User enters name and suggestion, then clicks submit and user will redirected to page showing thank you message, this can be at the same address, not necessary a redirect.
On server site I just need to send form content to specific email address. No tables, reports, simple email.

It would be nice not to install any additional modules, but if they are really necessary then that's fine.

Site is bit old and I am afraid that installing new modules will create issue.

There is a module called webforms, but can I achieve my goal without additional modules?

I think that you need to install the Webform module:

http://drupal.org/project/webform

There might be ways to do this with the Rules module, but I think for overall simplicity, Webform is the way to go.

I'm pretty sure that the version for Drupal 6 allows a custom message to be displayed to the user. In fact, if memory serves, it also has the option to redirect to a particular page.


Do purchased themes need to be fully built from the ground up? Really naïve newbie question....

I am brand new to Drupal after working in Wordpress for quite a while.  We bought a custom agricultural theme for $75 - it looked perfect for my project at work.  The sample had all the right stuff with content placed in areas I can customize to my project.

However, now that I have downloaded it, it is just "bare bones."  The structure for the content and images is nowhere to be found.  The drop-down menu isn't horizontal, the whole structure is absent. I thought this would be easier.  Do I have to build everything in Dreamweaver? Did I miss something? Are the themes merely "suggested formats?"

where did you buy the theme from? Do they provide installation instructions or usage instructions? Did it ship with any additional modules to enable configuration?

A theme is basically styled blocks, views, nodes, regions. You need to place your content into Regions of the theme for it to show up like their example.


Remove confirmation page in Drupal Installation Profile I'm doing some maintenance on a an installation profile I wrote for my small team. One of the annoyances that I am trying to remove is the confirmation page after the install is finished ("Congratulations! You have successfully installed Drupal"). Is there any to skip this page if the install is successful?

So far, the core install_finished function, seems to be the only thing I can find that actually handles this step. But I'd rather not kill kittens over this : )

I've never tried it but the docs for hook_install_tasks_alter() suggest it's possible since install_finished() it one of those tasks

Alter the full list of installation tasks.
Parameters
$tasks: An array of all available installation tasks, including those provided by Drupal core. You can modify this array to change or replace any part of the Drupal installation process that occurs after the installation profile is selected.

So in theory you should be able to replace the function for that entry with one that performs a redirect instead
function MYPROFILE_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_finished']['function'] = 'MYPROFILE_install_finished';
}

function MYPROFILE_install_finished(&$install_state) {
  // install_finished() still needs to run but we can discard the output.
  install_finished($install_state);
  drupal_goto('<front>');
}


How do I include the main navigation block twice? How can I put one block, for example the main navigation block, in two different regions. In Drupal 7 this was possible through the Menu Block module, but as this module won't be ported to Drupal 8, I guess there is an other method.

This functionality is present out of the box in Drupal 8. You can actually place the same block multiple times in different regions.

For adding a block multiple times:

Go to Admin -> Structure -> Block layout (/admin/structure/block).
Click on "Place block" button besides the region name.
Select any block you wish to add to that region.

Follow the same steps to add block to a different region.


How do I control the file appearance using File Entity? By installing File Entity module I was hoping to be able to control the way all file items are rendered, for instance I need: file rendered as a link wrapped inside an <li> element, or a link with a given class to force display: block. I must say I have now more disorder among the widget, formatters and displays than I used to have before, and I can see no way to control the markup.

Please shed light on me, I assume it's my ignorance rather than the module imperfection. Thanks.

Since I've been no longer into Drupal for a long time now, I'm even not sure I remember the answer. But I managed to dig up the code below which smells like an answer @digitgopher asks for. So FWIW, and sorry for somewhat messy comments hanging around:

<?php

/**
* Implements hook_field_formatter_info().
*/
function fileformatter_field_formatter_info() {
  return array(
    'fileformatter_formatter' => array(
      'label' => t('File Formatter'),
      'field types' => array('file'),
      'settings' => array(
        'link_text' => '',
      )
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function fileformatter_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state){
  //This gets the view_mode where our settings are stored
  $display = $instance['display'][$view_mode];

  //This gets the actual settings
  $settings = $display['settings'];

  //Initialize the element variable
  $element = array();

  //settings
  $element['link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Link text'),
    '#description' => t('The text to appear next to icon. Leave empty for raw file name. Possible tokens: %fn = file name, %fd = file description, %cp = node title'),
    '#default_value' => $settings['link_text'],
  );

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function fileformatter_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();

  $summary = t('will be labeled ');
  $summary .= ($settings['link_text'] == '') ? t('using file name') :  $settings['link_text'];

  return $summary;
}

/**
 * Implements hook_field_formatter_view().
 */
function fileformatter_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  $settings = $display['settings'];

  foreach ($items as $delta => $item) {
    $html = '';

    // LINK TEXT
    $link_text = ($settings['link_text'] == '') ? $item['filename'] : check_plain($settings['link_text']);

    /* if (module_exists('token')) {
      $link_text = token_replace($settings['link_text'], array('node' => $entity));
    } else { */
      $link_text = str_replace('%fn', $item['filename'], $link_text);
      $link_text = str_replace('%fd', $item['description'], $link_text);
      if($entity_type == 'node'){
        $link_text = str_replace('%cp', $entity->title, $link_text);
      } else {
        $link_text = str_replace('%cp', '', $link_text);
      }
    // }

    // last resort, so to not allow for empty links
    if($link_text == ''){
      $link_text = $item['filename'];
    }

    // ICON - as CSS class background, which reduces file requests and allows for easier vertical-alignment
    $dashed_mime = strtr($item['filemime'], array('/' => '-'));
    /* // img method:
      $icon = theme('file_icon', array('file' => file_load($item['fid']), 'icon_directory' => drupal_get_path('module', 'file') . '/icons'));
      $icon_html .= '' . $icon . '';
    */

    // LINK MARKUP
    $url = file_create_url($item['uri']);
    $link_options = array(
      'html'        => TRUE,
      'attributes'  => array(
        'title' => $item['filename'],
        'class' => 'file file-formatted ' . $dashed_mime . ' file-fid-' . $item['fid'],
        'type' => $item['filemime'] . '; length=' . $item['filesize'],
        'target' => '_blank',
       ),
    );

    $html .= l($link_text, $url, $link_options);

    $elements[$delta]['#markup'] = $html; // Assign it to the #markup of the element
  }
  return $elements;
}


Where do I put a custom function for multiple themes I have two 2 themes so two template.php. I have a function that I use in both themes. I don't want to write it twice.
Where do I put it ?

You can put it in a module, or set up your themes so that they are sub themes of a main theme.


Display list of users with a specific role to guest users Some users on my Drupal 8 site have the role of 'Champion'. I have created a views block that lists out all the users with this role. It shows the list correctly when I am logged in as an admin, but does not display any results to guest users. It appears that the 'View user information' permission, which I have assigned to guest users does not allow viewing of user's roles ( I can see why from a security point of view).

Can anyone suggest how I can get this list of users to display for guest (unauthenticated) users? Either how I could override the permissions, or another approach?

Please check this setting, Also check the user permission.


Migration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column I'm trying to migrate user's content profiles (Drupal 6) to Profile2's profiles (Drupal 7) using the example from http://grasmash.com/article/migrate-classes-content-profile-profile2. When I try importing, I get the following error:

  Migration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ctp.field_titul_pred_jmenem' in 'field list'

This is the migration class.

class SkipProfile2Migration extends Migration {
  public function __construct() {
    parent::__construct();
    $this->description = t('Migration of content profile into profile2 entities');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'nid' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => 'D6 Unique Node ID',
          'alias' => 'n',
        )
      ),
      MigrateDestinationNode::getKeySchema(),
        'default'
    );
    $query = Database::getConnection('default', 'legacy')
      ->select('node', 'n')
      ->fields('n', array('nid', 'vid', 'type', 'language', 'title', 'uid', 'status', 'created', 'changed', 'comment', 'promote', 'moderate', 'sticky', 'tnid', 'translate'))
      ->condition('n.type', 'profile', '=');
    $query->join('skip' . '.node_revisions', 'nr', 'n.vid = nr.vid');
    $query->addField('nr', 'body');
    $query->addField('nr', 'teaser');
    $query->addField('nr', 'format');
    $query->join('skip' . '.users', 'u', 'n.uid = u.uid');
    $query->addField('u', 'name');
    $query->leftJoin('skip' . '.content_type_clovek', 'ctp', 'n.nid = ctp.nid AND n.vid = ctp.vid');
    $query->addField('ctp','field_titul_pred_jmenem');
    $query->addField('ctp','field_krestni_jmeno');
    $query->addField('ctp','field_prijmeni');
    $query->addField('ctp','field_titul_za_jmenem');
    $query->addField('ctp','field_telefon');
    $query->addField('ctp','field_email_source');
    $query->addField('ctp','field_ulice');
    $query->addField('ctp','field_cislo_popisne');
    $query->addField('ctp','field_sidlo');
    $query->addField('ctp','field_smerovaci_cislo');
    $query->addField('ctp','field_funkce_cloveka');
    $query->addField('ctp','field_pracoviste');
    $query->addField('ctp','field_stat_iso');
    $query->orderBy('n.nid', 'ASC');

    $source_fields = array(
      'nid' => t('The node ID of the page'),
      'uid' => t('The user ID of a user'),
      'lid' => t('The location ID of a location instance'),
    );

    // Create a MigrateSource object, which manages retrieving the input data.
    $this->source = new MigrateSourceSQL($query, $source_fields);
    $this->destination = new MigrateDestinationProfile2('clovek');

// FIELD MAPPINGS    ...

Can anybody help me, please?

On Drupal 6 running CCK, the database field names are different from the CCK field names.

In my test site running Drupal 6, I created the following CCK fields:

field_code_page (text)
field_co_author (user reference)
field_book_list (node reference)

The database table created from CCK for the content type containing those fields has the following database fields:

field_code_page_value
field_co_author_uid
field_book_list_nid

It is rather probable the database field is named ctp.field_titul_pred_jmenem_value. To be sure, you should check the database table, as the database field could have a different name, basing on the type of the CCK field.


Add a calculated column programmatically using views data export I am using the views data export module with Drupal 8. I have a view that shows a list of users and the desired columns to be exported to the csv are:

Name
Trained
Status

Unfortunately, both of the Trained and Status columns are calculated through a semi-complex method from my module. Using the calculated field module isn't really an option.
Ideally my csv should look something like the below. The "Trained" and "Status" columns would be calculated by running the user_id through their respected methods:
Name | Trained | Status
user_name_1 | is_trained(user_id_1) | get_status(user_id_1)
user_name_2 | is_trained(user_id_2) | get_status(user_id_2)
...

I have tried what I feel is every combination of views pre_render, post_render, post_execute, etc...; however, I just can't seem to find a way to add a calculated value to the row. It is possible I am approaching this wrong but any suggestions on how to accomplish this would be appreciated.

I am going to go ahead and answer my own post to help anyone else out.
A simple way to do this for me was to write a views plugin as suggested in the comments.
Here is a great link to walk you through this: https://www.webomelette.com/creating-custom-views-field-drupal-8
I do not feel I can write any explanation better than what is done in this article so I would jump over there for more information.


How to reference a specific field? I need to link/sync a paragraph with another field on the parent node of this paragraph.

Background:

All my nodes have some node-type-specific fields for strict-structured data (e.g. a product node has product image & price; a location node has a geolocation field). All nodes share one huge, repeating paragraph "generic content" field with a lot of paragraph types for unstructered data (marketing texts, emotional images, bullet points,...). Basically that paragraph is used as a sort of site building tool.

Requirement:

I now need to display the node's structured data fields within the "generic content" paragraph field, so that editors can mix and move the structered content with the generic content paragraphs.

Didn't work:

My initial idea was to create a paragraph with an entity reference to field types where editors could select the basefield. However, that didn't really work because I can't limit the autocomplete to fields of the current node, leading to a unusable list with a lot of invalid entries.

Question:

Is there any way to create references to fields within a node? It has to be a mouse- and editor-friendly solution, my editors are trained in the Drupal Admin, but they have no access to code.

Technically, you could add a reference field to field config entities. But you can't limit the options there and I'm sure you don't want to allow all the fields, and you need custom theming logic for this anyway. That would just allow you to select the field name.

You can't link to a field value, the combination of entity and field doesn't have its own identifier.

If I understand you correctly, then the simplest option is to make a custom list field with allowed values like this:

field_name_a|Field A
field_name_b|Field B

With as many fields as you need. You could also register a allowed options callback and try to dynamically limit the options based the current page/node type, but that's a bit tricky.

Then you need custom logic in preprocess/twig templates for that paragraph type that gets the value for the selected field from the parent of the paragraph and renders it


how to print value of a taxonomy field to headline with node.html.twig? field_test1 is a taxonomy field like fields_tags.

{{ content.field_test1 }} prints the title and the value (not in teaser - why not?).
I only want the value and want to print it in the header of the node before {{ label }}.

{{ content.field_test1.value }} or {{ node.field_test1.value }} don't work.

{{ node.field_example.value }} seems to work only for "usual" fields, but not for taxonomy fields.

How to do that?

(I've read the book of Chaz Chumley, but found no solution. I've got an answer of 4k4 in another thread, but I didn't understand. Therefore I've clarified my question here.)

That's because a taxonomy field has no values. It contains entities, which are the referenced terms. You get the first term with .entity and then you can get the values inside of the term, for example if the term would have a field_test2:
{{ node.field_test1.entity.field_test2.value }}

Or simply the term label (no .value needed for this):
{{ node.field_test1.entity.label }}

If you need translation use the |translation filter of the module Twig Tweak.


CCK doesn't find the Image module on Drupal 7 After successfully migrating from Drupal 6 to Drupal 7, I wanted to migrate my CCK fields to core fields. I downloaded CCK for Drupal 7, and its field migrate module.

However, for all of my image fields, I got this error:

  Missing field module: 'image'. This field cannot be migrated.

What is that module 'image' that is missing? There is no more imagefield for Drupal 7, as it is supposed to be part of core.

Actually, the Image module is part of Drupal core. Enable it, and the error should vanish.

If you don't find the module listed between the modules, then you need to copy the Drupal files again on your server.

If the Image file is already present in your web server, it is enabled, and CCK keeps saying it cannot find the module, then open an issue report for CCK.


Devel's dpm needs two refreshes to display message from (pre)process I use Zen and have copy/pasted the STARTERKIT to my foo template.
Devel is enabled with the "Rebuild the theme registry on every page load" setting on.

In my completely empty template.php I type in the following and save:

function foo_process_node(&$variables, $hook) {
    dpm('test');
}

I then do drush cc all and refresh page. The message is not shown. If I refresh again the message shows.

If I change test to foobar on the 1st refresh I get the old test and on the second I get foobar.

Why does this happen and how can I avoid it?

Note that this lagging behavior is the same for preprocess and process but not there if I print the message from the foo_page_alter(&$page) function.

This is a common issue people encounter when themeing Drupal (it used to drive me crazy).

In basic terms what's happening is that the messages held in the $_SESSION super global have already been committed to the page by the time the template file containing your call to dpm() is invoked.

This means that the messages are added to the $_SESSION but aren't dumped out to the messages area until the next page...as $messages has already been set up for/printed in page.tpl.php.

The normal way to get around this is to invoke the dpm() at an earlier stage of the process, like in hook_page_alter() as you mention, or hook_node_view(), etc.

Also I think if you implement your preprocess hook at the module level, rather than the theme level, that your calls to dpm() will happen in time for the messages to be displayed in that particular page request.


Customized Search Results Page I'm seeking some help to better understand how to go about creating a custom search results page.  I've created search views and facetted search, but they really aren't what we are needing.  We are consolidating 4 indexes into one streamlined Drupal account and are needing our search to display results grouped by content type (basic filtering)...we were able to do this in search api (views) but we are also needing to display certain content a specific way.  For instance, images should have a thumbnail with no title.  Other pieces of content should just list the title name.  Here is an example of the search we're trying to replicate:  http://www.retrometrookc.org/. (Search for, e.g., belle isle.)

In theory this seems really simple but I can't seem to wrap my head around it.  If anyone has any suggestions or recommendation, I really would appreciate it!

It sounds like you are almost there but without writing custom templates for each content type I would look at display suite. That way, when you click manage display for each different content type you can choose "custom display settings" and then "search result". This will let you build a different layout for each different content type as a search result (and if you like eventually build your own template files easily based on display suites templates).

Then you go back to your view and choose "Show: Display Suite -> Search Result" and each result will be shown as you have set up in the manage display screen for that type. You can still use all the filters and sorts as you like.


How to create a Drupal calendar with 2 digits (day date format) instead of 1? Does anybody have experience with adding a 0 before the numbers 1 to 9.
After this my calendar numbers should all have 2 digits: 01,02,03,04,05,06,07,08,09,10,11...

I have added a new PHP date format ("d") and that should give 01 instead of 1 (according to the PHP manual).

But I don't know how to implement this in my calendar.

At first you should add a date format on that page admin/config/regional/date-time/formats/add.

For example this format (F d, Y) gives you that result: September 9, 2015.

Then you can use it anywhere on your site.


programmaticaly extract the shipping service name Through following code in a custom sub module for commerce_cybersource_sawm I am able to pass shipping information to merchant like name, address, country

$shipping_address = $order_wrapper->commerce_customer_shipping->commerce_customer_address->value();
 if (!empty($shipping_address['first_name'])) {
    $form['ship_to_forename'] = array(
    '#type' => 'hidden',
    '#value' => $shipping_address['first_name'],
  );
}

I want to know how can we extract the shipping service name. Since I have Free Shipping and Standard Shipping which I want to pass to the merchant.

I am not a developer, just found a code sample from @googletorp on the link below. Just modified that and got the result.

https://www.drupal.org/node/1555994#comment-5963680

    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    if ($line_item_wrapper->type->value() == 'shipping' ){
    $form['merchant_defined_data6'] = array(
    '#type' => 'hidden',
    '#value' => $line_item_wrapper->commerce_shipping_service->value(),
  );

  break;
  }
}


'Search Form' block I would like to add a link called "Advanced Search" below the existing Search box Within our 'Search Form' block I would like to add a link called "Advanced Search" below the existing Search box.  One possible way of implementing this would be to utilize hook_block_view_alter or hook_block_view_MODULE_DELTA_alter within a custom module and then add this new link to the bottom of this block.
Is this the best way to add this link to the 'Search Form' block?

You could either use the hook_block_view_alter to add the link, just like you say. Or you can implement the search-block-form.tpl.php in your theme and add the link in the template file.


Migrate text field with multiple values I've got a simple Text field which allows 2 values, let's call it field_text. My source database has two columns, let's say text1 and text2.

I want to set my migrate field mapping so that text1 is used as the first value for field_text and use text2 as the second value for field_text.

In other words, something like this:

$this->addFieldMapping('field_text[0]', 'text1');
$this->addFieldMapping('field_text[1]', 'text2');

You should implement prepareRow() method in your migration class. Inside prepareRow() you can read both source fields and add them to an array.
I will provide an example:

public function prepareRow($row) {
  $row->text1 = array($row->text1, $row->text2);
}

Now your source field "text1" will contain both values and it can be mapped to "field_text". "text2" has to be set to DNM (do not map).


WYSIWYG CKEditor config.js not being used? I've installed and configured the WYSIWYG module (latest dev) to use CKEditor, and I have downloaded the latest version of CKEditor (latest full release) to sites/all/libraries.  I'm able to use the editor.

I need to customize a few additional things, so I'm applying configuration changes to config.js in sites/all/libraries/ckeditor/config.js.  However, it seems like this file is not even being used or read at all.  I tested this hypothesis by adjusting the stock config.js as so:

CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here. For example:
    config.allowedContent = true;
    alert('Hello!');
};

alert('World!');

Whenever I load the editor, I would expect to get either one or two alerts, one saying either Hello! or World! or both.  However, no alert windows are launched.

How does one customize the configuration of CKEditor when using the WYSIWYG module?

This took some research, but I found this article which describes how to do it.

The meat of the article is the following hook, which defines a custom config file:

<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter()
 */
function MODULENAME_wysiwyg_editor_settings_alter(&$settings, $context)
{
    // The $context variable contains information about the wysiwyg profile we're using
    // In this case we just need to check that the editor being used is ckeditor
    if ($context['profile']->editor == 'ckeditor')
    {

        // The $settings variable contains all the config options ckeditor uses.
        // The array keys correspond directly with any setting that can be applied
        // to CKEditor - as outlined in the CKEditor docs:
        // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
        // Another way to override configuration is to use your own configuration javascript
        // file. In this case, we're going to add our own configuration file that will
        // Hold our stylesSet customizations...
        $settings['customConfig'] = base_path() . drupal_get_path('module', 'MODULENAME') . '/ckeditor_custom_config.js';
    }
}


Is there a way to create a hotel roommate system for a conference? I will host a conference but the hotel room rate is very expensive.  I am thinking of possible to create a system in drupal that allow registers to find a roommate to share a hotel room.

I saw the Room module, but I don't think this is what I am looking for.

There is no off-the-shelf module to do this, but you could set something up with a custom Room share request content type and then Rules and Entity Reference to handle the scheduling and assignments.  Combining Rules, fields (via content types), and entity references should be flexible enough to handle such a workflow but it will require a little work to set up and may be too much work in your case.

Unless this is a huge conference, you might just go with the built-in forum module and allow users to post to the forum if interested and sort things out themselves.  It requires very little set up and that way if your users don't actually use/need the feature then you won't waste time developing it.


Drush and multisite config I have a new multisite instance with the Backup & Migrate module installed in /sites/all/modules/

When I run drush the bam-* commands don't show as available commands.

I have site aliases set up and if I run drush @site-alias bam-destinations as a test it does show the available backup destinations.

Is there a more correct way to show the list of available commands for all sites as well as site-specific commands?

Did you try drush @site help?  Simply running drush help will show only the globally-available commands; you must change your working directory to the folder with your settings.php file or use a site alias to select a specific site to see the help for drush commands defined in that site's module.

Sometimes, the Drush command cache can get in your way.  Run drush cc drush to reset it.  Since drush @site bam-destinations is working, this is probably not your issue.

If you are still having trouble after trying these things, also try upgrading to the latest version of Drush (HEAD of master), as some fixes that may be related have been committed post-Drush-5.4.  Also try drush @site help bam-destinations and drush @site bam-destinations --help.  If you're still having trouble, please post a bug report in the Drush issue queue.


How can I use 'xx time ago' as date format? How can I use 'xx time ago' for date format in Drupal 8 nodes ?

I want to replace "xx time ago" with {{ date }} in node.

In Drupal 7 it worked with this code :

<?php
 print format_interval(time()-$node->created);
?>

There are two ways to tackle this.
One is to just use the field formatters.  If you have a DateTime field, just goto Manage Display, and change the Format to Time ago.  Then click the gear, and pick some options.  These are cache aware that will bubble up through the page, but you may end up with short cache lifetimes in some situations.
The other is to use a template_preprocess_node().  This is preferable when you have a timestamp that isn't a field.  Then you use the date formatter service to render out the timestamp in timeago format.  It is preferable to use the formatDiff() versions rather than formatInterval() (while not formally deprecated, it is discouraged).
function MYTHEME_preprocess_node(&$variables) {
  /** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
  $date_formatter = \Drupal::service('date.formatter');
  $request_time = \Drupal::time()->getRequestTime();
  $variables['foo'] = $date_formatter->formatDiff($request_time - 12345, $request_time, [
    'granularity' => 3,
    'return_as_object' => TRUE,
  ])->toRenderable();
}

When you specify 'return_as_object' => TRUE with the formatDiff() functions, a FormattedDateDiff object gets returned, which contains the formatted string as well as a mostly accurate [#cache]['max-age'] entry in a render array to make this work with Drupal 8's new caching system.  Then you can just use {{ foo }} in your Twig template; the render engine will do the right thing with the render array instead of a plain string.
Also read the docs on DateFormatterInterface for the formatTimeDiffSince() and formatTimeDiffUntil() variants, and for the $options you can pass in.


Not validating required validation drupal_validate_form is not validating required validation when i was creating a node programatically .

Can any one say, it is design like that or am i doing something wrong .

        $node_form = (object) array(
            'type' => 'MY_CONTENT_TYPE',
            'language' => LANGUAGE_NONE,
        );
        $form = drupal_get_form('application_node_form',$node_form);
        $old_fs = @unserialize($r->form_state);
        $form_state = array();
        $form_state['values'] = $old_fs['values'];
        $form_state['values']['op'] = t('Save');
        $form_state['submitted'] = 1;
        $form_state['complete form'] = array();
        $form_state['triggering_element'] = array('#parents'=>array('next'),'#button_type'=>'submit');
        unset($form['#token']);
        drupal_validate_form('MY_CONTENT_TYPE_node_form', $form, $form_state);

You can check if the form failed validation by calling form_get_errors

You could try using drupal_form_submit instead, which I think will also validate the form (seen via form_get_errors)


Add theme settings field to theme-settings.php in d8 is not working for me I followed the documentation on drupal.org to add a field to the theme-settings.php but there must be a mistake in code.

I have a filed called advertisement and a theme called tv so I tried to copy and paste the code and altered the names where to alter theme the files I created in particular are as follows:

/themes/tv/templates/system/thme-settings.php

#}
function tv_form_system_theme_settings_alter(&$form,
\Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  // Work-around for a core bug affecting admin themes. See issue
 #943212.
  if (isset($form_id)) {
    return;

$form['tv_advertisement'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Widget'),
    '#default_value' => theme_get_setting('tv_advertisement'),
    '#description'   => t("Place this text in the widget spot on your
 site."),
  );
}
$tv_advertisement = theme_get_setting('tv_advertisement');

in /themes/tv/config/install/tv.settings.yml I put this:

tv_advertisement: blue bikeshed

My /themes/tv/tv.theme file contains:

<?php
/**
 * @file
 * Theme functions
 */

// Include all files from the includes directory.
$includes_path = dirname(__FILE__) . '/includes/*.inc';
foreach (glob($includes_path) as $filename) {
  require_once dirname(__FILE__) . '/includes/' . basename($filename);
}

 function tv_preprocess_node(&$variables) {
 $variables['tv_advertisement'] =
 theme_get_setting('tv_advertisement');
 }

The last thing I did was

drush cr

to clear the cache

When I go to the themes settings page there are only the default fieds displayed but the new one does not show up

If anyone has a clue what I am doing wrong and is able to enlighten me I would be very pleased.

Thank you

Try to remove this code:

  if (isset($form_id)) {
    return;

The hook interface of hook_form_system_theme_settings_alter is hook_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state).

You can remove the third parameter:

 $form_id = NULL


memory available to drush If one allocates additional memory to drush in drushrc.php or drush.ini (am I correct that these are potentially valid options on a shared server?), is there a way to confirm that this amount is actually allocated when running drush?

Try:

$ drush ev 'print ini_get("memory_limit");'

This should print the memory_limit value set for Drush.  -1 means no limit.


How do I format a picture field as raw source url in a view I have a view of users, I'm displaying a number of fields, I want to output the path to the image, without rendering any of the html around it, I cant seem to figure out how to do this.

I found that "there's a module for that", Image URL Formatter:

  This module add a url formatter for image field. Then you can output
  image url directly.


Views, adding I like, Retweet - best approach I have several views.

Now I need to add FB I like and retweet button to those views.

I search for modules, but all I get doesn't goes with Views well.

I would like to pass nid of node as excluded field and use Views Custom Field to create those links, but is this possible to get data from another field in custom field?

I also searched for modules that would allow Social Sharing - what I ended up doing was just adding the code manually to the templates.  It's just a couple lines of javascript, usually.  I ended up using AddThis for the main group and then just pulled the Facebook like code from their website.

IMO, somtimes a module is overkill.


How to show more terms in the "Parent terms" select list when adding taxonomy term? When adding terms to a taxonomy vocabulary, the "Parent terms" scrolling selector list in the "RELATIONS" section only displays 4 items. When dealing with large, complex, hierarchical taxonomies, this makes it difficult and slow to find the parent (a similar complaint and another).

I would love to be able to use something like the Simple hierarchical select or Client-side hierarchical select widget there, but assuming that's not currently possible, how can I simply display a longer list to make the selection a bit easier?

I am guessing there is a file somewhere containing a setting of "4" (unless that's a default) that I would able to increase to "20" for example. I hunted but couldn't find it.

I'd be interested in an answer, even if it would be a core hack that I would have to redo with each update.

Edit: It seems, from this link, that one solution may involve adding code such as this:

<?php
function MyModuleName_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $form['relations']['parent']['#size'] = '20';
  }
}

But where to add it? Or perhaps in a custom module (called MyModuleName)? Perhaps in MyTheme.theme? Or perhaps in a twig file such as html--admin--structure--taxonomy--manage--MyVocabularyName--add.html.twig?

OK Nick, you need to add the 'hook' into a custom module..
so for drupal 8 if you do not have a custom module follow the documentation here
https://www.drupal8.ovh/.../create-a-simple-module-for...
https://www.drupal8.ovh/.../create-a-simple-module-to-use...

In 'modules' folder create a custom folder 'custom' to hold your custom modules.
path should be ...modules/custom
inside this create a folder folder to hold your custom module my_custom_module ( orwhatever you want to call it )
path should be ...modules/custom/my_custom_module

inside this folder (my_custom_module) add a 'my_custom_module.info.yml' file in this file add

name: My custom module
description: My custom module description
package: Custom

type: module
core: 8.x

run drush en my_custom_module -y
or in admin/modules enable the module

once enabled add a .module file to the my_custom_module folder, called my_custom_module.module (or whatever you have called it)

in this file you can add the hooks you want to use for your one it will be

<?php
function my_custom_module_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'taxonomy_term_vocabulary_name_form') {
$form['relations']['parent']['#size'] = '15';
}
}

change the my_custom_module to whatever you have called your module
change the section of the form id == vocabulary name to the name of the vocab you have created, you may need to inspect this and find it the form id! mine matched the vocab

clear the cache, go to your vocabulary and add a new term ! fingers crossed the size of the selct box has changed

think this covers it all, good luck


How to create a main menu with dropdown? I want to create a main menu with dropdown. There will be collapsed links in each menu heading. When the user hovers over one heading, links accompanied by that header will be displayed in a box.

I first tried to add node and give them parent nodes. For example, I have created a node with title called "Lorem" and created another with title called "Ipsum". I have provided both of them a menu link. I have set the "Lorem" node as the parent node of "Ipsum". But it seems like "Ipsum" doesn't appear in "Lorem"'s content of its menu link.

Is there any way to look up the links' child elements? For example:

dpm($main_menu);

This doesn't yeild me neither the link that connected to "Ipsum" or the "Lorem"'s child links. How can I see the "Lorem"'s child link? Or where it is?

If I can find it, I can override the theme_links and create dropdowns.

You need to use any of this module

Nice Menus

  Nice Menus enables drop-down/right/left expandable menus. It uses only
  CSS for most browsers, with minimal Javascript for IE6.

Superfish Menu

  You will see several blocks called Superfish", move any of them to a
  region, use the "Configure" link of the block to configure it
  accordingly to your needs, and save.

Responsive Dropdown Menus

    Responsive Dropdown Menus provides a new menu tree rendering to make
    responsive, drop-down enabled main menu possible on any theme.

Provides new menu blocks for each menu.
All module blocks add dropdown menu support and responsive menu toggles.

Megamenu

  Mega menus are a type of drop-down, which seeks to overcome some of
  the usability drawbacks of traditional drop-downs. Hierarchy of your
  navigation is made visible all at once and the amount of clicking,
  searching, and navigating is reduced.


How do I get template updates to show I'm sure this is a very simple fix, but I'm new to Drupal and would be very appreciative if someone could help. I have a theme that I am using on a Drupal site. I make some changes to the underlying text in the themes PhP files (e.g. "Page not found" -> "Page is not found!"). I then reload the page and I do not see the changes on the site. I have tried clearing Drupal's cache and then reloading, but this also doesn't seem to help. After I make changes to a theme, how do I get them to show up on the site?

The symptoms you describe is usually due to some caching happening. Make sure you've turned off all caching in Drupal (sometimes, just clearing the cache isn't enough). Also, make sure that you clear your browser's cache (SHIFT+reload).


Getting a list of altered fields when saving a node I need to trigger some logic to recalculate certain computed fields based on what fields may have been altered when a user updates a node. So I'm looking to create a function that returns a list of of fields the user has updated.

I've come pretty far by using hook_node_update().

Currently the process is like this.

My hook_node_update looks roughly like this:

function hook_node_update($node) {
  $old_node = node_load($node->nid);

  // Figure out what fields have been altered.
  $altered = _get_altered_fields($node, $old_node);

  // Recalculate the fields *after* node save.
  drupal_register_shutdown_function('_process_fields', $node, $altered);
}

And the _get_altered_fields function:

function _get_altered_fields($node, $old_node) {

  $changed = array();

  if ($old_node-> field_somefield != $node-> field_somefield) {
    $changed[] = 'somefield';
  } elseif ($old_node-> field_someotherfield != $node-> field_someotherfield) {
    $changed[] = 'someotherfield';
  }

  return $changed;
}

The problem with the above is that I get 'false positives' (i.e. 'someotherfield' gets registered as changed even though it is not) because the $node object does not have the exact same data structure as $old_node, which was fetched from the database. In general $node has more attributes - especially if it is a taxonomy field - such as 'vid', 'weight' and 'rdf_mapping'.

I tried creating a normalize function where I unset those attributes, but it gets very messy. I figure someone must have done this before me. Any suggestions how to do this in a clean way?

The simple way of recalculating and update field without any effect of other field is hook_entity_update or code like display here.

<?php
$entity_instance = entity_load('entity_name', array($id));
$entity_instance->field_myfield[LANGUAGE_NONE][0]['value']= 5;
$entity_instance->save();
?>


"[node:flag-vote-count]" displays the token name, not the number I have a problem in the Flag module with the [node:flag-vote-count] token. I googled for a solution, but I couldn't find one.

On my content page, the Flag module displays the token name (i.e. [node:flag-vote-count]) on the node creation preview page, instead of a number.

I am putting the token on the Flag -> Edit -> "Flag link text" field. Meaning inside the flag itself. [node:title] is working perfectly fine there.

Someone can help me here?

OK , so I solve it.

The [node:flag-vote-count] is really not working.
But you can look for another count token for the flag you created, under the TOKEN REPLACEMENT -> nodes.

Good luck :)